1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 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 semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex 32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex 33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex 34 #include "clang/Parse/ParseDiagnostic.h" 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/Template.h" 44 #include "llvm/ADT/SmallString.h" 45 #include "llvm/ADT/Triple.h" 46 #include <algorithm> 47 #include <cstring> 48 #include <functional> 49 using namespace clang; 50 using namespace sema; 51 52 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 53 if (OwnedType) { 54 Decl *Group[2] = { OwnedType, Ptr }; 55 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 56 } 57 58 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 59 } 60 61 namespace { 62 63 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 64 public: 65 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false, 66 bool AllowTemplates=false) 67 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 68 AllowClassTemplates(AllowTemplates) { 69 WantExpressionKeywords = false; 70 WantCXXNamedCasts = false; 71 WantRemainingKeywords = false; 72 } 73 74 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 75 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 76 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 77 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 78 return (IsType || AllowedTemplate) && 79 (AllowInvalidDecl || !ND->isInvalidDecl()); 80 } 81 return !WantClassName && candidate.isKeyword(); 82 } 83 84 private: 85 bool AllowInvalidDecl; 86 bool WantClassName; 87 bool AllowClassTemplates; 88 }; 89 90 } 91 92 /// \brief Determine whether the token kind starts a simple-type-specifier. 93 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 94 switch (Kind) { 95 // FIXME: Take into account the current language when deciding whether a 96 // token kind is a valid type specifier 97 case tok::kw_short: 98 case tok::kw_long: 99 case tok::kw___int64: 100 case tok::kw___int128: 101 case tok::kw_signed: 102 case tok::kw_unsigned: 103 case tok::kw_void: 104 case tok::kw_char: 105 case tok::kw_int: 106 case tok::kw_half: 107 case tok::kw_float: 108 case tok::kw_double: 109 case tok::kw_wchar_t: 110 case tok::kw_bool: 111 case tok::kw___underlying_type: 112 return true; 113 114 case tok::annot_typename: 115 case tok::kw_char16_t: 116 case tok::kw_char32_t: 117 case tok::kw_typeof: 118 case tok::annot_decltype: 119 case tok::kw_decltype: 120 return getLangOpts().CPlusPlus; 121 122 default: 123 break; 124 } 125 126 return false; 127 } 128 129 /// \brief If the identifier refers to a type name within this scope, 130 /// return the declaration of that type. 131 /// 132 /// This routine performs ordinary name lookup of the identifier II 133 /// within the given scope, with optional C++ scope specifier SS, to 134 /// determine whether the name refers to a type. If so, returns an 135 /// opaque pointer (actually a QualType) corresponding to that 136 /// type. Otherwise, returns NULL. 137 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 138 Scope *S, CXXScopeSpec *SS, 139 bool isClassName, bool HasTrailingDot, 140 ParsedType ObjectTypePtr, 141 bool IsCtorOrDtorName, 142 bool WantNontrivialTypeSourceInfo, 143 IdentifierInfo **CorrectedII) { 144 // Determine where we will perform name lookup. 145 DeclContext *LookupCtx = 0; 146 if (ObjectTypePtr) { 147 QualType ObjectType = ObjectTypePtr.get(); 148 if (ObjectType->isRecordType()) 149 LookupCtx = computeDeclContext(ObjectType); 150 } else if (SS && SS->isNotEmpty()) { 151 LookupCtx = computeDeclContext(*SS, false); 152 153 if (!LookupCtx) { 154 if (isDependentScopeSpecifier(*SS)) { 155 // C++ [temp.res]p3: 156 // A qualified-id that refers to a type and in which the 157 // nested-name-specifier depends on a template-parameter (14.6.2) 158 // shall be prefixed by the keyword typename to indicate that the 159 // qualified-id denotes a type, forming an 160 // elaborated-type-specifier (7.1.5.3). 161 // 162 // We therefore do not perform any name lookup if the result would 163 // refer to a member of an unknown specialization. 164 if (!isClassName && !IsCtorOrDtorName) 165 return ParsedType(); 166 167 // We know from the grammar that this name refers to a type, 168 // so build a dependent node to describe the type. 169 if (WantNontrivialTypeSourceInfo) 170 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 171 172 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 173 QualType T = 174 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 175 II, NameLoc); 176 177 return ParsedType::make(T); 178 } 179 180 return ParsedType(); 181 } 182 183 if (!LookupCtx->isDependentContext() && 184 RequireCompleteDeclContext(*SS, LookupCtx)) 185 return ParsedType(); 186 } 187 188 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 189 // lookup for class-names. 190 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 191 LookupOrdinaryName; 192 LookupResult Result(*this, &II, NameLoc, Kind); 193 if (LookupCtx) { 194 // Perform "qualified" name lookup into the declaration context we 195 // computed, which is either the type of the base of a member access 196 // expression or the declaration context associated with a prior 197 // nested-name-specifier. 198 LookupQualifiedName(Result, LookupCtx); 199 200 if (ObjectTypePtr && Result.empty()) { 201 // C++ [basic.lookup.classref]p3: 202 // If the unqualified-id is ~type-name, the type-name is looked up 203 // in the context of the entire postfix-expression. If the type T of 204 // the object expression is of a class type C, the type-name is also 205 // looked up in the scope of class C. At least one of the lookups shall 206 // find a name that refers to (possibly cv-qualified) T. 207 LookupName(Result, S); 208 } 209 } else { 210 // Perform unqualified name lookup. 211 LookupName(Result, S); 212 } 213 214 NamedDecl *IIDecl = 0; 215 switch (Result.getResultKind()) { 216 case LookupResult::NotFound: 217 case LookupResult::NotFoundInCurrentInstantiation: 218 if (CorrectedII) { 219 TypeNameValidatorCCC Validator(true, isClassName); 220 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 221 Kind, S, SS, Validator); 222 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 223 TemplateTy Template; 224 bool MemberOfUnknownSpecialization; 225 UnqualifiedId TemplateName; 226 TemplateName.setIdentifier(NewII, NameLoc); 227 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 228 CXXScopeSpec NewSS, *NewSSPtr = SS; 229 if (SS && NNS) { 230 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 231 NewSSPtr = &NewSS; 232 } 233 if (Correction && (NNS || NewII != &II) && 234 // Ignore a correction to a template type as the to-be-corrected 235 // identifier is not a template (typo correction for template names 236 // is handled elsewhere). 237 !(getLangOpts().CPlusPlus && NewSSPtr && 238 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 239 false, Template, MemberOfUnknownSpecialization))) { 240 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 241 isClassName, HasTrailingDot, ObjectTypePtr, 242 IsCtorOrDtorName, 243 WantNontrivialTypeSourceInfo); 244 if (Ty) { 245 diagnoseTypo(Correction, 246 PDiag(diag::err_unknown_type_or_class_name_suggest) 247 << Result.getLookupName() << isClassName); 248 if (SS && NNS) 249 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 250 *CorrectedII = NewII; 251 return Ty; 252 } 253 } 254 } 255 // If typo correction failed or was not performed, fall through 256 case LookupResult::FoundOverloaded: 257 case LookupResult::FoundUnresolvedValue: 258 Result.suppressDiagnostics(); 259 return ParsedType(); 260 261 case LookupResult::Ambiguous: 262 // Recover from type-hiding ambiguities by hiding the type. We'll 263 // do the lookup again when looking for an object, and we can 264 // diagnose the error then. If we don't do this, then the error 265 // about hiding the type will be immediately followed by an error 266 // that only makes sense if the identifier was treated like a type. 267 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 268 Result.suppressDiagnostics(); 269 return ParsedType(); 270 } 271 272 // Look to see if we have a type anywhere in the list of results. 273 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 274 Res != ResEnd; ++Res) { 275 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 276 if (!IIDecl || 277 (*Res)->getLocation().getRawEncoding() < 278 IIDecl->getLocation().getRawEncoding()) 279 IIDecl = *Res; 280 } 281 } 282 283 if (!IIDecl) { 284 // None of the entities we found is a type, so there is no way 285 // to even assume that the result is a type. In this case, don't 286 // complain about the ambiguity. The parser will either try to 287 // perform this lookup again (e.g., as an object name), which 288 // will produce the ambiguity, or will complain that it expected 289 // a type name. 290 Result.suppressDiagnostics(); 291 return ParsedType(); 292 } 293 294 // We found a type within the ambiguous lookup; diagnose the 295 // ambiguity and then return that type. This might be the right 296 // answer, or it might not be, but it suppresses any attempt to 297 // perform the name lookup again. 298 break; 299 300 case LookupResult::Found: 301 IIDecl = Result.getFoundDecl(); 302 break; 303 } 304 305 assert(IIDecl && "Didn't find decl"); 306 307 QualType T; 308 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 309 DiagnoseUseOfDecl(IIDecl, NameLoc); 310 311 if (T.isNull()) 312 T = Context.getTypeDeclType(TD); 313 314 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 315 // constructor or destructor name (in such a case, the scope specifier 316 // will be attached to the enclosing Expr or Decl node). 317 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 318 if (WantNontrivialTypeSourceInfo) { 319 // Construct a type with type-source information. 320 TypeLocBuilder Builder; 321 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 322 323 T = getElaboratedType(ETK_None, *SS, T); 324 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 325 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 326 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 327 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 328 } else { 329 T = getElaboratedType(ETK_None, *SS, T); 330 } 331 } 332 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 333 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 334 if (!HasTrailingDot) 335 T = Context.getObjCInterfaceType(IDecl); 336 } 337 338 if (T.isNull()) { 339 // If it's not plausibly a type, suppress diagnostics. 340 Result.suppressDiagnostics(); 341 return ParsedType(); 342 } 343 return ParsedType::make(T); 344 } 345 346 /// isTagName() - This method is called *for error recovery purposes only* 347 /// to determine if the specified name is a valid tag name ("struct foo"). If 348 /// so, this returns the TST for the tag corresponding to it (TST_enum, 349 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 350 /// cases in C where the user forgot to specify the tag. 351 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 352 // Do a tag name lookup in this scope. 353 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 354 LookupName(R, S, false); 355 R.suppressDiagnostics(); 356 if (R.getResultKind() == LookupResult::Found) 357 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 358 switch (TD->getTagKind()) { 359 case TTK_Struct: return DeclSpec::TST_struct; 360 case TTK_Interface: return DeclSpec::TST_interface; 361 case TTK_Union: return DeclSpec::TST_union; 362 case TTK_Class: return DeclSpec::TST_class; 363 case TTK_Enum: return DeclSpec::TST_enum; 364 } 365 } 366 367 return DeclSpec::TST_unspecified; 368 } 369 370 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 371 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 372 /// then downgrade the missing typename error to a warning. 373 /// This is needed for MSVC compatibility; Example: 374 /// @code 375 /// template<class T> class A { 376 /// public: 377 /// typedef int TYPE; 378 /// }; 379 /// template<class T> class B : public A<T> { 380 /// public: 381 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 382 /// }; 383 /// @endcode 384 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 385 if (CurContext->isRecord()) { 386 const Type *Ty = SS->getScopeRep()->getAsType(); 387 388 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 389 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 390 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 391 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 392 return true; 393 return S->isFunctionPrototypeScope(); 394 } 395 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 396 } 397 398 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 399 SourceLocation IILoc, 400 Scope *S, 401 CXXScopeSpec *SS, 402 ParsedType &SuggestedType, 403 bool AllowClassTemplates) { 404 // We don't have anything to suggest (yet). 405 SuggestedType = ParsedType(); 406 407 // There may have been a typo in the name of the type. Look up typo 408 // results, in case we have something that we can suggest. 409 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 410 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 411 LookupOrdinaryName, S, SS, 412 Validator)) { 413 if (Corrected.isKeyword()) { 414 // We corrected to a keyword. 415 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 416 II = Corrected.getCorrectionAsIdentifierInfo(); 417 } else { 418 // We found a similarly-named type or interface; suggest that. 419 if (!SS || !SS->isSet()) { 420 diagnoseTypo(Corrected, 421 PDiag(diag::err_unknown_typename_suggest) << II); 422 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 423 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 424 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 425 II->getName().equals(CorrectedStr); 426 diagnoseTypo(Corrected, 427 PDiag(diag::err_unknown_nested_typename_suggest) 428 << II << DC << DroppedSpecifier << SS->getRange()); 429 } else { 430 llvm_unreachable("could not have corrected a typo here"); 431 } 432 433 CXXScopeSpec tmpSS; 434 if (Corrected.getCorrectionSpecifier()) 435 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 436 SourceRange(IILoc)); 437 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 438 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 439 false, ParsedType(), 440 /*IsCtorOrDtorName=*/false, 441 /*NonTrivialTypeSourceInfo=*/true); 442 } 443 return true; 444 } 445 446 if (getLangOpts().CPlusPlus) { 447 // See if II is a class template that the user forgot to pass arguments to. 448 UnqualifiedId Name; 449 Name.setIdentifier(II, IILoc); 450 CXXScopeSpec EmptySS; 451 TemplateTy TemplateResult; 452 bool MemberOfUnknownSpecialization; 453 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 454 Name, ParsedType(), true, TemplateResult, 455 MemberOfUnknownSpecialization) == TNK_Type_template) { 456 TemplateName TplName = TemplateResult.get(); 457 Diag(IILoc, diag::err_template_missing_args) << TplName; 458 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 459 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 460 << TplDecl->getTemplateParameters()->getSourceRange(); 461 } 462 return true; 463 } 464 } 465 466 // FIXME: Should we move the logic that tries to recover from a missing tag 467 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 468 469 if (!SS || (!SS->isSet() && !SS->isInvalid())) 470 Diag(IILoc, diag::err_unknown_typename) << II; 471 else if (DeclContext *DC = computeDeclContext(*SS, false)) 472 Diag(IILoc, diag::err_typename_nested_not_found) 473 << II << DC << SS->getRange(); 474 else if (isDependentScopeSpecifier(*SS)) { 475 unsigned DiagID = diag::err_typename_missing; 476 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 477 DiagID = diag::warn_typename_missing; 478 479 Diag(SS->getRange().getBegin(), DiagID) 480 << SS->getScopeRep() << II->getName() 481 << SourceRange(SS->getRange().getBegin(), IILoc) 482 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 483 SuggestedType = ActOnTypenameType(S, SourceLocation(), 484 *SS, *II, IILoc).get(); 485 } else { 486 assert(SS && SS->isInvalid() && 487 "Invalid scope specifier has already been diagnosed"); 488 } 489 490 return true; 491 } 492 493 /// \brief Determine whether the given result set contains either a type name 494 /// or 495 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 496 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 497 NextToken.is(tok::less); 498 499 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 500 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 501 return true; 502 503 if (CheckTemplate && isa<TemplateDecl>(*I)) 504 return true; 505 } 506 507 return false; 508 } 509 510 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 511 Scope *S, CXXScopeSpec &SS, 512 IdentifierInfo *&Name, 513 SourceLocation NameLoc) { 514 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 515 SemaRef.LookupParsedName(R, S, &SS); 516 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 517 const char *TagName = 0; 518 const char *FixItTagName = 0; 519 switch (Tag->getTagKind()) { 520 case TTK_Class: 521 TagName = "class"; 522 FixItTagName = "class "; 523 break; 524 525 case TTK_Enum: 526 TagName = "enum"; 527 FixItTagName = "enum "; 528 break; 529 530 case TTK_Struct: 531 TagName = "struct"; 532 FixItTagName = "struct "; 533 break; 534 535 case TTK_Interface: 536 TagName = "__interface"; 537 FixItTagName = "__interface "; 538 break; 539 540 case TTK_Union: 541 TagName = "union"; 542 FixItTagName = "union "; 543 break; 544 } 545 546 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 547 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 548 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 549 550 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 551 I != IEnd; ++I) 552 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 553 << Name << TagName; 554 555 // Replace lookup results with just the tag decl. 556 Result.clear(Sema::LookupTagName); 557 SemaRef.LookupParsedName(Result, S, &SS); 558 return true; 559 } 560 561 return false; 562 } 563 564 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 565 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 566 QualType T, SourceLocation NameLoc) { 567 ASTContext &Context = S.Context; 568 569 TypeLocBuilder Builder; 570 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 571 572 T = S.getElaboratedType(ETK_None, SS, T); 573 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 574 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 575 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 576 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 577 } 578 579 Sema::NameClassification Sema::ClassifyName(Scope *S, 580 CXXScopeSpec &SS, 581 IdentifierInfo *&Name, 582 SourceLocation NameLoc, 583 const Token &NextToken, 584 bool IsAddressOfOperand, 585 CorrectionCandidateCallback *CCC) { 586 DeclarationNameInfo NameInfo(Name, NameLoc); 587 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 588 589 if (NextToken.is(tok::coloncolon)) { 590 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 591 QualType(), false, SS, 0, false); 592 593 } 594 595 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 596 LookupParsedName(Result, S, &SS, !CurMethod); 597 598 // Perform lookup for Objective-C instance variables (including automatically 599 // synthesized instance variables), if we're in an Objective-C method. 600 // FIXME: This lookup really, really needs to be folded in to the normal 601 // unqualified lookup mechanism. 602 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 603 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 604 if (E.get() || E.isInvalid()) 605 return E; 606 } 607 608 bool SecondTry = false; 609 bool IsFilteredTemplateName = false; 610 611 Corrected: 612 switch (Result.getResultKind()) { 613 case LookupResult::NotFound: 614 // If an unqualified-id is followed by a '(', then we have a function 615 // call. 616 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 617 // In C++, this is an ADL-only call. 618 // FIXME: Reference? 619 if (getLangOpts().CPlusPlus) 620 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 621 622 // C90 6.3.2.2: 623 // If the expression that precedes the parenthesized argument list in a 624 // function call consists solely of an identifier, and if no 625 // declaration is visible for this identifier, the identifier is 626 // implicitly declared exactly as if, in the innermost block containing 627 // the function call, the declaration 628 // 629 // extern int identifier (); 630 // 631 // appeared. 632 // 633 // We also allow this in C99 as an extension. 634 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 635 Result.addDecl(D); 636 Result.resolveKind(); 637 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 638 } 639 } 640 641 // In C, we first see whether there is a tag type by the same name, in 642 // which case it's likely that the user just forget to write "enum", 643 // "struct", or "union". 644 if (!getLangOpts().CPlusPlus && !SecondTry && 645 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 646 break; 647 } 648 649 // Perform typo correction to determine if there is another name that is 650 // close to this name. 651 if (!SecondTry && CCC) { 652 SecondTry = true; 653 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 654 Result.getLookupKind(), S, 655 &SS, *CCC)) { 656 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 657 unsigned QualifiedDiag = diag::err_no_member_suggest; 658 659 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 660 NamedDecl *UnderlyingFirstDecl 661 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 662 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 663 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 664 UnqualifiedDiag = diag::err_no_template_suggest; 665 QualifiedDiag = diag::err_no_member_template_suggest; 666 } else if (UnderlyingFirstDecl && 667 (isa<TypeDecl>(UnderlyingFirstDecl) || 668 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 669 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 670 UnqualifiedDiag = diag::err_unknown_typename_suggest; 671 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 672 } 673 674 if (SS.isEmpty()) { 675 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 676 } else {// FIXME: is this even reachable? Test it. 677 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 678 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 679 Name->getName().equals(CorrectedStr); 680 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 681 << Name << computeDeclContext(SS, false) 682 << DroppedSpecifier << SS.getRange()); 683 } 684 685 // Update the name, so that the caller has the new name. 686 Name = Corrected.getCorrectionAsIdentifierInfo(); 687 688 // Typo correction corrected to a keyword. 689 if (Corrected.isKeyword()) 690 return Name; 691 692 // Also update the LookupResult... 693 // FIXME: This should probably go away at some point 694 Result.clear(); 695 Result.setLookupName(Corrected.getCorrection()); 696 if (FirstDecl) 697 Result.addDecl(FirstDecl); 698 699 // If we found an Objective-C instance variable, let 700 // LookupInObjCMethod build the appropriate expression to 701 // reference the ivar. 702 // FIXME: This is a gross hack. 703 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 704 Result.clear(); 705 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 706 return E; 707 } 708 709 goto Corrected; 710 } 711 } 712 713 // We failed to correct; just fall through and let the parser deal with it. 714 Result.suppressDiagnostics(); 715 return NameClassification::Unknown(); 716 717 case LookupResult::NotFoundInCurrentInstantiation: { 718 // We performed name lookup into the current instantiation, and there were 719 // dependent bases, so we treat this result the same way as any other 720 // dependent nested-name-specifier. 721 722 // C++ [temp.res]p2: 723 // A name used in a template declaration or definition and that is 724 // dependent on a template-parameter is assumed not to name a type 725 // unless the applicable name lookup finds a type name or the name is 726 // qualified by the keyword typename. 727 // 728 // FIXME: If the next token is '<', we might want to ask the parser to 729 // perform some heroics to see if we actually have a 730 // template-argument-list, which would indicate a missing 'template' 731 // keyword here. 732 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 733 NameInfo, IsAddressOfOperand, 734 /*TemplateArgs=*/0); 735 } 736 737 case LookupResult::Found: 738 case LookupResult::FoundOverloaded: 739 case LookupResult::FoundUnresolvedValue: 740 break; 741 742 case LookupResult::Ambiguous: 743 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 744 hasAnyAcceptableTemplateNames(Result)) { 745 // C++ [temp.local]p3: 746 // A lookup that finds an injected-class-name (10.2) can result in an 747 // ambiguity in certain cases (for example, if it is found in more than 748 // one base class). If all of the injected-class-names that are found 749 // refer to specializations of the same class template, and if the name 750 // is followed by a template-argument-list, the reference refers to the 751 // class template itself and not a specialization thereof, and is not 752 // ambiguous. 753 // 754 // This filtering can make an ambiguous result into an unambiguous one, 755 // so try again after filtering out template names. 756 FilterAcceptableTemplateNames(Result); 757 if (!Result.isAmbiguous()) { 758 IsFilteredTemplateName = true; 759 break; 760 } 761 } 762 763 // Diagnose the ambiguity and return an error. 764 return NameClassification::Error(); 765 } 766 767 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 768 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 769 // C++ [temp.names]p3: 770 // After name lookup (3.4) finds that a name is a template-name or that 771 // an operator-function-id or a literal- operator-id refers to a set of 772 // overloaded functions any member of which is a function template if 773 // this is followed by a <, the < is always taken as the delimiter of a 774 // template-argument-list and never as the less-than operator. 775 if (!IsFilteredTemplateName) 776 FilterAcceptableTemplateNames(Result); 777 778 if (!Result.empty()) { 779 bool IsFunctionTemplate; 780 bool IsVarTemplate; 781 TemplateName Template; 782 if (Result.end() - Result.begin() > 1) { 783 IsFunctionTemplate = true; 784 Template = Context.getOverloadedTemplateName(Result.begin(), 785 Result.end()); 786 } else { 787 TemplateDecl *TD 788 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 789 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 790 IsVarTemplate = isa<VarTemplateDecl>(TD); 791 792 if (SS.isSet() && !SS.isInvalid()) 793 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 794 /*TemplateKeyword=*/false, 795 TD); 796 else 797 Template = TemplateName(TD); 798 } 799 800 if (IsFunctionTemplate) { 801 // Function templates always go through overload resolution, at which 802 // point we'll perform the various checks (e.g., accessibility) we need 803 // to based on which function we selected. 804 Result.suppressDiagnostics(); 805 806 return NameClassification::FunctionTemplate(Template); 807 } 808 809 return IsVarTemplate ? NameClassification::VarTemplate(Template) 810 : NameClassification::TypeTemplate(Template); 811 } 812 } 813 814 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 815 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 816 DiagnoseUseOfDecl(Type, NameLoc); 817 QualType T = Context.getTypeDeclType(Type); 818 if (SS.isNotEmpty()) 819 return buildNestedType(*this, SS, T, NameLoc); 820 return ParsedType::make(T); 821 } 822 823 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 824 if (!Class) { 825 // FIXME: It's unfortunate that we don't have a Type node for handling this. 826 if (ObjCCompatibleAliasDecl *Alias 827 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 828 Class = Alias->getClassInterface(); 829 } 830 831 if (Class) { 832 DiagnoseUseOfDecl(Class, NameLoc); 833 834 if (NextToken.is(tok::period)) { 835 // Interface. <something> is parsed as a property reference expression. 836 // Just return "unknown" as a fall-through for now. 837 Result.suppressDiagnostics(); 838 return NameClassification::Unknown(); 839 } 840 841 QualType T = Context.getObjCInterfaceType(Class); 842 return ParsedType::make(T); 843 } 844 845 // We can have a type template here if we're classifying a template argument. 846 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 847 return NameClassification::TypeTemplate( 848 TemplateName(cast<TemplateDecl>(FirstDecl))); 849 850 // Check for a tag type hidden by a non-type decl in a few cases where it 851 // seems likely a type is wanted instead of the non-type that was found. 852 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 853 if ((NextToken.is(tok::identifier) || 854 (NextIsOp && 855 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 856 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 857 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 858 DiagnoseUseOfDecl(Type, NameLoc); 859 QualType T = Context.getTypeDeclType(Type); 860 if (SS.isNotEmpty()) 861 return buildNestedType(*this, SS, T, NameLoc); 862 return ParsedType::make(T); 863 } 864 865 if (FirstDecl->isCXXClassMember()) 866 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 867 868 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 869 return BuildDeclarationNameExpr(SS, Result, ADL); 870 } 871 872 // Determines the context to return to after temporarily entering a 873 // context. This depends in an unnecessarily complicated way on the 874 // exact ordering of callbacks from the parser. 875 DeclContext *Sema::getContainingDC(DeclContext *DC) { 876 877 // Functions defined inline within classes aren't parsed until we've 878 // finished parsing the top-level class, so the top-level class is 879 // the context we'll need to return to. 880 // A Lambda call operator whose parent is a class must not be treated 881 // as an inline member function. A Lambda can be used legally 882 // either as an in-class member initializer or a default argument. These 883 // are parsed once the class has been marked complete and so the containing 884 // context would be the nested class (when the lambda is defined in one); 885 // If the class is not complete, then the lambda is being used in an 886 // ill-formed fashion (such as to specify the width of a bit-field, or 887 // in an array-bound) - in which case we still want to return the 888 // lexically containing DC (which could be a nested class). 889 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 890 DC = DC->getLexicalParent(); 891 892 // A function not defined within a class will always return to its 893 // lexical context. 894 if (!isa<CXXRecordDecl>(DC)) 895 return DC; 896 897 // A C++ inline method/friend is parsed *after* the topmost class 898 // it was declared in is fully parsed ("complete"); the topmost 899 // class is the context we need to return to. 900 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 901 DC = RD; 902 903 // Return the declaration context of the topmost class the inline method is 904 // declared in. 905 return DC; 906 } 907 908 return DC->getLexicalParent(); 909 } 910 911 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 912 assert(getContainingDC(DC) == CurContext && 913 "The next DeclContext should be lexically contained in the current one."); 914 CurContext = DC; 915 S->setEntity(DC); 916 } 917 918 void Sema::PopDeclContext() { 919 assert(CurContext && "DeclContext imbalance!"); 920 921 CurContext = getContainingDC(CurContext); 922 assert(CurContext && "Popped translation unit!"); 923 } 924 925 /// EnterDeclaratorContext - Used when we must lookup names in the context 926 /// of a declarator's nested name specifier. 927 /// 928 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 929 // C++0x [basic.lookup.unqual]p13: 930 // A name used in the definition of a static data member of class 931 // X (after the qualified-id of the static member) is looked up as 932 // if the name was used in a member function of X. 933 // C++0x [basic.lookup.unqual]p14: 934 // If a variable member of a namespace is defined outside of the 935 // scope of its namespace then any name used in the definition of 936 // the variable member (after the declarator-id) is looked up as 937 // if the definition of the variable member occurred in its 938 // namespace. 939 // Both of these imply that we should push a scope whose context 940 // is the semantic context of the declaration. We can't use 941 // PushDeclContext here because that context is not necessarily 942 // lexically contained in the current context. Fortunately, 943 // the containing scope should have the appropriate information. 944 945 assert(!S->getEntity() && "scope already has entity"); 946 947 #ifndef NDEBUG 948 Scope *Ancestor = S->getParent(); 949 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 950 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 951 #endif 952 953 CurContext = DC; 954 S->setEntity(DC); 955 } 956 957 void Sema::ExitDeclaratorContext(Scope *S) { 958 assert(S->getEntity() == CurContext && "Context imbalance!"); 959 960 // Switch back to the lexical context. The safety of this is 961 // enforced by an assert in EnterDeclaratorContext. 962 Scope *Ancestor = S->getParent(); 963 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 964 CurContext = Ancestor->getEntity(); 965 966 // We don't need to do anything with the scope, which is going to 967 // disappear. 968 } 969 970 971 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 972 // We assume that the caller has already called 973 // ActOnReenterTemplateScope so getTemplatedDecl() works. 974 FunctionDecl *FD = D->getAsFunction(); 975 if (!FD) 976 return; 977 978 // Same implementation as PushDeclContext, but enters the context 979 // from the lexical parent, rather than the top-level class. 980 assert(CurContext == FD->getLexicalParent() && 981 "The next DeclContext should be lexically contained in the current one."); 982 CurContext = FD; 983 S->setEntity(CurContext); 984 985 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 986 ParmVarDecl *Param = FD->getParamDecl(P); 987 // If the parameter has an identifier, then add it to the scope 988 if (Param->getIdentifier()) { 989 S->AddDecl(Param); 990 IdResolver.AddDecl(Param); 991 } 992 } 993 } 994 995 996 void Sema::ActOnExitFunctionContext() { 997 // Same implementation as PopDeclContext, but returns to the lexical parent, 998 // rather than the top-level class. 999 assert(CurContext && "DeclContext imbalance!"); 1000 CurContext = CurContext->getLexicalParent(); 1001 assert(CurContext && "Popped translation unit!"); 1002 } 1003 1004 1005 /// \brief Determine whether we allow overloading of the function 1006 /// PrevDecl with another declaration. 1007 /// 1008 /// This routine determines whether overloading is possible, not 1009 /// whether some new function is actually an overload. It will return 1010 /// true in C++ (where we can always provide overloads) or, as an 1011 /// extension, in C when the previous function is already an 1012 /// overloaded function declaration or has the "overloadable" 1013 /// attribute. 1014 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1015 ASTContext &Context) { 1016 if (Context.getLangOpts().CPlusPlus) 1017 return true; 1018 1019 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1020 return true; 1021 1022 return (Previous.getResultKind() == LookupResult::Found 1023 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1024 } 1025 1026 /// Add this decl to the scope shadowed decl chains. 1027 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1028 // Move up the scope chain until we find the nearest enclosing 1029 // non-transparent context. The declaration will be introduced into this 1030 // scope. 1031 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1032 S = S->getParent(); 1033 1034 // Add scoped declarations into their context, so that they can be 1035 // found later. Declarations without a context won't be inserted 1036 // into any context. 1037 if (AddToContext) 1038 CurContext->addDecl(D); 1039 1040 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1041 // are function-local declarations. 1042 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1043 !D->getDeclContext()->getRedeclContext()->Equals( 1044 D->getLexicalDeclContext()->getRedeclContext()) && 1045 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1046 return; 1047 1048 // Template instantiations should also not be pushed into scope. 1049 if (isa<FunctionDecl>(D) && 1050 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1051 return; 1052 1053 // If this replaces anything in the current scope, 1054 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1055 IEnd = IdResolver.end(); 1056 for (; I != IEnd; ++I) { 1057 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1058 S->RemoveDecl(*I); 1059 IdResolver.RemoveDecl(*I); 1060 1061 // Should only need to replace one decl. 1062 break; 1063 } 1064 } 1065 1066 S->AddDecl(D); 1067 1068 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1069 // Implicitly-generated labels may end up getting generated in an order that 1070 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1071 // the label at the appropriate place in the identifier chain. 1072 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1073 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1074 if (IDC == CurContext) { 1075 if (!S->isDeclScope(*I)) 1076 continue; 1077 } else if (IDC->Encloses(CurContext)) 1078 break; 1079 } 1080 1081 IdResolver.InsertDeclAfter(I, D); 1082 } else { 1083 IdResolver.AddDecl(D); 1084 } 1085 } 1086 1087 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1088 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1089 TUScope->AddDecl(D); 1090 } 1091 1092 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1093 bool AllowInlineNamespace) { 1094 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1095 } 1096 1097 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1098 DeclContext *TargetDC = DC->getPrimaryContext(); 1099 do { 1100 if (DeclContext *ScopeDC = S->getEntity()) 1101 if (ScopeDC->getPrimaryContext() == TargetDC) 1102 return S; 1103 } while ((S = S->getParent())); 1104 1105 return 0; 1106 } 1107 1108 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1109 DeclContext*, 1110 ASTContext&); 1111 1112 /// Filters out lookup results that don't fall within the given scope 1113 /// as determined by isDeclInScope. 1114 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1115 bool ConsiderLinkage, 1116 bool AllowInlineNamespace) { 1117 LookupResult::Filter F = R.makeFilter(); 1118 while (F.hasNext()) { 1119 NamedDecl *D = F.next(); 1120 1121 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1122 continue; 1123 1124 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1125 continue; 1126 1127 F.erase(); 1128 } 1129 1130 F.done(); 1131 } 1132 1133 static bool isUsingDecl(NamedDecl *D) { 1134 return isa<UsingShadowDecl>(D) || 1135 isa<UnresolvedUsingTypenameDecl>(D) || 1136 isa<UnresolvedUsingValueDecl>(D); 1137 } 1138 1139 /// Removes using shadow declarations from the lookup results. 1140 static void RemoveUsingDecls(LookupResult &R) { 1141 LookupResult::Filter F = R.makeFilter(); 1142 while (F.hasNext()) 1143 if (isUsingDecl(F.next())) 1144 F.erase(); 1145 1146 F.done(); 1147 } 1148 1149 /// \brief Check for this common pattern: 1150 /// @code 1151 /// class S { 1152 /// S(const S&); // DO NOT IMPLEMENT 1153 /// void operator=(const S&); // DO NOT IMPLEMENT 1154 /// }; 1155 /// @endcode 1156 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1157 // FIXME: Should check for private access too but access is set after we get 1158 // the decl here. 1159 if (D->doesThisDeclarationHaveABody()) 1160 return false; 1161 1162 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1163 return CD->isCopyConstructor(); 1164 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1165 return Method->isCopyAssignmentOperator(); 1166 return false; 1167 } 1168 1169 // We need this to handle 1170 // 1171 // typedef struct { 1172 // void *foo() { return 0; } 1173 // } A; 1174 // 1175 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1176 // for example. If 'A', foo will have external linkage. If we have '*A', 1177 // foo will have no linkage. Since we can't know until we get to the end 1178 // of the typedef, this function finds out if D might have non-external linkage. 1179 // Callers should verify at the end of the TU if it D has external linkage or 1180 // not. 1181 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1182 const DeclContext *DC = D->getDeclContext(); 1183 while (!DC->isTranslationUnit()) { 1184 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1185 if (!RD->hasNameForLinkage()) 1186 return true; 1187 } 1188 DC = DC->getParent(); 1189 } 1190 1191 return !D->isExternallyVisible(); 1192 } 1193 1194 // FIXME: This needs to be refactored; some other isInMainFile users want 1195 // these semantics. 1196 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1197 if (S.TUKind != TU_Complete) 1198 return false; 1199 return S.SourceMgr.isInMainFile(Loc); 1200 } 1201 1202 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1203 assert(D); 1204 1205 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1206 return false; 1207 1208 // Ignore class templates. 1209 if (D->getDeclContext()->isDependentContext() || 1210 D->getLexicalDeclContext()->isDependentContext()) 1211 return false; 1212 1213 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1214 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1215 return false; 1216 1217 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1218 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1219 return false; 1220 } else { 1221 // 'static inline' functions are defined in headers; don't warn. 1222 if (FD->isInlineSpecified() && 1223 !isMainFileLoc(*this, FD->getLocation())) 1224 return false; 1225 } 1226 1227 if (FD->doesThisDeclarationHaveABody() && 1228 Context.DeclMustBeEmitted(FD)) 1229 return false; 1230 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1231 // Constants and utility variables are defined in headers with internal 1232 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1233 // like "inline".) 1234 if (!isMainFileLoc(*this, VD->getLocation())) 1235 return false; 1236 1237 if (Context.DeclMustBeEmitted(VD)) 1238 return false; 1239 1240 if (VD->isStaticDataMember() && 1241 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1242 return false; 1243 } else { 1244 return false; 1245 } 1246 1247 // Only warn for unused decls internal to the translation unit. 1248 return mightHaveNonExternalLinkage(D); 1249 } 1250 1251 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1252 if (!D) 1253 return; 1254 1255 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1256 const FunctionDecl *First = FD->getFirstDecl(); 1257 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1258 return; // First should already be in the vector. 1259 } 1260 1261 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1262 const VarDecl *First = VD->getFirstDecl(); 1263 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1264 return; // First should already be in the vector. 1265 } 1266 1267 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1268 UnusedFileScopedDecls.push_back(D); 1269 } 1270 1271 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1272 if (D->isInvalidDecl()) 1273 return false; 1274 1275 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1276 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1277 return false; 1278 1279 if (isa<LabelDecl>(D)) 1280 return true; 1281 1282 // White-list anything that isn't a local variable. 1283 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1284 !D->getDeclContext()->isFunctionOrMethod()) 1285 return false; 1286 1287 // Types of valid local variables should be complete, so this should succeed. 1288 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1289 1290 // White-list anything with an __attribute__((unused)) type. 1291 QualType Ty = VD->getType(); 1292 1293 // Only look at the outermost level of typedef. 1294 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1295 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1296 return false; 1297 } 1298 1299 // If we failed to complete the type for some reason, or if the type is 1300 // dependent, don't diagnose the variable. 1301 if (Ty->isIncompleteType() || Ty->isDependentType()) 1302 return false; 1303 1304 if (const TagType *TT = Ty->getAs<TagType>()) { 1305 const TagDecl *Tag = TT->getDecl(); 1306 if (Tag->hasAttr<UnusedAttr>()) 1307 return false; 1308 1309 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1310 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1311 return false; 1312 1313 if (const Expr *Init = VD->getInit()) { 1314 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1315 Init = Cleanups->getSubExpr(); 1316 const CXXConstructExpr *Construct = 1317 dyn_cast<CXXConstructExpr>(Init); 1318 if (Construct && !Construct->isElidable()) { 1319 CXXConstructorDecl *CD = Construct->getConstructor(); 1320 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1321 return false; 1322 } 1323 } 1324 } 1325 } 1326 1327 // TODO: __attribute__((unused)) templates? 1328 } 1329 1330 return true; 1331 } 1332 1333 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1334 FixItHint &Hint) { 1335 if (isa<LabelDecl>(D)) { 1336 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1337 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1338 if (AfterColon.isInvalid()) 1339 return; 1340 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1341 getCharRange(D->getLocStart(), AfterColon)); 1342 } 1343 return; 1344 } 1345 1346 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1347 /// unless they are marked attr(unused). 1348 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1349 FixItHint Hint; 1350 if (!ShouldDiagnoseUnusedDecl(D)) 1351 return; 1352 1353 GenerateFixForUnusedDecl(D, Context, Hint); 1354 1355 unsigned DiagID; 1356 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1357 DiagID = diag::warn_unused_exception_param; 1358 else if (isa<LabelDecl>(D)) 1359 DiagID = diag::warn_unused_label; 1360 else 1361 DiagID = diag::warn_unused_variable; 1362 1363 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1364 } 1365 1366 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1367 // Verify that we have no forward references left. If so, there was a goto 1368 // or address of a label taken, but no definition of it. Label fwd 1369 // definitions are indicated with a null substmt. 1370 if (L->getStmt() == 0) 1371 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1372 } 1373 1374 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1375 if (S->decl_empty()) return; 1376 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1377 "Scope shouldn't contain decls!"); 1378 1379 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1380 I != E; ++I) { 1381 Decl *TmpD = (*I); 1382 assert(TmpD && "This decl didn't get pushed??"); 1383 1384 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1385 NamedDecl *D = cast<NamedDecl>(TmpD); 1386 1387 if (!D->getDeclName()) continue; 1388 1389 // Diagnose unused variables in this scope. 1390 if (!S->hasUnrecoverableErrorOccurred()) 1391 DiagnoseUnusedDecl(D); 1392 1393 // If this was a forward reference to a label, verify it was defined. 1394 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1395 CheckPoppedLabel(LD, *this); 1396 1397 // Remove this name from our lexical scope. 1398 IdResolver.RemoveDecl(D); 1399 } 1400 } 1401 1402 void Sema::ActOnStartFunctionDeclarator() { 1403 ++InFunctionDeclarator; 1404 } 1405 1406 void Sema::ActOnEndFunctionDeclarator() { 1407 assert(InFunctionDeclarator); 1408 --InFunctionDeclarator; 1409 } 1410 1411 /// \brief Look for an Objective-C class in the translation unit. 1412 /// 1413 /// \param Id The name of the Objective-C class we're looking for. If 1414 /// typo-correction fixes this name, the Id will be updated 1415 /// to the fixed name. 1416 /// 1417 /// \param IdLoc The location of the name in the translation unit. 1418 /// 1419 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1420 /// if there is no class with the given name. 1421 /// 1422 /// \returns The declaration of the named Objective-C class, or NULL if the 1423 /// class could not be found. 1424 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1425 SourceLocation IdLoc, 1426 bool DoTypoCorrection) { 1427 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1428 // creation from this context. 1429 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1430 1431 if (!IDecl && DoTypoCorrection) { 1432 // Perform typo correction at the given location, but only if we 1433 // find an Objective-C class name. 1434 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1435 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1436 LookupOrdinaryName, TUScope, NULL, 1437 Validator)) { 1438 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1439 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1440 Id = IDecl->getIdentifier(); 1441 } 1442 } 1443 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1444 // This routine must always return a class definition, if any. 1445 if (Def && Def->getDefinition()) 1446 Def = Def->getDefinition(); 1447 return Def; 1448 } 1449 1450 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1451 /// from S, where a non-field would be declared. This routine copes 1452 /// with the difference between C and C++ scoping rules in structs and 1453 /// unions. For example, the following code is well-formed in C but 1454 /// ill-formed in C++: 1455 /// @code 1456 /// struct S6 { 1457 /// enum { BAR } e; 1458 /// }; 1459 /// 1460 /// void test_S6() { 1461 /// struct S6 a; 1462 /// a.e = BAR; 1463 /// } 1464 /// @endcode 1465 /// For the declaration of BAR, this routine will return a different 1466 /// scope. The scope S will be the scope of the unnamed enumeration 1467 /// within S6. In C++, this routine will return the scope associated 1468 /// with S6, because the enumeration's scope is a transparent 1469 /// context but structures can contain non-field names. In C, this 1470 /// routine will return the translation unit scope, since the 1471 /// enumeration's scope is a transparent context and structures cannot 1472 /// contain non-field names. 1473 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1474 while (((S->getFlags() & Scope::DeclScope) == 0) || 1475 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1476 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1477 S = S->getParent(); 1478 return S; 1479 } 1480 1481 /// \brief Looks up the declaration of "struct objc_super" and 1482 /// saves it for later use in building builtin declaration of 1483 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1484 /// pre-existing declaration exists no action takes place. 1485 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1486 IdentifierInfo *II) { 1487 if (!II->isStr("objc_msgSendSuper")) 1488 return; 1489 ASTContext &Context = ThisSema.Context; 1490 1491 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1492 SourceLocation(), Sema::LookupTagName); 1493 ThisSema.LookupName(Result, S); 1494 if (Result.getResultKind() == LookupResult::Found) 1495 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1496 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1497 } 1498 1499 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1500 /// file scope. lazily create a decl for it. ForRedeclaration is true 1501 /// if we're creating this built-in in anticipation of redeclaring the 1502 /// built-in. 1503 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1504 Scope *S, bool ForRedeclaration, 1505 SourceLocation Loc) { 1506 LookupPredefedObjCSuperType(*this, S, II); 1507 1508 Builtin::ID BID = (Builtin::ID)bid; 1509 1510 ASTContext::GetBuiltinTypeError Error; 1511 QualType R = Context.GetBuiltinType(BID, Error); 1512 switch (Error) { 1513 case ASTContext::GE_None: 1514 // Okay 1515 break; 1516 1517 case ASTContext::GE_Missing_stdio: 1518 if (ForRedeclaration) 1519 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1520 << Context.BuiltinInfo.GetName(BID); 1521 return 0; 1522 1523 case ASTContext::GE_Missing_setjmp: 1524 if (ForRedeclaration) 1525 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1526 << Context.BuiltinInfo.GetName(BID); 1527 return 0; 1528 1529 case ASTContext::GE_Missing_ucontext: 1530 if (ForRedeclaration) 1531 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1532 << Context.BuiltinInfo.GetName(BID); 1533 return 0; 1534 } 1535 1536 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1537 Diag(Loc, diag::ext_implicit_lib_function_decl) 1538 << Context.BuiltinInfo.GetName(BID) 1539 << R; 1540 if (Context.BuiltinInfo.getHeaderName(BID) && 1541 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1542 != DiagnosticsEngine::Ignored) 1543 Diag(Loc, diag::note_please_include_header) 1544 << Context.BuiltinInfo.getHeaderName(BID) 1545 << Context.BuiltinInfo.GetName(BID); 1546 } 1547 1548 DeclContext *Parent = Context.getTranslationUnitDecl(); 1549 if (getLangOpts().CPlusPlus) { 1550 LinkageSpecDecl *CLinkageDecl = 1551 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1552 LinkageSpecDecl::lang_c, false); 1553 CLinkageDecl->setImplicit(); 1554 Parent->addDecl(CLinkageDecl); 1555 Parent = CLinkageDecl; 1556 } 1557 1558 FunctionDecl *New = FunctionDecl::Create(Context, 1559 Parent, 1560 Loc, Loc, II, R, /*TInfo=*/0, 1561 SC_Extern, 1562 false, 1563 /*hasPrototype=*/true); 1564 New->setImplicit(); 1565 1566 // Create Decl objects for each parameter, adding them to the 1567 // FunctionDecl. 1568 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1569 SmallVector<ParmVarDecl*, 16> Params; 1570 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1571 ParmVarDecl *parm = 1572 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1573 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0); 1574 parm->setScopeInfo(0, i); 1575 Params.push_back(parm); 1576 } 1577 New->setParams(Params); 1578 } 1579 1580 AddKnownFunctionAttributes(New); 1581 RegisterLocallyScopedExternCDecl(New, S); 1582 1583 // TUScope is the translation-unit scope to insert this function into. 1584 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1585 // relate Scopes to DeclContexts, and probably eliminate CurContext 1586 // entirely, but we're not there yet. 1587 DeclContext *SavedContext = CurContext; 1588 CurContext = Parent; 1589 PushOnScopeChains(New, TUScope); 1590 CurContext = SavedContext; 1591 return New; 1592 } 1593 1594 /// \brief Filter out any previous declarations that the given declaration 1595 /// should not consider because they are not permitted to conflict, e.g., 1596 /// because they come from hidden sub-modules and do not refer to the same 1597 /// entity. 1598 static void filterNonConflictingPreviousDecls(ASTContext &context, 1599 NamedDecl *decl, 1600 LookupResult &previous){ 1601 // This is only interesting when modules are enabled. 1602 if (!context.getLangOpts().Modules) 1603 return; 1604 1605 // Empty sets are uninteresting. 1606 if (previous.empty()) 1607 return; 1608 1609 LookupResult::Filter filter = previous.makeFilter(); 1610 while (filter.hasNext()) { 1611 NamedDecl *old = filter.next(); 1612 1613 // Non-hidden declarations are never ignored. 1614 if (!old->isHidden()) 1615 continue; 1616 1617 if (!old->isExternallyVisible()) 1618 filter.erase(); 1619 } 1620 1621 filter.done(); 1622 } 1623 1624 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1625 QualType OldType; 1626 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1627 OldType = OldTypedef->getUnderlyingType(); 1628 else 1629 OldType = Context.getTypeDeclType(Old); 1630 QualType NewType = New->getUnderlyingType(); 1631 1632 if (NewType->isVariablyModifiedType()) { 1633 // Must not redefine a typedef with a variably-modified type. 1634 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1635 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1636 << Kind << NewType; 1637 if (Old->getLocation().isValid()) 1638 Diag(Old->getLocation(), diag::note_previous_definition); 1639 New->setInvalidDecl(); 1640 return true; 1641 } 1642 1643 if (OldType != NewType && 1644 !OldType->isDependentType() && 1645 !NewType->isDependentType() && 1646 !Context.hasSameType(OldType, NewType)) { 1647 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1648 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1649 << Kind << NewType << OldType; 1650 if (Old->getLocation().isValid()) 1651 Diag(Old->getLocation(), diag::note_previous_definition); 1652 New->setInvalidDecl(); 1653 return true; 1654 } 1655 return false; 1656 } 1657 1658 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1659 /// same name and scope as a previous declaration 'Old'. Figure out 1660 /// how to resolve this situation, merging decls or emitting 1661 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1662 /// 1663 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1664 // If the new decl is known invalid already, don't bother doing any 1665 // merging checks. 1666 if (New->isInvalidDecl()) return; 1667 1668 // Allow multiple definitions for ObjC built-in typedefs. 1669 // FIXME: Verify the underlying types are equivalent! 1670 if (getLangOpts().ObjC1) { 1671 const IdentifierInfo *TypeID = New->getIdentifier(); 1672 switch (TypeID->getLength()) { 1673 default: break; 1674 case 2: 1675 { 1676 if (!TypeID->isStr("id")) 1677 break; 1678 QualType T = New->getUnderlyingType(); 1679 if (!T->isPointerType()) 1680 break; 1681 if (!T->isVoidPointerType()) { 1682 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1683 if (!PT->isStructureType()) 1684 break; 1685 } 1686 Context.setObjCIdRedefinitionType(T); 1687 // Install the built-in type for 'id', ignoring the current definition. 1688 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1689 return; 1690 } 1691 case 5: 1692 if (!TypeID->isStr("Class")) 1693 break; 1694 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1695 // Install the built-in type for 'Class', ignoring the current definition. 1696 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1697 return; 1698 case 3: 1699 if (!TypeID->isStr("SEL")) 1700 break; 1701 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1702 // Install the built-in type for 'SEL', ignoring the current definition. 1703 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1704 return; 1705 } 1706 // Fall through - the typedef name was not a builtin type. 1707 } 1708 1709 // Verify the old decl was also a type. 1710 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1711 if (!Old) { 1712 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1713 << New->getDeclName(); 1714 1715 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1716 if (OldD->getLocation().isValid()) 1717 Diag(OldD->getLocation(), diag::note_previous_definition); 1718 1719 return New->setInvalidDecl(); 1720 } 1721 1722 // If the old declaration is invalid, just give up here. 1723 if (Old->isInvalidDecl()) 1724 return New->setInvalidDecl(); 1725 1726 // If the typedef types are not identical, reject them in all languages and 1727 // with any extensions enabled. 1728 if (isIncompatibleTypedef(Old, New)) 1729 return; 1730 1731 // The types match. Link up the redeclaration chain and merge attributes if 1732 // the old declaration was a typedef. 1733 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1734 New->setPreviousDecl(Typedef); 1735 mergeDeclAttributes(New, Old); 1736 } 1737 1738 if (getLangOpts().MicrosoftExt) 1739 return; 1740 1741 if (getLangOpts().CPlusPlus) { 1742 // C++ [dcl.typedef]p2: 1743 // In a given non-class scope, a typedef specifier can be used to 1744 // redefine the name of any type declared in that scope to refer 1745 // to the type to which it already refers. 1746 if (!isa<CXXRecordDecl>(CurContext)) 1747 return; 1748 1749 // C++0x [dcl.typedef]p4: 1750 // In a given class scope, a typedef specifier can be used to redefine 1751 // any class-name declared in that scope that is not also a typedef-name 1752 // to refer to the type to which it already refers. 1753 // 1754 // This wording came in via DR424, which was a correction to the 1755 // wording in DR56, which accidentally banned code like: 1756 // 1757 // struct S { 1758 // typedef struct A { } A; 1759 // }; 1760 // 1761 // in the C++03 standard. We implement the C++0x semantics, which 1762 // allow the above but disallow 1763 // 1764 // struct S { 1765 // typedef int I; 1766 // typedef int I; 1767 // }; 1768 // 1769 // since that was the intent of DR56. 1770 if (!isa<TypedefNameDecl>(Old)) 1771 return; 1772 1773 Diag(New->getLocation(), diag::err_redefinition) 1774 << New->getDeclName(); 1775 Diag(Old->getLocation(), diag::note_previous_definition); 1776 return New->setInvalidDecl(); 1777 } 1778 1779 // Modules always permit redefinition of typedefs, as does C11. 1780 if (getLangOpts().Modules || getLangOpts().C11) 1781 return; 1782 1783 // If we have a redefinition of a typedef in C, emit a warning. This warning 1784 // is normally mapped to an error, but can be controlled with 1785 // -Wtypedef-redefinition. If either the original or the redefinition is 1786 // in a system header, don't emit this for compatibility with GCC. 1787 if (getDiagnostics().getSuppressSystemWarnings() && 1788 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1789 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1790 return; 1791 1792 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1793 << New->getDeclName(); 1794 Diag(Old->getLocation(), diag::note_previous_definition); 1795 return; 1796 } 1797 1798 /// DeclhasAttr - returns true if decl Declaration already has the target 1799 /// attribute. 1800 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1801 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1802 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1803 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1804 if ((*i)->getKind() == A->getKind()) { 1805 if (Ann) { 1806 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1807 return true; 1808 continue; 1809 } 1810 // FIXME: Don't hardcode this check 1811 if (OA && isa<OwnershipAttr>(*i)) 1812 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1813 return true; 1814 } 1815 1816 return false; 1817 } 1818 1819 static bool isAttributeTargetADefinition(Decl *D) { 1820 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1821 return VD->isThisDeclarationADefinition(); 1822 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1823 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1824 return true; 1825 } 1826 1827 /// Merge alignment attributes from \p Old to \p New, taking into account the 1828 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1829 /// 1830 /// \return \c true if any attributes were added to \p New. 1831 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1832 // Look for alignas attributes on Old, and pick out whichever attribute 1833 // specifies the strictest alignment requirement. 1834 AlignedAttr *OldAlignasAttr = 0; 1835 AlignedAttr *OldStrictestAlignAttr = 0; 1836 unsigned OldAlign = 0; 1837 for (specific_attr_iterator<AlignedAttr> 1838 I = Old->specific_attr_begin<AlignedAttr>(), 1839 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1840 // FIXME: We have no way of representing inherited dependent alignments 1841 // in a case like: 1842 // template<int A, int B> struct alignas(A) X; 1843 // template<int A, int B> struct alignas(B) X {}; 1844 // For now, we just ignore any alignas attributes which are not on the 1845 // definition in such a case. 1846 if (I->isAlignmentDependent()) 1847 return false; 1848 1849 if (I->isAlignas()) 1850 OldAlignasAttr = *I; 1851 1852 unsigned Align = I->getAlignment(S.Context); 1853 if (Align > OldAlign) { 1854 OldAlign = Align; 1855 OldStrictestAlignAttr = *I; 1856 } 1857 } 1858 1859 // Look for alignas attributes on New. 1860 AlignedAttr *NewAlignasAttr = 0; 1861 unsigned NewAlign = 0; 1862 for (specific_attr_iterator<AlignedAttr> 1863 I = New->specific_attr_begin<AlignedAttr>(), 1864 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1865 if (I->isAlignmentDependent()) 1866 return false; 1867 1868 if (I->isAlignas()) 1869 NewAlignasAttr = *I; 1870 1871 unsigned Align = I->getAlignment(S.Context); 1872 if (Align > NewAlign) 1873 NewAlign = Align; 1874 } 1875 1876 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1877 // Both declarations have 'alignas' attributes. We require them to match. 1878 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1879 // fall short. (If two declarations both have alignas, they must both match 1880 // every definition, and so must match each other if there is a definition.) 1881 1882 // If either declaration only contains 'alignas(0)' specifiers, then it 1883 // specifies the natural alignment for the type. 1884 if (OldAlign == 0 || NewAlign == 0) { 1885 QualType Ty; 1886 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1887 Ty = VD->getType(); 1888 else 1889 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1890 1891 if (OldAlign == 0) 1892 OldAlign = S.Context.getTypeAlign(Ty); 1893 if (NewAlign == 0) 1894 NewAlign = S.Context.getTypeAlign(Ty); 1895 } 1896 1897 if (OldAlign != NewAlign) { 1898 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1899 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1900 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1901 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1902 } 1903 } 1904 1905 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1906 // C++11 [dcl.align]p6: 1907 // if any declaration of an entity has an alignment-specifier, 1908 // every defining declaration of that entity shall specify an 1909 // equivalent alignment. 1910 // C11 6.7.5/7: 1911 // If the definition of an object does not have an alignment 1912 // specifier, any other declaration of that object shall also 1913 // have no alignment specifier. 1914 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1915 << OldAlignasAttr; 1916 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1917 << OldAlignasAttr; 1918 } 1919 1920 bool AnyAdded = false; 1921 1922 // Ensure we have an attribute representing the strictest alignment. 1923 if (OldAlign > NewAlign) { 1924 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1925 Clone->setInherited(true); 1926 New->addAttr(Clone); 1927 AnyAdded = true; 1928 } 1929 1930 // Ensure we have an alignas attribute if the old declaration had one. 1931 if (OldAlignasAttr && !NewAlignasAttr && 1932 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1933 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1934 Clone->setInherited(true); 1935 New->addAttr(Clone); 1936 AnyAdded = true; 1937 } 1938 1939 return AnyAdded; 1940 } 1941 1942 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1943 bool Override) { 1944 InheritableAttr *NewAttr = NULL; 1945 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1946 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1947 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1948 AA->getIntroduced(), AA->getDeprecated(), 1949 AA->getObsoleted(), AA->getUnavailable(), 1950 AA->getMessage(), Override, 1951 AttrSpellingListIndex); 1952 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1953 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1954 AttrSpellingListIndex); 1955 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1956 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1957 AttrSpellingListIndex); 1958 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1959 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1960 AttrSpellingListIndex); 1961 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1962 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1963 AttrSpellingListIndex); 1964 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1965 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1966 FA->getFormatIdx(), FA->getFirstArg(), 1967 AttrSpellingListIndex); 1968 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1969 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1970 AttrSpellingListIndex); 1971 else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr)) 1972 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 1973 AttrSpellingListIndex, 1974 IA->getSemanticSpelling()); 1975 else if (isa<AlignedAttr>(Attr)) 1976 // AlignedAttrs are handled separately, because we need to handle all 1977 // such attributes on a declaration at the same time. 1978 NewAttr = 0; 1979 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 1980 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1981 1982 if (NewAttr) { 1983 NewAttr->setInherited(true); 1984 D->addAttr(NewAttr); 1985 return true; 1986 } 1987 1988 return false; 1989 } 1990 1991 static const Decl *getDefinition(const Decl *D) { 1992 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1993 return TD->getDefinition(); 1994 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1995 const VarDecl *Def = VD->getDefinition(); 1996 if (Def) 1997 return Def; 1998 return VD->getActingDefinition(); 1999 } 2000 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2001 const FunctionDecl* Def; 2002 if (FD->isDefined(Def)) 2003 return Def; 2004 } 2005 return NULL; 2006 } 2007 2008 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2009 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2010 I != E; ++I) { 2011 Attr *Attribute = *I; 2012 if (Attribute->getKind() == Kind) 2013 return true; 2014 } 2015 return false; 2016 } 2017 2018 /// checkNewAttributesAfterDef - If we already have a definition, check that 2019 /// there are no new attributes in this declaration. 2020 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2021 if (!New->hasAttrs()) 2022 return; 2023 2024 const Decl *Def = getDefinition(Old); 2025 if (!Def || Def == New) 2026 return; 2027 2028 AttrVec &NewAttributes = New->getAttrs(); 2029 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2030 const Attr *NewAttribute = NewAttributes[I]; 2031 2032 if (isa<AliasAttr>(NewAttribute)) { 2033 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2034 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2035 else { 2036 VarDecl *VD = cast<VarDecl>(New); 2037 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2038 VarDecl::TentativeDefinition 2039 ? diag::err_alias_after_tentative 2040 : diag::err_redefinition; 2041 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2042 S.Diag(Def->getLocation(), diag::note_previous_definition); 2043 VD->setInvalidDecl(); 2044 } 2045 ++I; 2046 continue; 2047 } 2048 2049 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2050 // Tentative definitions are only interesting for the alias check above. 2051 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2052 ++I; 2053 continue; 2054 } 2055 } 2056 2057 if (hasAttribute(Def, NewAttribute->getKind())) { 2058 ++I; 2059 continue; // regular attr merging will take care of validating this. 2060 } 2061 2062 if (isa<C11NoReturnAttr>(NewAttribute)) { 2063 // C's _Noreturn is allowed to be added to a function after it is defined. 2064 ++I; 2065 continue; 2066 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2067 if (AA->isAlignas()) { 2068 // C++11 [dcl.align]p6: 2069 // if any declaration of an entity has an alignment-specifier, 2070 // every defining declaration of that entity shall specify an 2071 // equivalent alignment. 2072 // C11 6.7.5/7: 2073 // If the definition of an object does not have an alignment 2074 // specifier, any other declaration of that object shall also 2075 // have no alignment specifier. 2076 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2077 << AA; 2078 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2079 << AA; 2080 NewAttributes.erase(NewAttributes.begin() + I); 2081 --E; 2082 continue; 2083 } 2084 } 2085 2086 S.Diag(NewAttribute->getLocation(), 2087 diag::warn_attribute_precede_definition); 2088 S.Diag(Def->getLocation(), diag::note_previous_definition); 2089 NewAttributes.erase(NewAttributes.begin() + I); 2090 --E; 2091 } 2092 } 2093 2094 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2095 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2096 AvailabilityMergeKind AMK) { 2097 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2098 UsedAttr *NewAttr = OldAttr->clone(Context); 2099 NewAttr->setInherited(true); 2100 New->addAttr(NewAttr); 2101 } 2102 2103 if (!Old->hasAttrs() && !New->hasAttrs()) 2104 return; 2105 2106 // attributes declared post-definition are currently ignored 2107 checkNewAttributesAfterDef(*this, New, Old); 2108 2109 if (!Old->hasAttrs()) 2110 return; 2111 2112 bool foundAny = New->hasAttrs(); 2113 2114 // Ensure that any moving of objects within the allocated map is done before 2115 // we process them. 2116 if (!foundAny) New->setAttrs(AttrVec()); 2117 2118 for (specific_attr_iterator<InheritableAttr> 2119 i = Old->specific_attr_begin<InheritableAttr>(), 2120 e = Old->specific_attr_end<InheritableAttr>(); 2121 i != e; ++i) { 2122 bool Override = false; 2123 // Ignore deprecated/unavailable/availability attributes if requested. 2124 if (isa<DeprecatedAttr>(*i) || 2125 isa<UnavailableAttr>(*i) || 2126 isa<AvailabilityAttr>(*i)) { 2127 switch (AMK) { 2128 case AMK_None: 2129 continue; 2130 2131 case AMK_Redeclaration: 2132 break; 2133 2134 case AMK_Override: 2135 Override = true; 2136 break; 2137 } 2138 } 2139 2140 // Already handled. 2141 if (isa<UsedAttr>(*i)) 2142 continue; 2143 2144 if (mergeDeclAttribute(*this, New, *i, Override)) 2145 foundAny = true; 2146 } 2147 2148 if (mergeAlignedAttrs(*this, New, Old)) 2149 foundAny = true; 2150 2151 if (!foundAny) New->dropAttrs(); 2152 } 2153 2154 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2155 /// to the new one. 2156 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2157 const ParmVarDecl *oldDecl, 2158 Sema &S) { 2159 // C++11 [dcl.attr.depend]p2: 2160 // The first declaration of a function shall specify the 2161 // carries_dependency attribute for its declarator-id if any declaration 2162 // of the function specifies the carries_dependency attribute. 2163 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2164 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2165 S.Diag(CDA->getLocation(), 2166 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2167 // Find the first declaration of the parameter. 2168 // FIXME: Should we build redeclaration chains for function parameters? 2169 const FunctionDecl *FirstFD = 2170 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2171 const ParmVarDecl *FirstVD = 2172 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2173 S.Diag(FirstVD->getLocation(), 2174 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2175 } 2176 2177 if (!oldDecl->hasAttrs()) 2178 return; 2179 2180 bool foundAny = newDecl->hasAttrs(); 2181 2182 // Ensure that any moving of objects within the allocated map is 2183 // done before we process them. 2184 if (!foundAny) newDecl->setAttrs(AttrVec()); 2185 2186 for (specific_attr_iterator<InheritableParamAttr> 2187 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2188 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2189 if (!DeclHasAttr(newDecl, *i)) { 2190 InheritableAttr *newAttr = 2191 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2192 newAttr->setInherited(true); 2193 newDecl->addAttr(newAttr); 2194 foundAny = true; 2195 } 2196 } 2197 2198 if (!foundAny) newDecl->dropAttrs(); 2199 } 2200 2201 namespace { 2202 2203 /// Used in MergeFunctionDecl to keep track of function parameters in 2204 /// C. 2205 struct GNUCompatibleParamWarning { 2206 ParmVarDecl *OldParm; 2207 ParmVarDecl *NewParm; 2208 QualType PromotedType; 2209 }; 2210 2211 } 2212 2213 /// getSpecialMember - get the special member enum for a method. 2214 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2215 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2216 if (Ctor->isDefaultConstructor()) 2217 return Sema::CXXDefaultConstructor; 2218 2219 if (Ctor->isCopyConstructor()) 2220 return Sema::CXXCopyConstructor; 2221 2222 if (Ctor->isMoveConstructor()) 2223 return Sema::CXXMoveConstructor; 2224 } else if (isa<CXXDestructorDecl>(MD)) { 2225 return Sema::CXXDestructor; 2226 } else if (MD->isCopyAssignmentOperator()) { 2227 return Sema::CXXCopyAssignment; 2228 } else if (MD->isMoveAssignmentOperator()) { 2229 return Sema::CXXMoveAssignment; 2230 } 2231 2232 return Sema::CXXInvalid; 2233 } 2234 2235 /// canRedefineFunction - checks if a function can be redefined. Currently, 2236 /// only extern inline functions can be redefined, and even then only in 2237 /// GNU89 mode. 2238 static bool canRedefineFunction(const FunctionDecl *FD, 2239 const LangOptions& LangOpts) { 2240 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2241 !LangOpts.CPlusPlus && 2242 FD->isInlineSpecified() && 2243 FD->getStorageClass() == SC_Extern); 2244 } 2245 2246 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2247 const AttributedType *AT = T->getAs<AttributedType>(); 2248 while (AT && !AT->isCallingConv()) 2249 AT = AT->getModifiedType()->getAs<AttributedType>(); 2250 return AT; 2251 } 2252 2253 template <typename T> 2254 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2255 const DeclContext *DC = Old->getDeclContext(); 2256 if (DC->isRecord()) 2257 return false; 2258 2259 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2260 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2261 return true; 2262 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2263 return true; 2264 return false; 2265 } 2266 2267 /// MergeFunctionDecl - We just parsed a function 'New' from 2268 /// declarator D which has the same name and scope as a previous 2269 /// declaration 'Old'. Figure out how to resolve this situation, 2270 /// merging decls or emitting diagnostics as appropriate. 2271 /// 2272 /// In C++, New and Old must be declarations that are not 2273 /// overloaded. Use IsOverload to determine whether New and Old are 2274 /// overloaded, and to select the Old declaration that New should be 2275 /// merged with. 2276 /// 2277 /// Returns true if there was an error, false otherwise. 2278 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2279 Scope *S, bool MergeTypeWithOld) { 2280 // Verify the old decl was also a function. 2281 FunctionDecl *Old = OldD->getAsFunction(); 2282 if (!Old) { 2283 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2284 if (New->getFriendObjectKind()) { 2285 Diag(New->getLocation(), diag::err_using_decl_friend); 2286 Diag(Shadow->getTargetDecl()->getLocation(), 2287 diag::note_using_decl_target); 2288 Diag(Shadow->getUsingDecl()->getLocation(), 2289 diag::note_using_decl) << 0; 2290 return true; 2291 } 2292 2293 // C++11 [namespace.udecl]p14: 2294 // If a function declaration in namespace scope or block scope has the 2295 // same name and the same parameter-type-list as a function introduced 2296 // by a using-declaration, and the declarations do not declare the same 2297 // function, the program is ill-formed. 2298 2299 // Check whether the two declarations might declare the same function. 2300 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2301 if (Old && 2302 !Old->getDeclContext()->getRedeclContext()->Equals( 2303 New->getDeclContext()->getRedeclContext()) && 2304 !(Old->isExternC() && New->isExternC())) 2305 Old = 0; 2306 2307 if (!Old) { 2308 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2309 Diag(Shadow->getTargetDecl()->getLocation(), 2310 diag::note_using_decl_target); 2311 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2312 return true; 2313 } 2314 OldD = Old; 2315 } else { 2316 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2317 << New->getDeclName(); 2318 Diag(OldD->getLocation(), diag::note_previous_definition); 2319 return true; 2320 } 2321 } 2322 2323 // If the old declaration is invalid, just give up here. 2324 if (Old->isInvalidDecl()) 2325 return true; 2326 2327 // Determine whether the previous declaration was a definition, 2328 // implicit declaration, or a declaration. 2329 diag::kind PrevDiag; 2330 SourceLocation OldLocation = Old->getLocation(); 2331 if (Old->isThisDeclarationADefinition()) 2332 PrevDiag = diag::note_previous_definition; 2333 else if (Old->isImplicit()) { 2334 PrevDiag = diag::note_previous_implicit_declaration; 2335 if (OldLocation.isInvalid()) 2336 OldLocation = New->getLocation(); 2337 } else 2338 PrevDiag = diag::note_previous_declaration; 2339 2340 // Don't complain about this if we're in GNU89 mode and the old function 2341 // is an extern inline function. 2342 // Don't complain about specializations. They are not supposed to have 2343 // storage classes. 2344 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2345 New->getStorageClass() == SC_Static && 2346 Old->hasExternalFormalLinkage() && 2347 !New->getTemplateSpecializationInfo() && 2348 !canRedefineFunction(Old, getLangOpts())) { 2349 if (getLangOpts().MicrosoftExt) { 2350 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2351 Diag(OldLocation, PrevDiag); 2352 } else { 2353 Diag(New->getLocation(), diag::err_static_non_static) << New; 2354 Diag(OldLocation, PrevDiag); 2355 return true; 2356 } 2357 } 2358 2359 2360 // If a function is first declared with a calling convention, but is later 2361 // declared or defined without one, all following decls assume the calling 2362 // convention of the first. 2363 // 2364 // It's OK if a function is first declared without a calling convention, 2365 // but is later declared or defined with the default calling convention. 2366 // 2367 // To test if either decl has an explicit calling convention, we look for 2368 // AttributedType sugar nodes on the type as written. If they are missing or 2369 // were canonicalized away, we assume the calling convention was implicit. 2370 // 2371 // Note also that we DO NOT return at this point, because we still have 2372 // other tests to run. 2373 QualType OldQType = Context.getCanonicalType(Old->getType()); 2374 QualType NewQType = Context.getCanonicalType(New->getType()); 2375 const FunctionType *OldType = cast<FunctionType>(OldQType); 2376 const FunctionType *NewType = cast<FunctionType>(NewQType); 2377 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2378 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2379 bool RequiresAdjustment = false; 2380 2381 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2382 FunctionDecl *First = Old->getFirstDecl(); 2383 const FunctionType *FT = 2384 First->getType().getCanonicalType()->castAs<FunctionType>(); 2385 FunctionType::ExtInfo FI = FT->getExtInfo(); 2386 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2387 if (!NewCCExplicit) { 2388 // Inherit the CC from the previous declaration if it was specified 2389 // there but not here. 2390 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2391 RequiresAdjustment = true; 2392 } else { 2393 // Calling conventions aren't compatible, so complain. 2394 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2395 Diag(New->getLocation(), diag::err_cconv_change) 2396 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2397 << !FirstCCExplicit 2398 << (!FirstCCExplicit ? "" : 2399 FunctionType::getNameForCallConv(FI.getCC())); 2400 2401 // Put the note on the first decl, since it is the one that matters. 2402 Diag(First->getLocation(), diag::note_previous_declaration); 2403 return true; 2404 } 2405 } 2406 2407 // FIXME: diagnose the other way around? 2408 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2409 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2410 RequiresAdjustment = true; 2411 } 2412 2413 // Merge regparm attribute. 2414 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2415 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2416 if (NewTypeInfo.getHasRegParm()) { 2417 Diag(New->getLocation(), diag::err_regparm_mismatch) 2418 << NewType->getRegParmType() 2419 << OldType->getRegParmType(); 2420 Diag(OldLocation, diag::note_previous_declaration); 2421 return true; 2422 } 2423 2424 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2425 RequiresAdjustment = true; 2426 } 2427 2428 // Merge ns_returns_retained attribute. 2429 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2430 if (NewTypeInfo.getProducesResult()) { 2431 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2432 Diag(OldLocation, diag::note_previous_declaration); 2433 return true; 2434 } 2435 2436 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2437 RequiresAdjustment = true; 2438 } 2439 2440 if (RequiresAdjustment) { 2441 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2442 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2443 New->setType(QualType(AdjustedType, 0)); 2444 NewQType = Context.getCanonicalType(New->getType()); 2445 NewType = cast<FunctionType>(NewQType); 2446 } 2447 2448 // If this redeclaration makes the function inline, we may need to add it to 2449 // UndefinedButUsed. 2450 if (!Old->isInlined() && New->isInlined() && 2451 !New->hasAttr<GNUInlineAttr>() && 2452 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2453 Old->isUsed(false) && 2454 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2455 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2456 SourceLocation())); 2457 2458 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2459 // about it. 2460 if (New->hasAttr<GNUInlineAttr>() && 2461 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2462 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2463 } 2464 2465 if (getLangOpts().CPlusPlus) { 2466 // (C++98 13.1p2): 2467 // Certain function declarations cannot be overloaded: 2468 // -- Function declarations that differ only in the return type 2469 // cannot be overloaded. 2470 2471 // Go back to the type source info to compare the declared return types, 2472 // per C++1y [dcl.type.auto]p13: 2473 // Redeclarations or specializations of a function or function template 2474 // with a declared return type that uses a placeholder type shall also 2475 // use that placeholder, not a deduced type. 2476 QualType OldDeclaredReturnType = 2477 (Old->getTypeSourceInfo() 2478 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2479 : OldType)->getReturnType(); 2480 QualType NewDeclaredReturnType = 2481 (New->getTypeSourceInfo() 2482 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2483 : NewType)->getReturnType(); 2484 QualType ResQT; 2485 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2486 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2487 New->isLocalExternDecl())) { 2488 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2489 OldDeclaredReturnType->isObjCObjectPointerType()) 2490 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2491 if (ResQT.isNull()) { 2492 if (New->isCXXClassMember() && New->isOutOfLine()) 2493 Diag(New->getLocation(), 2494 diag::err_member_def_does_not_match_ret_type) << New; 2495 else 2496 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2497 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2498 return true; 2499 } 2500 else 2501 NewQType = ResQT; 2502 } 2503 2504 QualType OldReturnType = OldType->getReturnType(); 2505 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2506 if (OldReturnType != NewReturnType) { 2507 // If this function has a deduced return type and has already been 2508 // defined, copy the deduced value from the old declaration. 2509 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2510 if (OldAT && OldAT->isDeduced()) { 2511 New->setType( 2512 SubstAutoType(New->getType(), 2513 OldAT->isDependentType() ? Context.DependentTy 2514 : OldAT->getDeducedType())); 2515 NewQType = Context.getCanonicalType( 2516 SubstAutoType(NewQType, 2517 OldAT->isDependentType() ? Context.DependentTy 2518 : OldAT->getDeducedType())); 2519 } 2520 } 2521 2522 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2523 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2524 if (OldMethod && NewMethod) { 2525 // Preserve triviality. 2526 NewMethod->setTrivial(OldMethod->isTrivial()); 2527 2528 // MSVC allows explicit template specialization at class scope: 2529 // 2 CXXMethodDecls referring to the same function will be injected. 2530 // We don't want a redeclaration error. 2531 bool IsClassScopeExplicitSpecialization = 2532 OldMethod->isFunctionTemplateSpecialization() && 2533 NewMethod->isFunctionTemplateSpecialization(); 2534 bool isFriend = NewMethod->getFriendObjectKind(); 2535 2536 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2537 !IsClassScopeExplicitSpecialization) { 2538 // -- Member function declarations with the same name and the 2539 // same parameter types cannot be overloaded if any of them 2540 // is a static member function declaration. 2541 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2542 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2543 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2544 return true; 2545 } 2546 2547 // C++ [class.mem]p1: 2548 // [...] A member shall not be declared twice in the 2549 // member-specification, except that a nested class or member 2550 // class template can be declared and then later defined. 2551 if (ActiveTemplateInstantiations.empty()) { 2552 unsigned NewDiag; 2553 if (isa<CXXConstructorDecl>(OldMethod)) 2554 NewDiag = diag::err_constructor_redeclared; 2555 else if (isa<CXXDestructorDecl>(NewMethod)) 2556 NewDiag = diag::err_destructor_redeclared; 2557 else if (isa<CXXConversionDecl>(NewMethod)) 2558 NewDiag = diag::err_conv_function_redeclared; 2559 else 2560 NewDiag = diag::err_member_redeclared; 2561 2562 Diag(New->getLocation(), NewDiag); 2563 } else { 2564 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2565 << New << New->getType(); 2566 } 2567 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2568 2569 // Complain if this is an explicit declaration of a special 2570 // member that was initially declared implicitly. 2571 // 2572 // As an exception, it's okay to befriend such methods in order 2573 // to permit the implicit constructor/destructor/operator calls. 2574 } else if (OldMethod->isImplicit()) { 2575 if (isFriend) { 2576 NewMethod->setImplicit(); 2577 } else { 2578 Diag(NewMethod->getLocation(), 2579 diag::err_definition_of_implicitly_declared_member) 2580 << New << getSpecialMember(OldMethod); 2581 return true; 2582 } 2583 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2584 Diag(NewMethod->getLocation(), 2585 diag::err_definition_of_explicitly_defaulted_member) 2586 << getSpecialMember(OldMethod); 2587 return true; 2588 } 2589 } 2590 2591 // C++11 [dcl.attr.noreturn]p1: 2592 // The first declaration of a function shall specify the noreturn 2593 // attribute if any declaration of that function specifies the noreturn 2594 // attribute. 2595 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2596 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2597 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2598 Diag(Old->getFirstDecl()->getLocation(), 2599 diag::note_noreturn_missing_first_decl); 2600 } 2601 2602 // C++11 [dcl.attr.depend]p2: 2603 // The first declaration of a function shall specify the 2604 // carries_dependency attribute for its declarator-id if any declaration 2605 // of the function specifies the carries_dependency attribute. 2606 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2607 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2608 Diag(CDA->getLocation(), 2609 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2610 Diag(Old->getFirstDecl()->getLocation(), 2611 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2612 } 2613 2614 // (C++98 8.3.5p3): 2615 // All declarations for a function shall agree exactly in both the 2616 // return type and the parameter-type-list. 2617 // We also want to respect all the extended bits except noreturn. 2618 2619 // noreturn should now match unless the old type info didn't have it. 2620 QualType OldQTypeForComparison = OldQType; 2621 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2622 assert(OldQType == QualType(OldType, 0)); 2623 const FunctionType *OldTypeForComparison 2624 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2625 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2626 assert(OldQTypeForComparison.isCanonical()); 2627 } 2628 2629 if (haveIncompatibleLanguageLinkages(Old, New)) { 2630 // As a special case, retain the language linkage from previous 2631 // declarations of a friend function as an extension. 2632 // 2633 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2634 // and is useful because there's otherwise no way to specify language 2635 // linkage within class scope. 2636 // 2637 // Check cautiously as the friend object kind isn't yet complete. 2638 if (New->getFriendObjectKind() != Decl::FOK_None) { 2639 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2640 Diag(OldLocation, PrevDiag); 2641 } else { 2642 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2643 Diag(OldLocation, PrevDiag); 2644 return true; 2645 } 2646 } 2647 2648 if (OldQTypeForComparison == NewQType) 2649 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2650 2651 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2652 New->isLocalExternDecl()) { 2653 // It's OK if we couldn't merge types for a local function declaraton 2654 // if either the old or new type is dependent. We'll merge the types 2655 // when we instantiate the function. 2656 return false; 2657 } 2658 2659 // Fall through for conflicting redeclarations and redefinitions. 2660 } 2661 2662 // C: Function types need to be compatible, not identical. This handles 2663 // duplicate function decls like "void f(int); void f(enum X);" properly. 2664 if (!getLangOpts().CPlusPlus && 2665 Context.typesAreCompatible(OldQType, NewQType)) { 2666 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2667 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2668 const FunctionProtoType *OldProto = 0; 2669 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2670 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2671 // The old declaration provided a function prototype, but the 2672 // new declaration does not. Merge in the prototype. 2673 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2674 SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(), 2675 OldProto->param_type_end()); 2676 NewQType = 2677 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2678 OldProto->getExtProtoInfo()); 2679 New->setType(NewQType); 2680 New->setHasInheritedPrototype(); 2681 2682 // Synthesize a parameter for each argument type. 2683 SmallVector<ParmVarDecl*, 16> Params; 2684 for (FunctionProtoType::param_type_iterator 2685 ParamType = OldProto->param_type_begin(), 2686 ParamEnd = OldProto->param_type_end(); 2687 ParamType != ParamEnd; ++ParamType) { 2688 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2689 SourceLocation(), 2690 SourceLocation(), 0, 2691 *ParamType, /*TInfo=*/0, 2692 SC_None, 2693 0); 2694 Param->setScopeInfo(0, Params.size()); 2695 Param->setImplicit(); 2696 Params.push_back(Param); 2697 } 2698 2699 New->setParams(Params); 2700 } 2701 2702 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2703 } 2704 2705 // GNU C permits a K&R definition to follow a prototype declaration 2706 // if the declared types of the parameters in the K&R definition 2707 // match the types in the prototype declaration, even when the 2708 // promoted types of the parameters from the K&R definition differ 2709 // from the types in the prototype. GCC then keeps the types from 2710 // the prototype. 2711 // 2712 // If a variadic prototype is followed by a non-variadic K&R definition, 2713 // the K&R definition becomes variadic. This is sort of an edge case, but 2714 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2715 // C99 6.9.1p8. 2716 if (!getLangOpts().CPlusPlus && 2717 Old->hasPrototype() && !New->hasPrototype() && 2718 New->getType()->getAs<FunctionProtoType>() && 2719 Old->getNumParams() == New->getNumParams()) { 2720 SmallVector<QualType, 16> ArgTypes; 2721 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2722 const FunctionProtoType *OldProto 2723 = Old->getType()->getAs<FunctionProtoType>(); 2724 const FunctionProtoType *NewProto 2725 = New->getType()->getAs<FunctionProtoType>(); 2726 2727 // Determine whether this is the GNU C extension. 2728 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2729 NewProto->getReturnType()); 2730 bool LooseCompatible = !MergedReturn.isNull(); 2731 for (unsigned Idx = 0, End = Old->getNumParams(); 2732 LooseCompatible && Idx != End; ++Idx) { 2733 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2734 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2735 if (Context.typesAreCompatible(OldParm->getType(), 2736 NewProto->getParamType(Idx))) { 2737 ArgTypes.push_back(NewParm->getType()); 2738 } else if (Context.typesAreCompatible(OldParm->getType(), 2739 NewParm->getType(), 2740 /*CompareUnqualified=*/true)) { 2741 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2742 NewProto->getParamType(Idx) }; 2743 Warnings.push_back(Warn); 2744 ArgTypes.push_back(NewParm->getType()); 2745 } else 2746 LooseCompatible = false; 2747 } 2748 2749 if (LooseCompatible) { 2750 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2751 Diag(Warnings[Warn].NewParm->getLocation(), 2752 diag::ext_param_promoted_not_compatible_with_prototype) 2753 << Warnings[Warn].PromotedType 2754 << Warnings[Warn].OldParm->getType(); 2755 if (Warnings[Warn].OldParm->getLocation().isValid()) 2756 Diag(Warnings[Warn].OldParm->getLocation(), 2757 diag::note_previous_declaration); 2758 } 2759 2760 if (MergeTypeWithOld) 2761 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2762 OldProto->getExtProtoInfo())); 2763 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2764 } 2765 2766 // Fall through to diagnose conflicting types. 2767 } 2768 2769 // A function that has already been declared has been redeclared or 2770 // defined with a different type; show an appropriate diagnostic. 2771 2772 // If the previous declaration was an implicitly-generated builtin 2773 // declaration, then at the very least we should use a specialized note. 2774 unsigned BuiltinID; 2775 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2776 // If it's actually a library-defined builtin function like 'malloc' 2777 // or 'printf', just warn about the incompatible redeclaration. 2778 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2779 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2780 Diag(OldLocation, diag::note_previous_builtin_declaration) 2781 << Old << Old->getType(); 2782 2783 // If this is a global redeclaration, just forget hereafter 2784 // about the "builtin-ness" of the function. 2785 // 2786 // Doing this for local extern declarations is problematic. If 2787 // the builtin declaration remains visible, a second invalid 2788 // local declaration will produce a hard error; if it doesn't 2789 // remain visible, a single bogus local redeclaration (which is 2790 // actually only a warning) could break all the downstream code. 2791 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2792 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2793 2794 return false; 2795 } 2796 2797 PrevDiag = diag::note_previous_builtin_declaration; 2798 } 2799 2800 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2801 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2802 return true; 2803 } 2804 2805 /// \brief Completes the merge of two function declarations that are 2806 /// known to be compatible. 2807 /// 2808 /// This routine handles the merging of attributes and other 2809 /// properties of function declarations from the old declaration to 2810 /// the new declaration, once we know that New is in fact a 2811 /// redeclaration of Old. 2812 /// 2813 /// \returns false 2814 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2815 Scope *S, bool MergeTypeWithOld) { 2816 // Merge the attributes 2817 mergeDeclAttributes(New, Old); 2818 2819 // Merge "pure" flag. 2820 if (Old->isPure()) 2821 New->setPure(); 2822 2823 // Merge "used" flag. 2824 if (Old->getMostRecentDecl()->isUsed(false)) 2825 New->setIsUsed(); 2826 2827 // Merge attributes from the parameters. These can mismatch with K&R 2828 // declarations. 2829 if (New->getNumParams() == Old->getNumParams()) 2830 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2831 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2832 *this); 2833 2834 if (getLangOpts().CPlusPlus) 2835 return MergeCXXFunctionDecl(New, Old, S); 2836 2837 // Merge the function types so the we get the composite types for the return 2838 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2839 // was visible. 2840 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2841 if (!Merged.isNull() && MergeTypeWithOld) 2842 New->setType(Merged); 2843 2844 return false; 2845 } 2846 2847 2848 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2849 ObjCMethodDecl *oldMethod) { 2850 2851 // Merge the attributes, including deprecated/unavailable 2852 AvailabilityMergeKind MergeKind = 2853 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2854 : AMK_Override; 2855 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2856 2857 // Merge attributes from the parameters. 2858 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2859 oe = oldMethod->param_end(); 2860 for (ObjCMethodDecl::param_iterator 2861 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2862 ni != ne && oi != oe; ++ni, ++oi) 2863 mergeParamDeclAttributes(*ni, *oi, *this); 2864 2865 CheckObjCMethodOverride(newMethod, oldMethod); 2866 } 2867 2868 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2869 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2870 /// emitting diagnostics as appropriate. 2871 /// 2872 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2873 /// to here in AddInitializerToDecl. We can't check them before the initializer 2874 /// is attached. 2875 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2876 bool MergeTypeWithOld) { 2877 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2878 return; 2879 2880 QualType MergedT; 2881 if (getLangOpts().CPlusPlus) { 2882 if (New->getType()->isUndeducedType()) { 2883 // We don't know what the new type is until the initializer is attached. 2884 return; 2885 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2886 // These could still be something that needs exception specs checked. 2887 return MergeVarDeclExceptionSpecs(New, Old); 2888 } 2889 // C++ [basic.link]p10: 2890 // [...] the types specified by all declarations referring to a given 2891 // object or function shall be identical, except that declarations for an 2892 // array object can specify array types that differ by the presence or 2893 // absence of a major array bound (8.3.4). 2894 else if (Old->getType()->isIncompleteArrayType() && 2895 New->getType()->isArrayType()) { 2896 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2897 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2898 if (Context.hasSameType(OldArray->getElementType(), 2899 NewArray->getElementType())) 2900 MergedT = New->getType(); 2901 } else if (Old->getType()->isArrayType() && 2902 New->getType()->isIncompleteArrayType()) { 2903 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2904 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2905 if (Context.hasSameType(OldArray->getElementType(), 2906 NewArray->getElementType())) 2907 MergedT = Old->getType(); 2908 } else if (New->getType()->isObjCObjectPointerType() && 2909 Old->getType()->isObjCObjectPointerType()) { 2910 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2911 Old->getType()); 2912 } 2913 } else { 2914 // C 6.2.7p2: 2915 // All declarations that refer to the same object or function shall have 2916 // compatible type. 2917 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2918 } 2919 if (MergedT.isNull()) { 2920 // It's OK if we couldn't merge types if either type is dependent, for a 2921 // block-scope variable. In other cases (static data members of class 2922 // templates, variable templates, ...), we require the types to be 2923 // equivalent. 2924 // FIXME: The C++ standard doesn't say anything about this. 2925 if ((New->getType()->isDependentType() || 2926 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2927 // If the old type was dependent, we can't merge with it, so the new type 2928 // becomes dependent for now. We'll reproduce the original type when we 2929 // instantiate the TypeSourceInfo for the variable. 2930 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2931 New->setType(Context.DependentTy); 2932 return; 2933 } 2934 2935 // FIXME: Even if this merging succeeds, some other non-visible declaration 2936 // of this variable might have an incompatible type. For instance: 2937 // 2938 // extern int arr[]; 2939 // void f() { extern int arr[2]; } 2940 // void g() { extern int arr[3]; } 2941 // 2942 // Neither C nor C++ requires a diagnostic for this, but we should still try 2943 // to diagnose it. 2944 Diag(New->getLocation(), diag::err_redefinition_different_type) 2945 << New->getDeclName() << New->getType() << Old->getType(); 2946 Diag(Old->getLocation(), diag::note_previous_definition); 2947 return New->setInvalidDecl(); 2948 } 2949 2950 // Don't actually update the type on the new declaration if the old 2951 // declaration was an extern declaration in a different scope. 2952 if (MergeTypeWithOld) 2953 New->setType(MergedT); 2954 } 2955 2956 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2957 LookupResult &Previous) { 2958 // C11 6.2.7p4: 2959 // For an identifier with internal or external linkage declared 2960 // in a scope in which a prior declaration of that identifier is 2961 // visible, if the prior declaration specifies internal or 2962 // external linkage, the type of the identifier at the later 2963 // declaration becomes the composite type. 2964 // 2965 // If the variable isn't visible, we do not merge with its type. 2966 if (Previous.isShadowed()) 2967 return false; 2968 2969 if (S.getLangOpts().CPlusPlus) { 2970 // C++11 [dcl.array]p3: 2971 // If there is a preceding declaration of the entity in the same 2972 // scope in which the bound was specified, an omitted array bound 2973 // is taken to be the same as in that earlier declaration. 2974 return NewVD->isPreviousDeclInSameBlockScope() || 2975 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2976 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2977 } else { 2978 // If the old declaration was function-local, don't merge with its 2979 // type unless we're in the same function. 2980 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2981 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2982 } 2983 } 2984 2985 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2986 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2987 /// situation, merging decls or emitting diagnostics as appropriate. 2988 /// 2989 /// Tentative definition rules (C99 6.9.2p2) are checked by 2990 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2991 /// definitions here, since the initializer hasn't been attached. 2992 /// 2993 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2994 // If the new decl is already invalid, don't do any other checking. 2995 if (New->isInvalidDecl()) 2996 return; 2997 2998 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 2999 3000 // Verify the old decl was also a variable or variable template. 3001 VarDecl *Old = 0; 3002 VarTemplateDecl *OldTemplate = 0; 3003 if (Previous.isSingleResult()) { 3004 if (NewTemplate) { 3005 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3006 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0; 3007 } else 3008 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3009 } 3010 if (!Old) { 3011 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3012 << New->getDeclName(); 3013 Diag(Previous.getRepresentativeDecl()->getLocation(), 3014 diag::note_previous_definition); 3015 return New->setInvalidDecl(); 3016 } 3017 3018 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3019 return; 3020 3021 // Ensure the template parameters are compatible. 3022 if (NewTemplate && 3023 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3024 OldTemplate->getTemplateParameters(), 3025 /*Complain=*/true, TPL_TemplateMatch)) 3026 return; 3027 3028 // C++ [class.mem]p1: 3029 // A member shall not be declared twice in the member-specification [...] 3030 // 3031 // Here, we need only consider static data members. 3032 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3033 Diag(New->getLocation(), diag::err_duplicate_member) 3034 << New->getIdentifier(); 3035 Diag(Old->getLocation(), diag::note_previous_declaration); 3036 New->setInvalidDecl(); 3037 } 3038 3039 mergeDeclAttributes(New, Old); 3040 // Warn if an already-declared variable is made a weak_import in a subsequent 3041 // declaration 3042 if (New->hasAttr<WeakImportAttr>() && 3043 Old->getStorageClass() == SC_None && 3044 !Old->hasAttr<WeakImportAttr>()) { 3045 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3046 Diag(Old->getLocation(), diag::note_previous_definition); 3047 // Remove weak_import attribute on new declaration. 3048 New->dropAttr<WeakImportAttr>(); 3049 } 3050 3051 // Merge the types. 3052 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3053 3054 if (New->isInvalidDecl()) 3055 return; 3056 3057 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3058 if (New->getStorageClass() == SC_Static && 3059 !New->isStaticDataMember() && 3060 Old->hasExternalFormalLinkage()) { 3061 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3062 Diag(Old->getLocation(), diag::note_previous_definition); 3063 return New->setInvalidDecl(); 3064 } 3065 // C99 6.2.2p4: 3066 // For an identifier declared with the storage-class specifier 3067 // extern in a scope in which a prior declaration of that 3068 // identifier is visible,23) if the prior declaration specifies 3069 // internal or external linkage, the linkage of the identifier at 3070 // the later declaration is the same as the linkage specified at 3071 // the prior declaration. If no prior declaration is visible, or 3072 // if the prior declaration specifies no linkage, then the 3073 // identifier has external linkage. 3074 if (New->hasExternalStorage() && Old->hasLinkage()) 3075 /* Okay */; 3076 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3077 !New->isStaticDataMember() && 3078 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3079 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3080 Diag(Old->getLocation(), diag::note_previous_definition); 3081 return New->setInvalidDecl(); 3082 } 3083 3084 // Check if extern is followed by non-extern and vice-versa. 3085 if (New->hasExternalStorage() && 3086 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3087 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3088 Diag(Old->getLocation(), diag::note_previous_definition); 3089 return New->setInvalidDecl(); 3090 } 3091 if (Old->hasLinkage() && New->isLocalVarDecl() && 3092 !New->hasExternalStorage()) { 3093 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3094 Diag(Old->getLocation(), diag::note_previous_definition); 3095 return New->setInvalidDecl(); 3096 } 3097 3098 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3099 3100 // FIXME: The test for external storage here seems wrong? We still 3101 // need to check for mismatches. 3102 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3103 // Don't complain about out-of-line definitions of static members. 3104 !(Old->getLexicalDeclContext()->isRecord() && 3105 !New->getLexicalDeclContext()->isRecord())) { 3106 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3107 Diag(Old->getLocation(), diag::note_previous_definition); 3108 return New->setInvalidDecl(); 3109 } 3110 3111 if (New->getTLSKind() != Old->getTLSKind()) { 3112 if (!Old->getTLSKind()) { 3113 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3114 Diag(Old->getLocation(), diag::note_previous_declaration); 3115 } else if (!New->getTLSKind()) { 3116 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3117 Diag(Old->getLocation(), diag::note_previous_declaration); 3118 } else { 3119 // Do not allow redeclaration to change the variable between requiring 3120 // static and dynamic initialization. 3121 // FIXME: GCC allows this, but uses the TLS keyword on the first 3122 // declaration to determine the kind. Do we need to be compatible here? 3123 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3124 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3125 Diag(Old->getLocation(), diag::note_previous_declaration); 3126 } 3127 } 3128 3129 // C++ doesn't have tentative definitions, so go right ahead and check here. 3130 const VarDecl *Def; 3131 if (getLangOpts().CPlusPlus && 3132 New->isThisDeclarationADefinition() == VarDecl::Definition && 3133 (Def = Old->getDefinition())) { 3134 Diag(New->getLocation(), diag::err_redefinition) << New; 3135 Diag(Def->getLocation(), diag::note_previous_definition); 3136 New->setInvalidDecl(); 3137 return; 3138 } 3139 3140 if (haveIncompatibleLanguageLinkages(Old, New)) { 3141 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3142 Diag(Old->getLocation(), diag::note_previous_definition); 3143 New->setInvalidDecl(); 3144 return; 3145 } 3146 3147 // Merge "used" flag. 3148 if (Old->getMostRecentDecl()->isUsed(false)) 3149 New->setIsUsed(); 3150 3151 // Keep a chain of previous declarations. 3152 New->setPreviousDecl(Old); 3153 if (NewTemplate) 3154 NewTemplate->setPreviousDecl(OldTemplate); 3155 3156 // Inherit access appropriately. 3157 New->setAccess(Old->getAccess()); 3158 if (NewTemplate) 3159 NewTemplate->setAccess(New->getAccess()); 3160 } 3161 3162 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3163 /// no declarator (e.g. "struct foo;") is parsed. 3164 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3165 DeclSpec &DS) { 3166 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3167 } 3168 3169 static void HandleTagNumbering(Sema &S, const TagDecl *Tag) { 3170 if (!S.Context.getLangOpts().CPlusPlus) 3171 return; 3172 3173 if (isa<CXXRecordDecl>(Tag->getParent())) { 3174 // If this tag is the direct child of a class, number it if 3175 // it is anonymous. 3176 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3177 return; 3178 MangleNumberingContext &MCtx = 3179 S.Context.getManglingNumberContext(Tag->getParent()); 3180 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag)); 3181 return; 3182 } 3183 3184 // If this tag isn't a direct child of a class, number it if it is local. 3185 Decl *ManglingContextDecl; 3186 if (MangleNumberingContext *MCtx = 3187 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3188 ManglingContextDecl)) { 3189 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag)); 3190 } 3191 } 3192 3193 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3194 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3195 /// parameters to cope with template friend declarations. 3196 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3197 DeclSpec &DS, 3198 MultiTemplateParamsArg TemplateParams, 3199 bool IsExplicitInstantiation) { 3200 Decl *TagD = 0; 3201 TagDecl *Tag = 0; 3202 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3203 DS.getTypeSpecType() == DeclSpec::TST_struct || 3204 DS.getTypeSpecType() == DeclSpec::TST_interface || 3205 DS.getTypeSpecType() == DeclSpec::TST_union || 3206 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3207 TagD = DS.getRepAsDecl(); 3208 3209 if (!TagD) // We probably had an error 3210 return 0; 3211 3212 // Note that the above type specs guarantee that the 3213 // type rep is a Decl, whereas in many of the others 3214 // it's a Type. 3215 if (isa<TagDecl>(TagD)) 3216 Tag = cast<TagDecl>(TagD); 3217 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3218 Tag = CTD->getTemplatedDecl(); 3219 } 3220 3221 if (Tag) { 3222 HandleTagNumbering(*this, Tag); 3223 Tag->setFreeStanding(); 3224 if (Tag->isInvalidDecl()) 3225 return Tag; 3226 } 3227 3228 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3229 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3230 // or incomplete types shall not be restrict-qualified." 3231 if (TypeQuals & DeclSpec::TQ_restrict) 3232 Diag(DS.getRestrictSpecLoc(), 3233 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3234 << DS.getSourceRange(); 3235 } 3236 3237 if (DS.isConstexprSpecified()) { 3238 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3239 // and definitions of functions and variables. 3240 if (Tag) 3241 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3242 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3243 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3244 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3245 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3246 else 3247 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3248 // Don't emit warnings after this error. 3249 return TagD; 3250 } 3251 3252 DiagnoseFunctionSpecifiers(DS); 3253 3254 if (DS.isFriendSpecified()) { 3255 // If we're dealing with a decl but not a TagDecl, assume that 3256 // whatever routines created it handled the friendship aspect. 3257 if (TagD && !Tag) 3258 return 0; 3259 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3260 } 3261 3262 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3263 bool IsExplicitSpecialization = 3264 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3265 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3266 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3267 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3268 // nested-name-specifier unless it is an explicit instantiation 3269 // or an explicit specialization. 3270 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3271 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3272 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3273 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3274 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3275 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3276 << SS.getRange(); 3277 return 0; 3278 } 3279 3280 // Track whether this decl-specifier declares anything. 3281 bool DeclaresAnything = true; 3282 3283 // Handle anonymous struct definitions. 3284 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3285 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3286 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3287 if (getLangOpts().CPlusPlus || 3288 Record->getDeclContext()->isRecord()) 3289 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3290 3291 DeclaresAnything = false; 3292 } 3293 } 3294 3295 // Check for Microsoft C extension: anonymous struct member. 3296 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3297 CurContext->isRecord() && 3298 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3299 // Handle 2 kinds of anonymous struct: 3300 // struct STRUCT; 3301 // and 3302 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3303 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3304 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3305 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3306 DS.getRepAsType().get()->isStructureType())) { 3307 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3308 << DS.getSourceRange(); 3309 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3310 } 3311 } 3312 3313 // Skip all the checks below if we have a type error. 3314 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3315 (TagD && TagD->isInvalidDecl())) 3316 return TagD; 3317 3318 if (getLangOpts().CPlusPlus && 3319 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3320 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3321 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3322 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3323 DeclaresAnything = false; 3324 3325 if (!DS.isMissingDeclaratorOk()) { 3326 // Customize diagnostic for a typedef missing a name. 3327 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3328 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3329 << DS.getSourceRange(); 3330 else 3331 DeclaresAnything = false; 3332 } 3333 3334 if (DS.isModulePrivateSpecified() && 3335 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3336 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3337 << Tag->getTagKind() 3338 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3339 3340 ActOnDocumentableDecl(TagD); 3341 3342 // C 6.7/2: 3343 // A declaration [...] shall declare at least a declarator [...], a tag, 3344 // or the members of an enumeration. 3345 // C++ [dcl.dcl]p3: 3346 // [If there are no declarators], and except for the declaration of an 3347 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3348 // names into the program, or shall redeclare a name introduced by a 3349 // previous declaration. 3350 if (!DeclaresAnything) { 3351 // In C, we allow this as a (popular) extension / bug. Don't bother 3352 // producing further diagnostics for redundant qualifiers after this. 3353 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3354 return TagD; 3355 } 3356 3357 // C++ [dcl.stc]p1: 3358 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3359 // init-declarator-list of the declaration shall not be empty. 3360 // C++ [dcl.fct.spec]p1: 3361 // If a cv-qualifier appears in a decl-specifier-seq, the 3362 // init-declarator-list of the declaration shall not be empty. 3363 // 3364 // Spurious qualifiers here appear to be valid in C. 3365 unsigned DiagID = diag::warn_standalone_specifier; 3366 if (getLangOpts().CPlusPlus) 3367 DiagID = diag::ext_standalone_specifier; 3368 3369 // Note that a linkage-specification sets a storage class, but 3370 // 'extern "C" struct foo;' is actually valid and not theoretically 3371 // useless. 3372 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3373 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3374 Diag(DS.getStorageClassSpecLoc(), DiagID) 3375 << DeclSpec::getSpecifierName(SCS); 3376 3377 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3378 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3379 << DeclSpec::getSpecifierName(TSCS); 3380 if (DS.getTypeQualifiers()) { 3381 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3382 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3383 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3384 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3385 // Restrict is covered above. 3386 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3387 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3388 } 3389 3390 // Warn about ignored type attributes, for example: 3391 // __attribute__((aligned)) struct A; 3392 // Attributes should be placed after tag to apply to type declaration. 3393 if (!DS.getAttributes().empty()) { 3394 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3395 if (TypeSpecType == DeclSpec::TST_class || 3396 TypeSpecType == DeclSpec::TST_struct || 3397 TypeSpecType == DeclSpec::TST_interface || 3398 TypeSpecType == DeclSpec::TST_union || 3399 TypeSpecType == DeclSpec::TST_enum) { 3400 AttributeList* attrs = DS.getAttributes().getList(); 3401 while (attrs) { 3402 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3403 << attrs->getName() 3404 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3405 TypeSpecType == DeclSpec::TST_struct ? 1 : 3406 TypeSpecType == DeclSpec::TST_union ? 2 : 3407 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3408 attrs = attrs->getNext(); 3409 } 3410 } 3411 } 3412 3413 return TagD; 3414 } 3415 3416 /// We are trying to inject an anonymous member into the given scope; 3417 /// check if there's an existing declaration that can't be overloaded. 3418 /// 3419 /// \return true if this is a forbidden redeclaration 3420 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3421 Scope *S, 3422 DeclContext *Owner, 3423 DeclarationName Name, 3424 SourceLocation NameLoc, 3425 unsigned diagnostic) { 3426 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3427 Sema::ForRedeclaration); 3428 if (!SemaRef.LookupName(R, S)) return false; 3429 3430 if (R.getAsSingle<TagDecl>()) 3431 return false; 3432 3433 // Pick a representative declaration. 3434 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3435 assert(PrevDecl && "Expected a non-null Decl"); 3436 3437 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3438 return false; 3439 3440 SemaRef.Diag(NameLoc, diagnostic) << Name; 3441 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3442 3443 return true; 3444 } 3445 3446 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3447 /// anonymous struct or union AnonRecord into the owning context Owner 3448 /// and scope S. This routine will be invoked just after we realize 3449 /// that an unnamed union or struct is actually an anonymous union or 3450 /// struct, e.g., 3451 /// 3452 /// @code 3453 /// union { 3454 /// int i; 3455 /// float f; 3456 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3457 /// // f into the surrounding scope.x 3458 /// @endcode 3459 /// 3460 /// This routine is recursive, injecting the names of nested anonymous 3461 /// structs/unions into the owning context and scope as well. 3462 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3463 DeclContext *Owner, 3464 RecordDecl *AnonRecord, 3465 AccessSpecifier AS, 3466 SmallVectorImpl<NamedDecl *> &Chaining, 3467 bool MSAnonStruct) { 3468 unsigned diagKind 3469 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3470 : diag::err_anonymous_struct_member_redecl; 3471 3472 bool Invalid = false; 3473 3474 // Look every FieldDecl and IndirectFieldDecl with a name. 3475 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3476 DEnd = AnonRecord->decls_end(); 3477 D != DEnd; ++D) { 3478 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3479 cast<NamedDecl>(*D)->getDeclName()) { 3480 ValueDecl *VD = cast<ValueDecl>(*D); 3481 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3482 VD->getLocation(), diagKind)) { 3483 // C++ [class.union]p2: 3484 // The names of the members of an anonymous union shall be 3485 // distinct from the names of any other entity in the 3486 // scope in which the anonymous union is declared. 3487 Invalid = true; 3488 } else { 3489 // C++ [class.union]p2: 3490 // For the purpose of name lookup, after the anonymous union 3491 // definition, the members of the anonymous union are 3492 // considered to have been defined in the scope in which the 3493 // anonymous union is declared. 3494 unsigned OldChainingSize = Chaining.size(); 3495 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3496 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3497 PE = IF->chain_end(); PI != PE; ++PI) 3498 Chaining.push_back(*PI); 3499 else 3500 Chaining.push_back(VD); 3501 3502 assert(Chaining.size() >= 2); 3503 NamedDecl **NamedChain = 3504 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3505 for (unsigned i = 0; i < Chaining.size(); i++) 3506 NamedChain[i] = Chaining[i]; 3507 3508 IndirectFieldDecl* IndirectField = 3509 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3510 VD->getIdentifier(), VD->getType(), 3511 NamedChain, Chaining.size()); 3512 3513 IndirectField->setAccess(AS); 3514 IndirectField->setImplicit(); 3515 SemaRef.PushOnScopeChains(IndirectField, S); 3516 3517 // That includes picking up the appropriate access specifier. 3518 if (AS != AS_none) IndirectField->setAccess(AS); 3519 3520 Chaining.resize(OldChainingSize); 3521 } 3522 } 3523 } 3524 3525 return Invalid; 3526 } 3527 3528 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3529 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3530 /// illegal input values are mapped to SC_None. 3531 static StorageClass 3532 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3533 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3534 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3535 "Parser allowed 'typedef' as storage class VarDecl."); 3536 switch (StorageClassSpec) { 3537 case DeclSpec::SCS_unspecified: return SC_None; 3538 case DeclSpec::SCS_extern: 3539 if (DS.isExternInLinkageSpec()) 3540 return SC_None; 3541 return SC_Extern; 3542 case DeclSpec::SCS_static: return SC_Static; 3543 case DeclSpec::SCS_auto: return SC_Auto; 3544 case DeclSpec::SCS_register: return SC_Register; 3545 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3546 // Illegal SCSs map to None: error reporting is up to the caller. 3547 case DeclSpec::SCS_mutable: // Fall through. 3548 case DeclSpec::SCS_typedef: return SC_None; 3549 } 3550 llvm_unreachable("unknown storage class specifier"); 3551 } 3552 3553 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3554 assert(Record->hasInClassInitializer()); 3555 3556 for (DeclContext::decl_iterator I = Record->decls_begin(), 3557 E = Record->decls_end(); 3558 I != E; ++I) { 3559 FieldDecl *FD = dyn_cast<FieldDecl>(*I); 3560 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) 3561 FD = IFD->getAnonField(); 3562 if (FD && FD->hasInClassInitializer()) 3563 return FD->getLocation(); 3564 } 3565 3566 llvm_unreachable("couldn't find in-class initializer"); 3567 } 3568 3569 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3570 SourceLocation DefaultInitLoc) { 3571 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3572 return; 3573 3574 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3575 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3576 } 3577 3578 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3579 CXXRecordDecl *AnonUnion) { 3580 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3581 return; 3582 3583 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3584 } 3585 3586 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3587 /// anonymous structure or union. Anonymous unions are a C++ feature 3588 /// (C++ [class.union]) and a C11 feature; anonymous structures 3589 /// are a C11 feature and GNU C++ extension. 3590 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3591 AccessSpecifier AS, 3592 RecordDecl *Record, 3593 const PrintingPolicy &Policy) { 3594 DeclContext *Owner = Record->getDeclContext(); 3595 3596 // Diagnose whether this anonymous struct/union is an extension. 3597 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3598 Diag(Record->getLocation(), diag::ext_anonymous_union); 3599 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3600 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3601 else if (!Record->isUnion() && !getLangOpts().C11) 3602 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3603 3604 // C and C++ require different kinds of checks for anonymous 3605 // structs/unions. 3606 bool Invalid = false; 3607 if (getLangOpts().CPlusPlus) { 3608 const char* PrevSpec = 0; 3609 unsigned DiagID; 3610 if (Record->isUnion()) { 3611 // C++ [class.union]p6: 3612 // Anonymous unions declared in a named namespace or in the 3613 // global namespace shall be declared static. 3614 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3615 (isa<TranslationUnitDecl>(Owner) || 3616 (isa<NamespaceDecl>(Owner) && 3617 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3618 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3619 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3620 3621 // Recover by adding 'static'. 3622 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3623 PrevSpec, DiagID, Policy); 3624 } 3625 // C++ [class.union]p6: 3626 // A storage class is not allowed in a declaration of an 3627 // anonymous union in a class scope. 3628 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3629 isa<RecordDecl>(Owner)) { 3630 Diag(DS.getStorageClassSpecLoc(), 3631 diag::err_anonymous_union_with_storage_spec) 3632 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3633 3634 // Recover by removing the storage specifier. 3635 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3636 SourceLocation(), 3637 PrevSpec, DiagID, Context.getPrintingPolicy()); 3638 } 3639 } 3640 3641 // Ignore const/volatile/restrict qualifiers. 3642 if (DS.getTypeQualifiers()) { 3643 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3644 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3645 << Record->isUnion() << "const" 3646 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3647 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3648 Diag(DS.getVolatileSpecLoc(), 3649 diag::ext_anonymous_struct_union_qualified) 3650 << Record->isUnion() << "volatile" 3651 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3652 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3653 Diag(DS.getRestrictSpecLoc(), 3654 diag::ext_anonymous_struct_union_qualified) 3655 << Record->isUnion() << "restrict" 3656 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3657 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3658 Diag(DS.getAtomicSpecLoc(), 3659 diag::ext_anonymous_struct_union_qualified) 3660 << Record->isUnion() << "_Atomic" 3661 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3662 3663 DS.ClearTypeQualifiers(); 3664 } 3665 3666 // C++ [class.union]p2: 3667 // The member-specification of an anonymous union shall only 3668 // define non-static data members. [Note: nested types and 3669 // functions cannot be declared within an anonymous union. ] 3670 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3671 MemEnd = Record->decls_end(); 3672 Mem != MemEnd; ++Mem) { 3673 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3674 // C++ [class.union]p3: 3675 // An anonymous union shall not have private or protected 3676 // members (clause 11). 3677 assert(FD->getAccess() != AS_none); 3678 if (FD->getAccess() != AS_public) { 3679 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3680 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3681 Invalid = true; 3682 } 3683 3684 // C++ [class.union]p1 3685 // An object of a class with a non-trivial constructor, a non-trivial 3686 // copy constructor, a non-trivial destructor, or a non-trivial copy 3687 // assignment operator cannot be a member of a union, nor can an 3688 // array of such objects. 3689 if (CheckNontrivialField(FD)) 3690 Invalid = true; 3691 } else if ((*Mem)->isImplicit()) { 3692 // Any implicit members are fine. 3693 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3694 // This is a type that showed up in an 3695 // elaborated-type-specifier inside the anonymous struct or 3696 // union, but which actually declares a type outside of the 3697 // anonymous struct or union. It's okay. 3698 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3699 if (!MemRecord->isAnonymousStructOrUnion() && 3700 MemRecord->getDeclName()) { 3701 // Visual C++ allows type definition in anonymous struct or union. 3702 if (getLangOpts().MicrosoftExt) 3703 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3704 << (int)Record->isUnion(); 3705 else { 3706 // This is a nested type declaration. 3707 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3708 << (int)Record->isUnion(); 3709 Invalid = true; 3710 } 3711 } else { 3712 // This is an anonymous type definition within another anonymous type. 3713 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3714 // not part of standard C++. 3715 Diag(MemRecord->getLocation(), 3716 diag::ext_anonymous_record_with_anonymous_type) 3717 << (int)Record->isUnion(); 3718 } 3719 } else if (isa<AccessSpecDecl>(*Mem)) { 3720 // Any access specifier is fine. 3721 } else { 3722 // We have something that isn't a non-static data 3723 // member. Complain about it. 3724 unsigned DK = diag::err_anonymous_record_bad_member; 3725 if (isa<TypeDecl>(*Mem)) 3726 DK = diag::err_anonymous_record_with_type; 3727 else if (isa<FunctionDecl>(*Mem)) 3728 DK = diag::err_anonymous_record_with_function; 3729 else if (isa<VarDecl>(*Mem)) 3730 DK = diag::err_anonymous_record_with_static; 3731 3732 // Visual C++ allows type definition in anonymous struct or union. 3733 if (getLangOpts().MicrosoftExt && 3734 DK == diag::err_anonymous_record_with_type) 3735 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3736 << (int)Record->isUnion(); 3737 else { 3738 Diag((*Mem)->getLocation(), DK) 3739 << (int)Record->isUnion(); 3740 Invalid = true; 3741 } 3742 } 3743 } 3744 3745 // C++11 [class.union]p8 (DR1460): 3746 // At most one variant member of a union may have a 3747 // brace-or-equal-initializer. 3748 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3749 Owner->isRecord()) 3750 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3751 cast<CXXRecordDecl>(Record)); 3752 } 3753 3754 if (!Record->isUnion() && !Owner->isRecord()) { 3755 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3756 << (int)getLangOpts().CPlusPlus; 3757 Invalid = true; 3758 } 3759 3760 // Mock up a declarator. 3761 Declarator Dc(DS, Declarator::MemberContext); 3762 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3763 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3764 3765 // Create a declaration for this anonymous struct/union. 3766 NamedDecl *Anon = 0; 3767 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3768 Anon = FieldDecl::Create(Context, OwningClass, 3769 DS.getLocStart(), 3770 Record->getLocation(), 3771 /*IdentifierInfo=*/0, 3772 Context.getTypeDeclType(Record), 3773 TInfo, 3774 /*BitWidth=*/0, /*Mutable=*/false, 3775 /*InitStyle=*/ICIS_NoInit); 3776 Anon->setAccess(AS); 3777 if (getLangOpts().CPlusPlus) 3778 FieldCollector->Add(cast<FieldDecl>(Anon)); 3779 } else { 3780 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3781 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3782 if (SCSpec == DeclSpec::SCS_mutable) { 3783 // mutable can only appear on non-static class members, so it's always 3784 // an error here 3785 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3786 Invalid = true; 3787 SC = SC_None; 3788 } 3789 3790 Anon = VarDecl::Create(Context, Owner, 3791 DS.getLocStart(), 3792 Record->getLocation(), /*IdentifierInfo=*/0, 3793 Context.getTypeDeclType(Record), 3794 TInfo, SC); 3795 3796 // Default-initialize the implicit variable. This initialization will be 3797 // trivial in almost all cases, except if a union member has an in-class 3798 // initializer: 3799 // union { int n = 0; }; 3800 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3801 } 3802 Anon->setImplicit(); 3803 3804 // Mark this as an anonymous struct/union type. 3805 Record->setAnonymousStructOrUnion(true); 3806 3807 // Add the anonymous struct/union object to the current 3808 // context. We'll be referencing this object when we refer to one of 3809 // its members. 3810 Owner->addDecl(Anon); 3811 3812 // Inject the members of the anonymous struct/union into the owning 3813 // context and into the identifier resolver chain for name lookup 3814 // purposes. 3815 SmallVector<NamedDecl*, 2> Chain; 3816 Chain.push_back(Anon); 3817 3818 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3819 Chain, false)) 3820 Invalid = true; 3821 3822 if (Invalid) 3823 Anon->setInvalidDecl(); 3824 3825 return Anon; 3826 } 3827 3828 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3829 /// Microsoft C anonymous structure. 3830 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3831 /// Example: 3832 /// 3833 /// struct A { int a; }; 3834 /// struct B { struct A; int b; }; 3835 /// 3836 /// void foo() { 3837 /// B var; 3838 /// var.a = 3; 3839 /// } 3840 /// 3841 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3842 RecordDecl *Record) { 3843 3844 // If there is no Record, get the record via the typedef. 3845 if (!Record) 3846 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3847 3848 // Mock up a declarator. 3849 Declarator Dc(DS, Declarator::TypeNameContext); 3850 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3851 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3852 3853 // Create a declaration for this anonymous struct. 3854 NamedDecl* Anon = FieldDecl::Create(Context, 3855 cast<RecordDecl>(CurContext), 3856 DS.getLocStart(), 3857 DS.getLocStart(), 3858 /*IdentifierInfo=*/0, 3859 Context.getTypeDeclType(Record), 3860 TInfo, 3861 /*BitWidth=*/0, /*Mutable=*/false, 3862 /*InitStyle=*/ICIS_NoInit); 3863 Anon->setImplicit(); 3864 3865 // Add the anonymous struct object to the current context. 3866 CurContext->addDecl(Anon); 3867 3868 // Inject the members of the anonymous struct into the current 3869 // context and into the identifier resolver chain for name lookup 3870 // purposes. 3871 SmallVector<NamedDecl*, 2> Chain; 3872 Chain.push_back(Anon); 3873 3874 RecordDecl *RecordDef = Record->getDefinition(); 3875 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3876 RecordDef, AS_none, 3877 Chain, true)) 3878 Anon->setInvalidDecl(); 3879 3880 return Anon; 3881 } 3882 3883 /// GetNameForDeclarator - Determine the full declaration name for the 3884 /// given Declarator. 3885 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3886 return GetNameFromUnqualifiedId(D.getName()); 3887 } 3888 3889 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3890 DeclarationNameInfo 3891 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3892 DeclarationNameInfo NameInfo; 3893 NameInfo.setLoc(Name.StartLocation); 3894 3895 switch (Name.getKind()) { 3896 3897 case UnqualifiedId::IK_ImplicitSelfParam: 3898 case UnqualifiedId::IK_Identifier: 3899 NameInfo.setName(Name.Identifier); 3900 NameInfo.setLoc(Name.StartLocation); 3901 return NameInfo; 3902 3903 case UnqualifiedId::IK_OperatorFunctionId: 3904 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3905 Name.OperatorFunctionId.Operator)); 3906 NameInfo.setLoc(Name.StartLocation); 3907 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3908 = Name.OperatorFunctionId.SymbolLocations[0]; 3909 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3910 = Name.EndLocation.getRawEncoding(); 3911 return NameInfo; 3912 3913 case UnqualifiedId::IK_LiteralOperatorId: 3914 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3915 Name.Identifier)); 3916 NameInfo.setLoc(Name.StartLocation); 3917 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3918 return NameInfo; 3919 3920 case UnqualifiedId::IK_ConversionFunctionId: { 3921 TypeSourceInfo *TInfo; 3922 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3923 if (Ty.isNull()) 3924 return DeclarationNameInfo(); 3925 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3926 Context.getCanonicalType(Ty))); 3927 NameInfo.setLoc(Name.StartLocation); 3928 NameInfo.setNamedTypeInfo(TInfo); 3929 return NameInfo; 3930 } 3931 3932 case UnqualifiedId::IK_ConstructorName: { 3933 TypeSourceInfo *TInfo; 3934 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3935 if (Ty.isNull()) 3936 return DeclarationNameInfo(); 3937 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3938 Context.getCanonicalType(Ty))); 3939 NameInfo.setLoc(Name.StartLocation); 3940 NameInfo.setNamedTypeInfo(TInfo); 3941 return NameInfo; 3942 } 3943 3944 case UnqualifiedId::IK_ConstructorTemplateId: { 3945 // In well-formed code, we can only have a constructor 3946 // template-id that refers to the current context, so go there 3947 // to find the actual type being constructed. 3948 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3949 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3950 return DeclarationNameInfo(); 3951 3952 // Determine the type of the class being constructed. 3953 QualType CurClassType = Context.getTypeDeclType(CurClass); 3954 3955 // FIXME: Check two things: that the template-id names the same type as 3956 // CurClassType, and that the template-id does not occur when the name 3957 // was qualified. 3958 3959 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3960 Context.getCanonicalType(CurClassType))); 3961 NameInfo.setLoc(Name.StartLocation); 3962 // FIXME: should we retrieve TypeSourceInfo? 3963 NameInfo.setNamedTypeInfo(0); 3964 return NameInfo; 3965 } 3966 3967 case UnqualifiedId::IK_DestructorName: { 3968 TypeSourceInfo *TInfo; 3969 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3970 if (Ty.isNull()) 3971 return DeclarationNameInfo(); 3972 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3973 Context.getCanonicalType(Ty))); 3974 NameInfo.setLoc(Name.StartLocation); 3975 NameInfo.setNamedTypeInfo(TInfo); 3976 return NameInfo; 3977 } 3978 3979 case UnqualifiedId::IK_TemplateId: { 3980 TemplateName TName = Name.TemplateId->Template.get(); 3981 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3982 return Context.getNameForTemplate(TName, TNameLoc); 3983 } 3984 3985 } // switch (Name.getKind()) 3986 3987 llvm_unreachable("Unknown name kind"); 3988 } 3989 3990 static QualType getCoreType(QualType Ty) { 3991 do { 3992 if (Ty->isPointerType() || Ty->isReferenceType()) 3993 Ty = Ty->getPointeeType(); 3994 else if (Ty->isArrayType()) 3995 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3996 else 3997 return Ty.withoutLocalFastQualifiers(); 3998 } while (true); 3999 } 4000 4001 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4002 /// and Definition have "nearly" matching parameters. This heuristic is 4003 /// used to improve diagnostics in the case where an out-of-line function 4004 /// definition doesn't match any declaration within the class or namespace. 4005 /// Also sets Params to the list of indices to the parameters that differ 4006 /// between the declaration and the definition. If hasSimilarParameters 4007 /// returns true and Params is empty, then all of the parameters match. 4008 static bool hasSimilarParameters(ASTContext &Context, 4009 FunctionDecl *Declaration, 4010 FunctionDecl *Definition, 4011 SmallVectorImpl<unsigned> &Params) { 4012 Params.clear(); 4013 if (Declaration->param_size() != Definition->param_size()) 4014 return false; 4015 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4016 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4017 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4018 4019 // The parameter types are identical 4020 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4021 continue; 4022 4023 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4024 QualType DefParamBaseTy = getCoreType(DefParamTy); 4025 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4026 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4027 4028 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4029 (DeclTyName && DeclTyName == DefTyName)) 4030 Params.push_back(Idx); 4031 else // The two parameters aren't even close 4032 return false; 4033 } 4034 4035 return true; 4036 } 4037 4038 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4039 /// declarator needs to be rebuilt in the current instantiation. 4040 /// Any bits of declarator which appear before the name are valid for 4041 /// consideration here. That's specifically the type in the decl spec 4042 /// and the base type in any member-pointer chunks. 4043 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4044 DeclarationName Name) { 4045 // The types we specifically need to rebuild are: 4046 // - typenames, typeofs, and decltypes 4047 // - types which will become injected class names 4048 // Of course, we also need to rebuild any type referencing such a 4049 // type. It's safest to just say "dependent", but we call out a 4050 // few cases here. 4051 4052 DeclSpec &DS = D.getMutableDeclSpec(); 4053 switch (DS.getTypeSpecType()) { 4054 case DeclSpec::TST_typename: 4055 case DeclSpec::TST_typeofType: 4056 case DeclSpec::TST_underlyingType: 4057 case DeclSpec::TST_atomic: { 4058 // Grab the type from the parser. 4059 TypeSourceInfo *TSI = 0; 4060 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4061 if (T.isNull() || !T->isDependentType()) break; 4062 4063 // Make sure there's a type source info. This isn't really much 4064 // of a waste; most dependent types should have type source info 4065 // attached already. 4066 if (!TSI) 4067 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4068 4069 // Rebuild the type in the current instantiation. 4070 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4071 if (!TSI) return true; 4072 4073 // Store the new type back in the decl spec. 4074 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4075 DS.UpdateTypeRep(LocType); 4076 break; 4077 } 4078 4079 case DeclSpec::TST_decltype: 4080 case DeclSpec::TST_typeofExpr: { 4081 Expr *E = DS.getRepAsExpr(); 4082 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4083 if (Result.isInvalid()) return true; 4084 DS.UpdateExprRep(Result.get()); 4085 break; 4086 } 4087 4088 default: 4089 // Nothing to do for these decl specs. 4090 break; 4091 } 4092 4093 // It doesn't matter what order we do this in. 4094 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4095 DeclaratorChunk &Chunk = D.getTypeObject(I); 4096 4097 // The only type information in the declarator which can come 4098 // before the declaration name is the base type of a member 4099 // pointer. 4100 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4101 continue; 4102 4103 // Rebuild the scope specifier in-place. 4104 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4105 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4106 return true; 4107 } 4108 4109 return false; 4110 } 4111 4112 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4113 D.setFunctionDefinitionKind(FDK_Declaration); 4114 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4115 4116 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4117 Dcl && Dcl->getDeclContext()->isFileContext()) 4118 Dcl->setTopLevelDeclInObjCContainer(); 4119 4120 return Dcl; 4121 } 4122 4123 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4124 /// If T is the name of a class, then each of the following shall have a 4125 /// name different from T: 4126 /// - every static data member of class T; 4127 /// - every member function of class T 4128 /// - every member of class T that is itself a type; 4129 /// \returns true if the declaration name violates these rules. 4130 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4131 DeclarationNameInfo NameInfo) { 4132 DeclarationName Name = NameInfo.getName(); 4133 4134 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4135 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4136 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4137 return true; 4138 } 4139 4140 return false; 4141 } 4142 4143 /// \brief Diagnose a declaration whose declarator-id has the given 4144 /// nested-name-specifier. 4145 /// 4146 /// \param SS The nested-name-specifier of the declarator-id. 4147 /// 4148 /// \param DC The declaration context to which the nested-name-specifier 4149 /// resolves. 4150 /// 4151 /// \param Name The name of the entity being declared. 4152 /// 4153 /// \param Loc The location of the name of the entity being declared. 4154 /// 4155 /// \returns true if we cannot safely recover from this error, false otherwise. 4156 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4157 DeclarationName Name, 4158 SourceLocation Loc) { 4159 DeclContext *Cur = CurContext; 4160 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4161 Cur = Cur->getParent(); 4162 4163 // If the user provided a superfluous scope specifier that refers back to the 4164 // class in which the entity is already declared, diagnose and ignore it. 4165 // 4166 // class X { 4167 // void X::f(); 4168 // }; 4169 // 4170 // Note, it was once ill-formed to give redundant qualification in all 4171 // contexts, but that rule was removed by DR482. 4172 if (Cur->Equals(DC)) { 4173 if (Cur->isRecord()) { 4174 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4175 : diag::err_member_extra_qualification) 4176 << Name << FixItHint::CreateRemoval(SS.getRange()); 4177 SS.clear(); 4178 } else { 4179 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4180 } 4181 return false; 4182 } 4183 4184 // Check whether the qualifying scope encloses the scope of the original 4185 // declaration. 4186 if (!Cur->Encloses(DC)) { 4187 if (Cur->isRecord()) 4188 Diag(Loc, diag::err_member_qualification) 4189 << Name << SS.getRange(); 4190 else if (isa<TranslationUnitDecl>(DC)) 4191 Diag(Loc, diag::err_invalid_declarator_global_scope) 4192 << Name << SS.getRange(); 4193 else if (isa<FunctionDecl>(Cur)) 4194 Diag(Loc, diag::err_invalid_declarator_in_function) 4195 << Name << SS.getRange(); 4196 else if (isa<BlockDecl>(Cur)) 4197 Diag(Loc, diag::err_invalid_declarator_in_block) 4198 << Name << SS.getRange(); 4199 else 4200 Diag(Loc, diag::err_invalid_declarator_scope) 4201 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4202 4203 return true; 4204 } 4205 4206 if (Cur->isRecord()) { 4207 // Cannot qualify members within a class. 4208 Diag(Loc, diag::err_member_qualification) 4209 << Name << SS.getRange(); 4210 SS.clear(); 4211 4212 // C++ constructors and destructors with incorrect scopes can break 4213 // our AST invariants by having the wrong underlying types. If 4214 // that's the case, then drop this declaration entirely. 4215 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4216 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4217 !Context.hasSameType(Name.getCXXNameType(), 4218 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4219 return true; 4220 4221 return false; 4222 } 4223 4224 // C++11 [dcl.meaning]p1: 4225 // [...] "The nested-name-specifier of the qualified declarator-id shall 4226 // not begin with a decltype-specifer" 4227 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4228 while (SpecLoc.getPrefix()) 4229 SpecLoc = SpecLoc.getPrefix(); 4230 if (dyn_cast_or_null<DecltypeType>( 4231 SpecLoc.getNestedNameSpecifier()->getAsType())) 4232 Diag(Loc, diag::err_decltype_in_declarator) 4233 << SpecLoc.getTypeLoc().getSourceRange(); 4234 4235 return false; 4236 } 4237 4238 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4239 MultiTemplateParamsArg TemplateParamLists) { 4240 // TODO: consider using NameInfo for diagnostic. 4241 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4242 DeclarationName Name = NameInfo.getName(); 4243 4244 // All of these full declarators require an identifier. If it doesn't have 4245 // one, the ParsedFreeStandingDeclSpec action should be used. 4246 if (!Name) { 4247 if (!D.isInvalidType()) // Reject this if we think it is valid. 4248 Diag(D.getDeclSpec().getLocStart(), 4249 diag::err_declarator_need_ident) 4250 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4251 return 0; 4252 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4253 return 0; 4254 4255 // The scope passed in may not be a decl scope. Zip up the scope tree until 4256 // we find one that is. 4257 while ((S->getFlags() & Scope::DeclScope) == 0 || 4258 (S->getFlags() & Scope::TemplateParamScope) != 0) 4259 S = S->getParent(); 4260 4261 DeclContext *DC = CurContext; 4262 if (D.getCXXScopeSpec().isInvalid()) 4263 D.setInvalidType(); 4264 else if (D.getCXXScopeSpec().isSet()) { 4265 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4266 UPPC_DeclarationQualifier)) 4267 return 0; 4268 4269 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4270 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4271 if (!DC || isa<EnumDecl>(DC)) { 4272 // If we could not compute the declaration context, it's because the 4273 // declaration context is dependent but does not refer to a class, 4274 // class template, or class template partial specialization. Complain 4275 // and return early, to avoid the coming semantic disaster. 4276 Diag(D.getIdentifierLoc(), 4277 diag::err_template_qualified_declarator_no_match) 4278 << D.getCXXScopeSpec().getScopeRep() 4279 << D.getCXXScopeSpec().getRange(); 4280 return 0; 4281 } 4282 bool IsDependentContext = DC->isDependentContext(); 4283 4284 if (!IsDependentContext && 4285 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4286 return 0; 4287 4288 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4289 Diag(D.getIdentifierLoc(), 4290 diag::err_member_def_undefined_record) 4291 << Name << DC << D.getCXXScopeSpec().getRange(); 4292 D.setInvalidType(); 4293 } else if (!D.getDeclSpec().isFriendSpecified()) { 4294 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4295 Name, D.getIdentifierLoc())) { 4296 if (DC->isRecord()) 4297 return 0; 4298 4299 D.setInvalidType(); 4300 } 4301 } 4302 4303 // Check whether we need to rebuild the type of the given 4304 // declaration in the current instantiation. 4305 if (EnteringContext && IsDependentContext && 4306 TemplateParamLists.size() != 0) { 4307 ContextRAII SavedContext(*this, DC); 4308 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4309 D.setInvalidType(); 4310 } 4311 } 4312 4313 if (DiagnoseClassNameShadow(DC, NameInfo)) 4314 // If this is a typedef, we'll end up spewing multiple diagnostics. 4315 // Just return early; it's safer. 4316 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4317 return 0; 4318 4319 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4320 QualType R = TInfo->getType(); 4321 4322 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4323 UPPC_DeclarationType)) 4324 D.setInvalidType(); 4325 4326 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4327 ForRedeclaration); 4328 4329 // See if this is a redefinition of a variable in the same scope. 4330 if (!D.getCXXScopeSpec().isSet()) { 4331 bool IsLinkageLookup = false; 4332 bool CreateBuiltins = false; 4333 4334 // If the declaration we're planning to build will be a function 4335 // or object with linkage, then look for another declaration with 4336 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4337 // 4338 // If the declaration we're planning to build will be declared with 4339 // external linkage in the translation unit, create any builtin with 4340 // the same name. 4341 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4342 /* Do nothing*/; 4343 else if (CurContext->isFunctionOrMethod() && 4344 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4345 R->isFunctionType())) { 4346 IsLinkageLookup = true; 4347 CreateBuiltins = 4348 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4349 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4350 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4351 CreateBuiltins = true; 4352 4353 if (IsLinkageLookup) 4354 Previous.clear(LookupRedeclarationWithLinkage); 4355 4356 LookupName(Previous, S, CreateBuiltins); 4357 } else { // Something like "int foo::x;" 4358 LookupQualifiedName(Previous, DC); 4359 4360 // C++ [dcl.meaning]p1: 4361 // When the declarator-id is qualified, the declaration shall refer to a 4362 // previously declared member of the class or namespace to which the 4363 // qualifier refers (or, in the case of a namespace, of an element of the 4364 // inline namespace set of that namespace (7.3.1)) or to a specialization 4365 // thereof; [...] 4366 // 4367 // Note that we already checked the context above, and that we do not have 4368 // enough information to make sure that Previous contains the declaration 4369 // we want to match. For example, given: 4370 // 4371 // class X { 4372 // void f(); 4373 // void f(float); 4374 // }; 4375 // 4376 // void X::f(int) { } // ill-formed 4377 // 4378 // In this case, Previous will point to the overload set 4379 // containing the two f's declared in X, but neither of them 4380 // matches. 4381 4382 // C++ [dcl.meaning]p1: 4383 // [...] the member shall not merely have been introduced by a 4384 // using-declaration in the scope of the class or namespace nominated by 4385 // the nested-name-specifier of the declarator-id. 4386 RemoveUsingDecls(Previous); 4387 } 4388 4389 if (Previous.isSingleResult() && 4390 Previous.getFoundDecl()->isTemplateParameter()) { 4391 // Maybe we will complain about the shadowed template parameter. 4392 if (!D.isInvalidType()) 4393 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4394 Previous.getFoundDecl()); 4395 4396 // Just pretend that we didn't see the previous declaration. 4397 Previous.clear(); 4398 } 4399 4400 // In C++, the previous declaration we find might be a tag type 4401 // (class or enum). In this case, the new declaration will hide the 4402 // tag type. Note that this does does not apply if we're declaring a 4403 // typedef (C++ [dcl.typedef]p4). 4404 if (Previous.isSingleTagDecl() && 4405 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4406 Previous.clear(); 4407 4408 // Check that there are no default arguments other than in the parameters 4409 // of a function declaration (C++ only). 4410 if (getLangOpts().CPlusPlus) 4411 CheckExtraCXXDefaultArguments(D); 4412 4413 NamedDecl *New; 4414 4415 bool AddToScope = true; 4416 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4417 if (TemplateParamLists.size()) { 4418 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4419 return 0; 4420 } 4421 4422 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4423 } else if (R->isFunctionType()) { 4424 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4425 TemplateParamLists, 4426 AddToScope); 4427 } else { 4428 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4429 AddToScope); 4430 } 4431 4432 if (New == 0) 4433 return 0; 4434 4435 // If this has an identifier and is not an invalid redeclaration or 4436 // function template specialization, add it to the scope stack. 4437 if (New->getDeclName() && AddToScope && 4438 !(D.isRedeclaration() && New->isInvalidDecl())) { 4439 // Only make a locally-scoped extern declaration visible if it is the first 4440 // declaration of this entity. Qualified lookup for such an entity should 4441 // only find this declaration if there is no visible declaration of it. 4442 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4443 PushOnScopeChains(New, S, AddToContext); 4444 if (!AddToContext) 4445 CurContext->addHiddenDecl(New); 4446 } 4447 4448 return New; 4449 } 4450 4451 /// Helper method to turn variable array types into constant array 4452 /// types in certain situations which would otherwise be errors (for 4453 /// GCC compatibility). 4454 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4455 ASTContext &Context, 4456 bool &SizeIsNegative, 4457 llvm::APSInt &Oversized) { 4458 // This method tries to turn a variable array into a constant 4459 // array even when the size isn't an ICE. This is necessary 4460 // for compatibility with code that depends on gcc's buggy 4461 // constant expression folding, like struct {char x[(int)(char*)2];} 4462 SizeIsNegative = false; 4463 Oversized = 0; 4464 4465 if (T->isDependentType()) 4466 return QualType(); 4467 4468 QualifierCollector Qs; 4469 const Type *Ty = Qs.strip(T); 4470 4471 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4472 QualType Pointee = PTy->getPointeeType(); 4473 QualType FixedType = 4474 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4475 Oversized); 4476 if (FixedType.isNull()) return FixedType; 4477 FixedType = Context.getPointerType(FixedType); 4478 return Qs.apply(Context, FixedType); 4479 } 4480 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4481 QualType Inner = PTy->getInnerType(); 4482 QualType FixedType = 4483 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4484 Oversized); 4485 if (FixedType.isNull()) return FixedType; 4486 FixedType = Context.getParenType(FixedType); 4487 return Qs.apply(Context, FixedType); 4488 } 4489 4490 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4491 if (!VLATy) 4492 return QualType(); 4493 // FIXME: We should probably handle this case 4494 if (VLATy->getElementType()->isVariablyModifiedType()) 4495 return QualType(); 4496 4497 llvm::APSInt Res; 4498 if (!VLATy->getSizeExpr() || 4499 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4500 return QualType(); 4501 4502 // Check whether the array size is negative. 4503 if (Res.isSigned() && Res.isNegative()) { 4504 SizeIsNegative = true; 4505 return QualType(); 4506 } 4507 4508 // Check whether the array is too large to be addressed. 4509 unsigned ActiveSizeBits 4510 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4511 Res); 4512 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4513 Oversized = Res; 4514 return QualType(); 4515 } 4516 4517 return Context.getConstantArrayType(VLATy->getElementType(), 4518 Res, ArrayType::Normal, 0); 4519 } 4520 4521 static void 4522 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4523 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4524 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4525 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4526 DstPTL.getPointeeLoc()); 4527 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4528 return; 4529 } 4530 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4531 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4532 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4533 DstPTL.getInnerLoc()); 4534 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4535 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4536 return; 4537 } 4538 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4539 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4540 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4541 TypeLoc DstElemTL = DstATL.getElementLoc(); 4542 DstElemTL.initializeFullCopy(SrcElemTL); 4543 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4544 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4545 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4546 } 4547 4548 /// Helper method to turn variable array types into constant array 4549 /// types in certain situations which would otherwise be errors (for 4550 /// GCC compatibility). 4551 static TypeSourceInfo* 4552 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4553 ASTContext &Context, 4554 bool &SizeIsNegative, 4555 llvm::APSInt &Oversized) { 4556 QualType FixedTy 4557 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4558 SizeIsNegative, Oversized); 4559 if (FixedTy.isNull()) 4560 return 0; 4561 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4562 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4563 FixedTInfo->getTypeLoc()); 4564 return FixedTInfo; 4565 } 4566 4567 /// \brief Register the given locally-scoped extern "C" declaration so 4568 /// that it can be found later for redeclarations. We include any extern "C" 4569 /// declaration that is not visible in the translation unit here, not just 4570 /// function-scope declarations. 4571 void 4572 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4573 if (!getLangOpts().CPlusPlus && 4574 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4575 // Don't need to track declarations in the TU in C. 4576 return; 4577 4578 // Note that we have a locally-scoped external with this name. 4579 // FIXME: There can be multiple such declarations if they are functions marked 4580 // __attribute__((overloadable)) declared in function scope in C. 4581 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4582 } 4583 4584 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4585 if (ExternalSource) { 4586 // Load locally-scoped external decls from the external source. 4587 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4588 SmallVector<NamedDecl *, 4> Decls; 4589 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4590 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4591 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4592 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4593 if (Pos == LocallyScopedExternCDecls.end()) 4594 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4595 } 4596 } 4597 4598 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4599 return D ? D->getMostRecentDecl() : 0; 4600 } 4601 4602 /// \brief Diagnose function specifiers on a declaration of an identifier that 4603 /// does not identify a function. 4604 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4605 // FIXME: We should probably indicate the identifier in question to avoid 4606 // confusion for constructs like "inline int a(), b;" 4607 if (DS.isInlineSpecified()) 4608 Diag(DS.getInlineSpecLoc(), 4609 diag::err_inline_non_function); 4610 4611 if (DS.isVirtualSpecified()) 4612 Diag(DS.getVirtualSpecLoc(), 4613 diag::err_virtual_non_function); 4614 4615 if (DS.isExplicitSpecified()) 4616 Diag(DS.getExplicitSpecLoc(), 4617 diag::err_explicit_non_function); 4618 4619 if (DS.isNoreturnSpecified()) 4620 Diag(DS.getNoreturnSpecLoc(), 4621 diag::err_noreturn_non_function); 4622 } 4623 4624 NamedDecl* 4625 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4626 TypeSourceInfo *TInfo, LookupResult &Previous) { 4627 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4628 if (D.getCXXScopeSpec().isSet()) { 4629 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4630 << D.getCXXScopeSpec().getRange(); 4631 D.setInvalidType(); 4632 // Pretend we didn't see the scope specifier. 4633 DC = CurContext; 4634 Previous.clear(); 4635 } 4636 4637 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4638 4639 if (D.getDeclSpec().isConstexprSpecified()) 4640 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4641 << 1; 4642 4643 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4644 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4645 << D.getName().getSourceRange(); 4646 return 0; 4647 } 4648 4649 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4650 if (!NewTD) return 0; 4651 4652 // Handle attributes prior to checking for duplicates in MergeVarDecl 4653 ProcessDeclAttributes(S, NewTD, D); 4654 4655 CheckTypedefForVariablyModifiedType(S, NewTD); 4656 4657 bool Redeclaration = D.isRedeclaration(); 4658 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4659 D.setRedeclaration(Redeclaration); 4660 return ND; 4661 } 4662 4663 void 4664 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4665 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4666 // then it shall have block scope. 4667 // Note that variably modified types must be fixed before merging the decl so 4668 // that redeclarations will match. 4669 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4670 QualType T = TInfo->getType(); 4671 if (T->isVariablyModifiedType()) { 4672 getCurFunction()->setHasBranchProtectedScope(); 4673 4674 if (S->getFnParent() == 0) { 4675 bool SizeIsNegative; 4676 llvm::APSInt Oversized; 4677 TypeSourceInfo *FixedTInfo = 4678 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4679 SizeIsNegative, 4680 Oversized); 4681 if (FixedTInfo) { 4682 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4683 NewTD->setTypeSourceInfo(FixedTInfo); 4684 } else { 4685 if (SizeIsNegative) 4686 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4687 else if (T->isVariableArrayType()) 4688 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4689 else if (Oversized.getBoolValue()) 4690 Diag(NewTD->getLocation(), diag::err_array_too_large) 4691 << Oversized.toString(10); 4692 else 4693 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4694 NewTD->setInvalidDecl(); 4695 } 4696 } 4697 } 4698 } 4699 4700 4701 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4702 /// declares a typedef-name, either using the 'typedef' type specifier or via 4703 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4704 NamedDecl* 4705 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4706 LookupResult &Previous, bool &Redeclaration) { 4707 // Merge the decl with the existing one if appropriate. If the decl is 4708 // in an outer scope, it isn't the same thing. 4709 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4710 /*AllowInlineNamespace*/false); 4711 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4712 if (!Previous.empty()) { 4713 Redeclaration = true; 4714 MergeTypedefNameDecl(NewTD, Previous); 4715 } 4716 4717 // If this is the C FILE type, notify the AST context. 4718 if (IdentifierInfo *II = NewTD->getIdentifier()) 4719 if (!NewTD->isInvalidDecl() && 4720 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4721 if (II->isStr("FILE")) 4722 Context.setFILEDecl(NewTD); 4723 else if (II->isStr("jmp_buf")) 4724 Context.setjmp_bufDecl(NewTD); 4725 else if (II->isStr("sigjmp_buf")) 4726 Context.setsigjmp_bufDecl(NewTD); 4727 else if (II->isStr("ucontext_t")) 4728 Context.setucontext_tDecl(NewTD); 4729 } 4730 4731 return NewTD; 4732 } 4733 4734 /// \brief Determines whether the given declaration is an out-of-scope 4735 /// previous declaration. 4736 /// 4737 /// This routine should be invoked when name lookup has found a 4738 /// previous declaration (PrevDecl) that is not in the scope where a 4739 /// new declaration by the same name is being introduced. If the new 4740 /// declaration occurs in a local scope, previous declarations with 4741 /// linkage may still be considered previous declarations (C99 4742 /// 6.2.2p4-5, C++ [basic.link]p6). 4743 /// 4744 /// \param PrevDecl the previous declaration found by name 4745 /// lookup 4746 /// 4747 /// \param DC the context in which the new declaration is being 4748 /// declared. 4749 /// 4750 /// \returns true if PrevDecl is an out-of-scope previous declaration 4751 /// for a new delcaration with the same name. 4752 static bool 4753 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4754 ASTContext &Context) { 4755 if (!PrevDecl) 4756 return false; 4757 4758 if (!PrevDecl->hasLinkage()) 4759 return false; 4760 4761 if (Context.getLangOpts().CPlusPlus) { 4762 // C++ [basic.link]p6: 4763 // If there is a visible declaration of an entity with linkage 4764 // having the same name and type, ignoring entities declared 4765 // outside the innermost enclosing namespace scope, the block 4766 // scope declaration declares that same entity and receives the 4767 // linkage of the previous declaration. 4768 DeclContext *OuterContext = DC->getRedeclContext(); 4769 if (!OuterContext->isFunctionOrMethod()) 4770 // This rule only applies to block-scope declarations. 4771 return false; 4772 4773 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4774 if (PrevOuterContext->isRecord()) 4775 // We found a member function: ignore it. 4776 return false; 4777 4778 // Find the innermost enclosing namespace for the new and 4779 // previous declarations. 4780 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4781 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4782 4783 // The previous declaration is in a different namespace, so it 4784 // isn't the same function. 4785 if (!OuterContext->Equals(PrevOuterContext)) 4786 return false; 4787 } 4788 4789 return true; 4790 } 4791 4792 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4793 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4794 if (!SS.isSet()) return; 4795 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4796 } 4797 4798 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4799 QualType type = decl->getType(); 4800 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4801 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4802 // Various kinds of declaration aren't allowed to be __autoreleasing. 4803 unsigned kind = -1U; 4804 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4805 if (var->hasAttr<BlocksAttr>()) 4806 kind = 0; // __block 4807 else if (!var->hasLocalStorage()) 4808 kind = 1; // global 4809 } else if (isa<ObjCIvarDecl>(decl)) { 4810 kind = 3; // ivar 4811 } else if (isa<FieldDecl>(decl)) { 4812 kind = 2; // field 4813 } 4814 4815 if (kind != -1U) { 4816 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4817 << kind; 4818 } 4819 } else if (lifetime == Qualifiers::OCL_None) { 4820 // Try to infer lifetime. 4821 if (!type->isObjCLifetimeType()) 4822 return false; 4823 4824 lifetime = type->getObjCARCImplicitLifetime(); 4825 type = Context.getLifetimeQualifiedType(type, lifetime); 4826 decl->setType(type); 4827 } 4828 4829 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4830 // Thread-local variables cannot have lifetime. 4831 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4832 var->getTLSKind()) { 4833 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4834 << var->getType(); 4835 return true; 4836 } 4837 } 4838 4839 return false; 4840 } 4841 4842 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4843 // Ensure that an auto decl is deduced otherwise the checks below might cache 4844 // the wrong linkage. 4845 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4846 4847 // 'weak' only applies to declarations with external linkage. 4848 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4849 if (!ND.isExternallyVisible()) { 4850 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4851 ND.dropAttr<WeakAttr>(); 4852 } 4853 } 4854 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4855 if (ND.isExternallyVisible()) { 4856 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4857 ND.dropAttr<WeakRefAttr>(); 4858 } 4859 } 4860 4861 // 'selectany' only applies to externally visible varable declarations. 4862 // It does not apply to functions. 4863 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4864 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4865 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4866 ND.dropAttr<SelectAnyAttr>(); 4867 } 4868 } 4869 } 4870 4871 /// Given that we are within the definition of the given function, 4872 /// will that definition behave like C99's 'inline', where the 4873 /// definition is discarded except for optimization purposes? 4874 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4875 // Try to avoid calling GetGVALinkageForFunction. 4876 4877 // All cases of this require the 'inline' keyword. 4878 if (!FD->isInlined()) return false; 4879 4880 // This is only possible in C++ with the gnu_inline attribute. 4881 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4882 return false; 4883 4884 // Okay, go ahead and call the relatively-more-expensive function. 4885 4886 #ifndef NDEBUG 4887 // AST quite reasonably asserts that it's working on a function 4888 // definition. We don't really have a way to tell it that we're 4889 // currently defining the function, so just lie to it in +Asserts 4890 // builds. This is an awful hack. 4891 FD->setLazyBody(1); 4892 #endif 4893 4894 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4895 4896 #ifndef NDEBUG 4897 FD->setLazyBody(0); 4898 #endif 4899 4900 return isC99Inline; 4901 } 4902 4903 /// Determine whether a variable is extern "C" prior to attaching 4904 /// an initializer. We can't just call isExternC() here, because that 4905 /// will also compute and cache whether the declaration is externally 4906 /// visible, which might change when we attach the initializer. 4907 /// 4908 /// This can only be used if the declaration is known to not be a 4909 /// redeclaration of an internal linkage declaration. 4910 /// 4911 /// For instance: 4912 /// 4913 /// auto x = []{}; 4914 /// 4915 /// Attaching the initializer here makes this declaration not externally 4916 /// visible, because its type has internal linkage. 4917 /// 4918 /// FIXME: This is a hack. 4919 template<typename T> 4920 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4921 if (S.getLangOpts().CPlusPlus) { 4922 // In C++, the overloadable attribute negates the effects of extern "C". 4923 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4924 return false; 4925 } 4926 return D->isExternC(); 4927 } 4928 4929 static bool shouldConsiderLinkage(const VarDecl *VD) { 4930 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4931 if (DC->isFunctionOrMethod()) 4932 return VD->hasExternalStorage(); 4933 if (DC->isFileContext()) 4934 return true; 4935 if (DC->isRecord()) 4936 return false; 4937 llvm_unreachable("Unexpected context"); 4938 } 4939 4940 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4941 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4942 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4943 return true; 4944 if (DC->isRecord()) 4945 return false; 4946 llvm_unreachable("Unexpected context"); 4947 } 4948 4949 /// Adjust the \c DeclContext for a function or variable that might be a 4950 /// function-local external declaration. 4951 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 4952 if (!DC->isFunctionOrMethod()) 4953 return false; 4954 4955 // If this is a local extern function or variable declared within a function 4956 // template, don't add it into the enclosing namespace scope until it is 4957 // instantiated; it might have a dependent type right now. 4958 if (DC->isDependentContext()) 4959 return true; 4960 4961 // C++11 [basic.link]p7: 4962 // When a block scope declaration of an entity with linkage is not found to 4963 // refer to some other declaration, then that entity is a member of the 4964 // innermost enclosing namespace. 4965 // 4966 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 4967 // semantically-enclosing namespace, not a lexically-enclosing one. 4968 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 4969 DC = DC->getParent(); 4970 return true; 4971 } 4972 4973 NamedDecl * 4974 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4975 TypeSourceInfo *TInfo, LookupResult &Previous, 4976 MultiTemplateParamsArg TemplateParamLists, 4977 bool &AddToScope) { 4978 QualType R = TInfo->getType(); 4979 DeclarationName Name = GetNameForDeclarator(D).getName(); 4980 4981 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4982 VarDecl::StorageClass SC = 4983 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 4984 4985 DeclContext *OriginalDC = DC; 4986 bool IsLocalExternDecl = SC == SC_Extern && 4987 adjustContextForLocalExternDecl(DC); 4988 4989 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) { 4990 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4991 // half array type (unless the cl_khr_fp16 extension is enabled). 4992 if (Context.getBaseElementType(R)->isHalfType()) { 4993 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4994 D.setInvalidType(); 4995 } 4996 } 4997 4998 if (SCSpec == DeclSpec::SCS_mutable) { 4999 // mutable can only appear on non-static class members, so it's always 5000 // an error here 5001 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5002 D.setInvalidType(); 5003 SC = SC_None; 5004 } 5005 5006 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5007 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5008 D.getDeclSpec().getStorageClassSpecLoc())) { 5009 // In C++11, the 'register' storage class specifier is deprecated. 5010 // Suppress the warning in system macros, it's used in macros in some 5011 // popular C system headers, such as in glibc's htonl() macro. 5012 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5013 diag::warn_deprecated_register) 5014 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5015 } 5016 5017 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5018 if (!II) { 5019 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5020 << Name; 5021 return 0; 5022 } 5023 5024 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5025 5026 if (!DC->isRecord() && S->getFnParent() == 0) { 5027 // C99 6.9p2: The storage-class specifiers auto and register shall not 5028 // appear in the declaration specifiers in an external declaration. 5029 if (SC == SC_Auto || SC == SC_Register) { 5030 // If this is a register variable with an asm label specified, then this 5031 // is a GNU extension. 5032 if (SC == SC_Register && D.getAsmLabel()) 5033 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 5034 else 5035 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5036 D.setInvalidType(); 5037 } 5038 } 5039 5040 if (getLangOpts().OpenCL) { 5041 // Set up the special work-group-local storage class for variables in the 5042 // OpenCL __local address space. 5043 if (R.getAddressSpace() == LangAS::opencl_local) { 5044 SC = SC_OpenCLWorkGroupLocal; 5045 } 5046 5047 // OpenCL v1.2 s6.9.b p4: 5048 // The sampler type cannot be used with the __local and __global address 5049 // space qualifiers. 5050 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5051 R.getAddressSpace() == LangAS::opencl_global)) { 5052 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5053 } 5054 5055 // OpenCL 1.2 spec, p6.9 r: 5056 // The event type cannot be used to declare a program scope variable. 5057 // The event type cannot be used with the __local, __constant and __global 5058 // address space qualifiers. 5059 if (R->isEventT()) { 5060 if (S->getParent() == 0) { 5061 Diag(D.getLocStart(), diag::err_event_t_global_var); 5062 D.setInvalidType(); 5063 } 5064 5065 if (R.getAddressSpace()) { 5066 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5067 D.setInvalidType(); 5068 } 5069 } 5070 } 5071 5072 bool IsExplicitSpecialization = false; 5073 bool IsVariableTemplateSpecialization = false; 5074 bool IsPartialSpecialization = false; 5075 bool IsVariableTemplate = false; 5076 VarDecl *NewVD = 0; 5077 VarTemplateDecl *NewTemplate = 0; 5078 TemplateParameterList *TemplateParams = 0; 5079 if (!getLangOpts().CPlusPlus) { 5080 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5081 D.getIdentifierLoc(), II, 5082 R, TInfo, SC); 5083 5084 if (D.isInvalidType()) 5085 NewVD->setInvalidDecl(); 5086 } else { 5087 bool Invalid = false; 5088 5089 if (DC->isRecord() && !CurContext->isRecord()) { 5090 // This is an out-of-line definition of a static data member. 5091 switch (SC) { 5092 case SC_None: 5093 break; 5094 case SC_Static: 5095 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5096 diag::err_static_out_of_line) 5097 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5098 break; 5099 case SC_Auto: 5100 case SC_Register: 5101 case SC_Extern: 5102 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5103 // to names of variables declared in a block or to function parameters. 5104 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5105 // of class members 5106 5107 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5108 diag::err_storage_class_for_static_member) 5109 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5110 break; 5111 case SC_PrivateExtern: 5112 llvm_unreachable("C storage class in c++!"); 5113 case SC_OpenCLWorkGroupLocal: 5114 llvm_unreachable("OpenCL storage class in c++!"); 5115 } 5116 } 5117 5118 if (SC == SC_Static && CurContext->isRecord()) { 5119 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5120 if (RD->isLocalClass()) 5121 Diag(D.getIdentifierLoc(), 5122 diag::err_static_data_member_not_allowed_in_local_class) 5123 << Name << RD->getDeclName(); 5124 5125 // C++98 [class.union]p1: If a union contains a static data member, 5126 // the program is ill-formed. C++11 drops this restriction. 5127 if (RD->isUnion()) 5128 Diag(D.getIdentifierLoc(), 5129 getLangOpts().CPlusPlus11 5130 ? diag::warn_cxx98_compat_static_data_member_in_union 5131 : diag::ext_static_data_member_in_union) << Name; 5132 // We conservatively disallow static data members in anonymous structs. 5133 else if (!RD->getDeclName()) 5134 Diag(D.getIdentifierLoc(), 5135 diag::err_static_data_member_not_allowed_in_anon_struct) 5136 << Name << RD->isUnion(); 5137 } 5138 } 5139 5140 // Match up the template parameter lists with the scope specifier, then 5141 // determine whether we have a template or a template specialization. 5142 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5143 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5144 D.getCXXScopeSpec(), TemplateParamLists, 5145 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5146 5147 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId && 5148 !TemplateParams) { 5149 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5150 5151 // We have encountered something that the user meant to be a 5152 // specialization (because it has explicitly-specified template 5153 // arguments) but that was not introduced with a "template<>" (or had 5154 // too few of them). 5155 // FIXME: Differentiate between attempts for explicit instantiations 5156 // (starting with "template") and the rest. 5157 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5158 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5159 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5160 "template<> "); 5161 IsExplicitSpecialization = true; 5162 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(), 5163 SourceLocation(), 0, 0, 5164 SourceLocation()); 5165 } 5166 5167 if (TemplateParams) { 5168 if (!TemplateParams->size() && 5169 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5170 // There is an extraneous 'template<>' for this variable. Complain 5171 // about it, but allow the declaration of the variable. 5172 Diag(TemplateParams->getTemplateLoc(), 5173 diag::err_template_variable_noparams) 5174 << II 5175 << SourceRange(TemplateParams->getTemplateLoc(), 5176 TemplateParams->getRAngleLoc()); 5177 TemplateParams = 0; 5178 } else { 5179 // Only C++1y supports variable templates (N3651). 5180 Diag(D.getIdentifierLoc(), 5181 getLangOpts().CPlusPlus1y 5182 ? diag::warn_cxx11_compat_variable_template 5183 : diag::ext_variable_template); 5184 5185 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5186 // This is an explicit specialization or a partial specialization. 5187 // FIXME: Check that we can declare a specialization here. 5188 IsVariableTemplateSpecialization = true; 5189 IsPartialSpecialization = TemplateParams->size() > 0; 5190 } else { // if (TemplateParams->size() > 0) 5191 // This is a template declaration. 5192 IsVariableTemplate = true; 5193 5194 // Check that we can declare a template here. 5195 if (CheckTemplateDeclScope(S, TemplateParams)) 5196 return 0; 5197 } 5198 } 5199 } 5200 5201 if (IsVariableTemplateSpecialization) { 5202 SourceLocation TemplateKWLoc = 5203 TemplateParamLists.size() > 0 5204 ? TemplateParamLists[0]->getTemplateLoc() 5205 : SourceLocation(); 5206 DeclResult Res = ActOnVarTemplateSpecialization( 5207 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5208 IsPartialSpecialization); 5209 if (Res.isInvalid()) 5210 return 0; 5211 NewVD = cast<VarDecl>(Res.get()); 5212 AddToScope = false; 5213 } else 5214 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5215 D.getIdentifierLoc(), II, R, TInfo, SC); 5216 5217 // If this is supposed to be a variable template, create it as such. 5218 if (IsVariableTemplate) { 5219 NewTemplate = 5220 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5221 TemplateParams, NewVD); 5222 NewVD->setDescribedVarTemplate(NewTemplate); 5223 } 5224 5225 // If this decl has an auto type in need of deduction, make a note of the 5226 // Decl so we can diagnose uses of it in its own initializer. 5227 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5228 ParsingInitForAutoVars.insert(NewVD); 5229 5230 if (D.isInvalidType() || Invalid) { 5231 NewVD->setInvalidDecl(); 5232 if (NewTemplate) 5233 NewTemplate->setInvalidDecl(); 5234 } 5235 5236 SetNestedNameSpecifier(NewVD, D); 5237 5238 // If we have any template parameter lists that don't directly belong to 5239 // the variable (matching the scope specifier), store them. 5240 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5241 if (TemplateParamLists.size() > VDTemplateParamLists) 5242 NewVD->setTemplateParameterListsInfo( 5243 Context, TemplateParamLists.size() - VDTemplateParamLists, 5244 TemplateParamLists.data()); 5245 5246 if (D.getDeclSpec().isConstexprSpecified()) 5247 NewVD->setConstexpr(true); 5248 } 5249 5250 // Set the lexical context. If the declarator has a C++ scope specifier, the 5251 // lexical context will be different from the semantic context. 5252 NewVD->setLexicalDeclContext(CurContext); 5253 if (NewTemplate) 5254 NewTemplate->setLexicalDeclContext(CurContext); 5255 5256 if (IsLocalExternDecl) 5257 NewVD->setLocalExternDecl(); 5258 5259 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5260 if (NewVD->hasLocalStorage()) { 5261 // C++11 [dcl.stc]p4: 5262 // When thread_local is applied to a variable of block scope the 5263 // storage-class-specifier static is implied if it does not appear 5264 // explicitly. 5265 // Core issue: 'static' is not implied if the variable is declared 5266 // 'extern'. 5267 if (SCSpec == DeclSpec::SCS_unspecified && 5268 TSCS == DeclSpec::TSCS_thread_local && 5269 DC->isFunctionOrMethod()) 5270 NewVD->setTSCSpec(TSCS); 5271 else 5272 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5273 diag::err_thread_non_global) 5274 << DeclSpec::getSpecifierName(TSCS); 5275 } else if (!Context.getTargetInfo().isTLSSupported()) 5276 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5277 diag::err_thread_unsupported); 5278 else 5279 NewVD->setTSCSpec(TSCS); 5280 } 5281 5282 // C99 6.7.4p3 5283 // An inline definition of a function with external linkage shall 5284 // not contain a definition of a modifiable object with static or 5285 // thread storage duration... 5286 // We only apply this when the function is required to be defined 5287 // elsewhere, i.e. when the function is not 'extern inline'. Note 5288 // that a local variable with thread storage duration still has to 5289 // be marked 'static'. Also note that it's possible to get these 5290 // semantics in C++ using __attribute__((gnu_inline)). 5291 if (SC == SC_Static && S->getFnParent() != 0 && 5292 !NewVD->getType().isConstQualified()) { 5293 FunctionDecl *CurFD = getCurFunctionDecl(); 5294 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5295 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5296 diag::warn_static_local_in_extern_inline); 5297 MaybeSuggestAddingStaticToDecl(CurFD); 5298 } 5299 } 5300 5301 if (D.getDeclSpec().isModulePrivateSpecified()) { 5302 if (IsVariableTemplateSpecialization) 5303 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5304 << (IsPartialSpecialization ? 1 : 0) 5305 << FixItHint::CreateRemoval( 5306 D.getDeclSpec().getModulePrivateSpecLoc()); 5307 else if (IsExplicitSpecialization) 5308 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5309 << 2 5310 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5311 else if (NewVD->hasLocalStorage()) 5312 Diag(NewVD->getLocation(), diag::err_module_private_local) 5313 << 0 << NewVD->getDeclName() 5314 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5315 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5316 else { 5317 NewVD->setModulePrivate(); 5318 if (NewTemplate) 5319 NewTemplate->setModulePrivate(); 5320 } 5321 } 5322 5323 // Handle attributes prior to checking for duplicates in MergeVarDecl 5324 ProcessDeclAttributes(S, NewVD, D); 5325 5326 if (NewVD->hasAttrs()) 5327 CheckAlignasUnderalignment(NewVD); 5328 5329 if (getLangOpts().CUDA) { 5330 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5331 // storage [duration]." 5332 if (SC == SC_None && S->getFnParent() != 0 && 5333 (NewVD->hasAttr<CUDASharedAttr>() || 5334 NewVD->hasAttr<CUDAConstantAttr>())) { 5335 NewVD->setStorageClass(SC_Static); 5336 } 5337 } 5338 5339 // In auto-retain/release, infer strong retension for variables of 5340 // retainable type. 5341 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5342 NewVD->setInvalidDecl(); 5343 5344 // Handle GNU asm-label extension (encoded as an attribute). 5345 if (Expr *E = (Expr*)D.getAsmLabel()) { 5346 // The parser guarantees this is a string. 5347 StringLiteral *SE = cast<StringLiteral>(E); 5348 StringRef Label = SE->getString(); 5349 if (S->getFnParent() != 0) { 5350 switch (SC) { 5351 case SC_None: 5352 case SC_Auto: 5353 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5354 break; 5355 case SC_Register: 5356 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5357 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5358 break; 5359 case SC_Static: 5360 case SC_Extern: 5361 case SC_PrivateExtern: 5362 case SC_OpenCLWorkGroupLocal: 5363 break; 5364 } 5365 } 5366 5367 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5368 Context, Label, 0)); 5369 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5370 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5371 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5372 if (I != ExtnameUndeclaredIdentifiers.end()) { 5373 NewVD->addAttr(I->second); 5374 ExtnameUndeclaredIdentifiers.erase(I); 5375 } 5376 } 5377 5378 // Diagnose shadowed variables before filtering for scope. 5379 if (D.getCXXScopeSpec().isEmpty()) 5380 CheckShadow(S, NewVD, Previous); 5381 5382 // Don't consider existing declarations that are in a different 5383 // scope and are out-of-semantic-context declarations (if the new 5384 // declaration has linkage). 5385 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5386 D.getCXXScopeSpec().isNotEmpty() || 5387 IsExplicitSpecialization || 5388 IsVariableTemplateSpecialization); 5389 5390 // Check whether the previous declaration is in the same block scope. This 5391 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5392 if (getLangOpts().CPlusPlus && 5393 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5394 NewVD->setPreviousDeclInSameBlockScope( 5395 Previous.isSingleResult() && !Previous.isShadowed() && 5396 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5397 5398 if (!getLangOpts().CPlusPlus) { 5399 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5400 } else { 5401 // If this is an explicit specialization of a static data member, check it. 5402 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5403 CheckMemberSpecialization(NewVD, Previous)) 5404 NewVD->setInvalidDecl(); 5405 5406 // Merge the decl with the existing one if appropriate. 5407 if (!Previous.empty()) { 5408 if (Previous.isSingleResult() && 5409 isa<FieldDecl>(Previous.getFoundDecl()) && 5410 D.getCXXScopeSpec().isSet()) { 5411 // The user tried to define a non-static data member 5412 // out-of-line (C++ [dcl.meaning]p1). 5413 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5414 << D.getCXXScopeSpec().getRange(); 5415 Previous.clear(); 5416 NewVD->setInvalidDecl(); 5417 } 5418 } else if (D.getCXXScopeSpec().isSet()) { 5419 // No previous declaration in the qualifying scope. 5420 Diag(D.getIdentifierLoc(), diag::err_no_member) 5421 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5422 << D.getCXXScopeSpec().getRange(); 5423 NewVD->setInvalidDecl(); 5424 } 5425 5426 if (!IsVariableTemplateSpecialization) 5427 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5428 5429 if (NewTemplate) { 5430 VarTemplateDecl *PrevVarTemplate = 5431 NewVD->getPreviousDecl() 5432 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5433 : 0; 5434 5435 // Check the template parameter list of this declaration, possibly 5436 // merging in the template parameter list from the previous variable 5437 // template declaration. 5438 if (CheckTemplateParameterList( 5439 TemplateParams, 5440 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5441 : 0, 5442 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5443 DC->isDependentContext()) 5444 ? TPC_ClassTemplateMember 5445 : TPC_VarTemplate)) 5446 NewVD->setInvalidDecl(); 5447 5448 // If we are providing an explicit specialization of a static variable 5449 // template, make a note of that. 5450 if (PrevVarTemplate && 5451 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5452 PrevVarTemplate->setMemberSpecialization(); 5453 } 5454 } 5455 5456 ProcessPragmaWeak(S, NewVD); 5457 5458 // If this is the first declaration of an extern C variable, update 5459 // the map of such variables. 5460 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5461 isIncompleteDeclExternC(*this, NewVD)) 5462 RegisterLocallyScopedExternCDecl(NewVD, S); 5463 5464 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5465 Decl *ManglingContextDecl; 5466 if (MangleNumberingContext *MCtx = 5467 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5468 ManglingContextDecl)) { 5469 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD)); 5470 } 5471 } 5472 5473 if (NewTemplate) { 5474 if (NewVD->isInvalidDecl()) 5475 NewTemplate->setInvalidDecl(); 5476 ActOnDocumentableDecl(NewTemplate); 5477 return NewTemplate; 5478 } 5479 5480 return NewVD; 5481 } 5482 5483 /// \brief Diagnose variable or built-in function shadowing. Implements 5484 /// -Wshadow. 5485 /// 5486 /// This method is called whenever a VarDecl is added to a "useful" 5487 /// scope. 5488 /// 5489 /// \param S the scope in which the shadowing name is being declared 5490 /// \param R the lookup of the name 5491 /// 5492 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5493 // Return if warning is ignored. 5494 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5495 DiagnosticsEngine::Ignored) 5496 return; 5497 5498 // Don't diagnose declarations at file scope. 5499 if (D->hasGlobalStorage()) 5500 return; 5501 5502 DeclContext *NewDC = D->getDeclContext(); 5503 5504 // Only diagnose if we're shadowing an unambiguous field or variable. 5505 if (R.getResultKind() != LookupResult::Found) 5506 return; 5507 5508 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5509 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5510 return; 5511 5512 // Fields are not shadowed by variables in C++ static methods. 5513 if (isa<FieldDecl>(ShadowedDecl)) 5514 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5515 if (MD->isStatic()) 5516 return; 5517 5518 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5519 if (shadowedVar->isExternC()) { 5520 // For shadowing external vars, make sure that we point to the global 5521 // declaration, not a locally scoped extern declaration. 5522 for (VarDecl::redecl_iterator 5523 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 5524 I != E; ++I) 5525 if (I->isFileVarDecl()) { 5526 ShadowedDecl = *I; 5527 break; 5528 } 5529 } 5530 5531 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5532 5533 // Only warn about certain kinds of shadowing for class members. 5534 if (NewDC && NewDC->isRecord()) { 5535 // In particular, don't warn about shadowing non-class members. 5536 if (!OldDC->isRecord()) 5537 return; 5538 5539 // TODO: should we warn about static data members shadowing 5540 // static data members from base classes? 5541 5542 // TODO: don't diagnose for inaccessible shadowed members. 5543 // This is hard to do perfectly because we might friend the 5544 // shadowing context, but that's just a false negative. 5545 } 5546 5547 // Determine what kind of declaration we're shadowing. 5548 unsigned Kind; 5549 if (isa<RecordDecl>(OldDC)) { 5550 if (isa<FieldDecl>(ShadowedDecl)) 5551 Kind = 3; // field 5552 else 5553 Kind = 2; // static data member 5554 } else if (OldDC->isFileContext()) 5555 Kind = 1; // global 5556 else 5557 Kind = 0; // local 5558 5559 DeclarationName Name = R.getLookupName(); 5560 5561 // Emit warning and note. 5562 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5563 return; 5564 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5565 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5566 } 5567 5568 /// \brief Check -Wshadow without the advantage of a previous lookup. 5569 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5570 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5571 DiagnosticsEngine::Ignored) 5572 return; 5573 5574 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5575 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5576 LookupName(R, S); 5577 CheckShadow(S, D, R); 5578 } 5579 5580 /// Check for conflict between this global or extern "C" declaration and 5581 /// previous global or extern "C" declarations. This is only used in C++. 5582 template<typename T> 5583 static bool checkGlobalOrExternCConflict( 5584 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5585 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5586 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5587 5588 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5589 // The common case: this global doesn't conflict with any extern "C" 5590 // declaration. 5591 return false; 5592 } 5593 5594 if (Prev) { 5595 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5596 // Both the old and new declarations have C language linkage. This is a 5597 // redeclaration. 5598 Previous.clear(); 5599 Previous.addDecl(Prev); 5600 return true; 5601 } 5602 5603 // This is a global, non-extern "C" declaration, and there is a previous 5604 // non-global extern "C" declaration. Diagnose if this is a variable 5605 // declaration. 5606 if (!isa<VarDecl>(ND)) 5607 return false; 5608 } else { 5609 // The declaration is extern "C". Check for any declaration in the 5610 // translation unit which might conflict. 5611 if (IsGlobal) { 5612 // We have already performed the lookup into the translation unit. 5613 IsGlobal = false; 5614 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5615 I != E; ++I) { 5616 if (isa<VarDecl>(*I)) { 5617 Prev = *I; 5618 break; 5619 } 5620 } 5621 } else { 5622 DeclContext::lookup_result R = 5623 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5624 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5625 I != E; ++I) { 5626 if (isa<VarDecl>(*I)) { 5627 Prev = *I; 5628 break; 5629 } 5630 // FIXME: If we have any other entity with this name in global scope, 5631 // the declaration is ill-formed, but that is a defect: it breaks the 5632 // 'stat' hack, for instance. Only variables can have mangled name 5633 // clashes with extern "C" declarations, so only they deserve a 5634 // diagnostic. 5635 } 5636 } 5637 5638 if (!Prev) 5639 return false; 5640 } 5641 5642 // Use the first declaration's location to ensure we point at something which 5643 // is lexically inside an extern "C" linkage-spec. 5644 assert(Prev && "should have found a previous declaration to diagnose"); 5645 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5646 Prev = FD->getFirstDecl(); 5647 else 5648 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5649 5650 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5651 << IsGlobal << ND; 5652 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5653 << IsGlobal; 5654 return false; 5655 } 5656 5657 /// Apply special rules for handling extern "C" declarations. Returns \c true 5658 /// if we have found that this is a redeclaration of some prior entity. 5659 /// 5660 /// Per C++ [dcl.link]p6: 5661 /// Two declarations [for a function or variable] with C language linkage 5662 /// with the same name that appear in different scopes refer to the same 5663 /// [entity]. An entity with C language linkage shall not be declared with 5664 /// the same name as an entity in global scope. 5665 template<typename T> 5666 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5667 LookupResult &Previous) { 5668 if (!S.getLangOpts().CPlusPlus) { 5669 // In C, when declaring a global variable, look for a corresponding 'extern' 5670 // variable declared in function scope. We don't need this in C++, because 5671 // we find local extern decls in the surrounding file-scope DeclContext. 5672 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5673 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5674 Previous.clear(); 5675 Previous.addDecl(Prev); 5676 return true; 5677 } 5678 } 5679 return false; 5680 } 5681 5682 // A declaration in the translation unit can conflict with an extern "C" 5683 // declaration. 5684 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5685 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5686 5687 // An extern "C" declaration can conflict with a declaration in the 5688 // translation unit or can be a redeclaration of an extern "C" declaration 5689 // in another scope. 5690 if (isIncompleteDeclExternC(S,ND)) 5691 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5692 5693 // Neither global nor extern "C": nothing to do. 5694 return false; 5695 } 5696 5697 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5698 // If the decl is already known invalid, don't check it. 5699 if (NewVD->isInvalidDecl()) 5700 return; 5701 5702 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5703 QualType T = TInfo->getType(); 5704 5705 // Defer checking an 'auto' type until its initializer is attached. 5706 if (T->isUndeducedType()) 5707 return; 5708 5709 if (T->isObjCObjectType()) { 5710 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5711 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5712 T = Context.getObjCObjectPointerType(T); 5713 NewVD->setType(T); 5714 } 5715 5716 // Emit an error if an address space was applied to decl with local storage. 5717 // This includes arrays of objects with address space qualifiers, but not 5718 // automatic variables that point to other address spaces. 5719 // ISO/IEC TR 18037 S5.1.2 5720 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5721 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5722 NewVD->setInvalidDecl(); 5723 return; 5724 } 5725 5726 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5727 // __constant address space. 5728 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5729 && T.getAddressSpace() != LangAS::opencl_constant 5730 && !T->isSamplerT()){ 5731 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5732 NewVD->setInvalidDecl(); 5733 return; 5734 } 5735 5736 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5737 // scope. 5738 if ((getLangOpts().OpenCLVersion >= 120) 5739 && NewVD->isStaticLocal()) { 5740 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5741 NewVD->setInvalidDecl(); 5742 return; 5743 } 5744 5745 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5746 && !NewVD->hasAttr<BlocksAttr>()) { 5747 if (getLangOpts().getGC() != LangOptions::NonGC) 5748 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5749 else { 5750 assert(!getLangOpts().ObjCAutoRefCount); 5751 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5752 } 5753 } 5754 5755 bool isVM = T->isVariablyModifiedType(); 5756 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5757 NewVD->hasAttr<BlocksAttr>()) 5758 getCurFunction()->setHasBranchProtectedScope(); 5759 5760 if ((isVM && NewVD->hasLinkage()) || 5761 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5762 bool SizeIsNegative; 5763 llvm::APSInt Oversized; 5764 TypeSourceInfo *FixedTInfo = 5765 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5766 SizeIsNegative, Oversized); 5767 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5768 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5769 // FIXME: This won't give the correct result for 5770 // int a[10][n]; 5771 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5772 5773 if (NewVD->isFileVarDecl()) 5774 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5775 << SizeRange; 5776 else if (NewVD->isStaticLocal()) 5777 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5778 << SizeRange; 5779 else 5780 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5781 << SizeRange; 5782 NewVD->setInvalidDecl(); 5783 return; 5784 } 5785 5786 if (FixedTInfo == 0) { 5787 if (NewVD->isFileVarDecl()) 5788 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5789 else 5790 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5791 NewVD->setInvalidDecl(); 5792 return; 5793 } 5794 5795 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5796 NewVD->setType(FixedTInfo->getType()); 5797 NewVD->setTypeSourceInfo(FixedTInfo); 5798 } 5799 5800 if (T->isVoidType()) { 5801 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5802 // of objects and functions. 5803 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5804 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5805 << T; 5806 NewVD->setInvalidDecl(); 5807 return; 5808 } 5809 } 5810 5811 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5812 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5813 NewVD->setInvalidDecl(); 5814 return; 5815 } 5816 5817 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5818 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5819 NewVD->setInvalidDecl(); 5820 return; 5821 } 5822 5823 if (NewVD->isConstexpr() && !T->isDependentType() && 5824 RequireLiteralType(NewVD->getLocation(), T, 5825 diag::err_constexpr_var_non_literal)) { 5826 // Can't perform this check until the type is deduced. 5827 NewVD->setInvalidDecl(); 5828 return; 5829 } 5830 } 5831 5832 /// \brief Perform semantic checking on a newly-created variable 5833 /// declaration. 5834 /// 5835 /// This routine performs all of the type-checking required for a 5836 /// variable declaration once it has been built. It is used both to 5837 /// check variables after they have been parsed and their declarators 5838 /// have been translated into a declaration, and to check variables 5839 /// that have been instantiated from a template. 5840 /// 5841 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5842 /// 5843 /// Returns true if the variable declaration is a redeclaration. 5844 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5845 CheckVariableDeclarationType(NewVD); 5846 5847 // If the decl is already known invalid, don't check it. 5848 if (NewVD->isInvalidDecl()) 5849 return false; 5850 5851 // If we did not find anything by this name, look for a non-visible 5852 // extern "C" declaration with the same name. 5853 if (Previous.empty() && 5854 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5855 Previous.setShadowed(); 5856 5857 // Filter out any non-conflicting previous declarations. 5858 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5859 5860 if (!Previous.empty()) { 5861 MergeVarDecl(NewVD, Previous); 5862 return true; 5863 } 5864 return false; 5865 } 5866 5867 /// \brief Data used with FindOverriddenMethod 5868 struct FindOverriddenMethodData { 5869 Sema *S; 5870 CXXMethodDecl *Method; 5871 }; 5872 5873 /// \brief Member lookup function that determines whether a given C++ 5874 /// method overrides a method in a base class, to be used with 5875 /// CXXRecordDecl::lookupInBases(). 5876 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5877 CXXBasePath &Path, 5878 void *UserData) { 5879 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5880 5881 FindOverriddenMethodData *Data 5882 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5883 5884 DeclarationName Name = Data->Method->getDeclName(); 5885 5886 // FIXME: Do we care about other names here too? 5887 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5888 // We really want to find the base class destructor here. 5889 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5890 CanQualType CT = Data->S->Context.getCanonicalType(T); 5891 5892 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5893 } 5894 5895 for (Path.Decls = BaseRecord->lookup(Name); 5896 !Path.Decls.empty(); 5897 Path.Decls = Path.Decls.slice(1)) { 5898 NamedDecl *D = Path.Decls.front(); 5899 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5900 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5901 return true; 5902 } 5903 } 5904 5905 return false; 5906 } 5907 5908 namespace { 5909 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5910 } 5911 /// \brief Report an error regarding overriding, along with any relevant 5912 /// overriden methods. 5913 /// 5914 /// \param DiagID the primary error to report. 5915 /// \param MD the overriding method. 5916 /// \param OEK which overrides to include as notes. 5917 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5918 OverrideErrorKind OEK = OEK_All) { 5919 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5920 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5921 E = MD->end_overridden_methods(); 5922 I != E; ++I) { 5923 // This check (& the OEK parameter) could be replaced by a predicate, but 5924 // without lambdas that would be overkill. This is still nicer than writing 5925 // out the diag loop 3 times. 5926 if ((OEK == OEK_All) || 5927 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5928 (OEK == OEK_Deleted && (*I)->isDeleted())) 5929 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5930 } 5931 } 5932 5933 /// AddOverriddenMethods - See if a method overrides any in the base classes, 5934 /// and if so, check that it's a valid override and remember it. 5935 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5936 // Look for virtual methods in base classes that this method might override. 5937 CXXBasePaths Paths; 5938 FindOverriddenMethodData Data; 5939 Data.Method = MD; 5940 Data.S = this; 5941 bool hasDeletedOverridenMethods = false; 5942 bool hasNonDeletedOverridenMethods = false; 5943 bool AddedAny = false; 5944 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5945 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5946 E = Paths.found_decls_end(); I != E; ++I) { 5947 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5948 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5949 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5950 !CheckOverridingFunctionAttributes(MD, OldMD) && 5951 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5952 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5953 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5954 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5955 AddedAny = true; 5956 } 5957 } 5958 } 5959 } 5960 5961 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5962 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5963 } 5964 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5965 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5966 } 5967 5968 return AddedAny; 5969 } 5970 5971 namespace { 5972 // Struct for holding all of the extra arguments needed by 5973 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5974 struct ActOnFDArgs { 5975 Scope *S; 5976 Declarator &D; 5977 MultiTemplateParamsArg TemplateParamLists; 5978 bool AddToScope; 5979 }; 5980 } 5981 5982 namespace { 5983 5984 // Callback to only accept typo corrections that have a non-zero edit distance. 5985 // Also only accept corrections that have the same parent decl. 5986 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5987 public: 5988 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5989 CXXRecordDecl *Parent) 5990 : Context(Context), OriginalFD(TypoFD), 5991 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5992 5993 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5994 if (candidate.getEditDistance() == 0) 5995 return false; 5996 5997 SmallVector<unsigned, 1> MismatchedParams; 5998 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5999 CDeclEnd = candidate.end(); 6000 CDecl != CDeclEnd; ++CDecl) { 6001 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6002 6003 if (FD && !FD->hasBody() && 6004 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6005 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6006 CXXRecordDecl *Parent = MD->getParent(); 6007 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6008 return true; 6009 } else if (!ExpectedParent) { 6010 return true; 6011 } 6012 } 6013 } 6014 6015 return false; 6016 } 6017 6018 private: 6019 ASTContext &Context; 6020 FunctionDecl *OriginalFD; 6021 CXXRecordDecl *ExpectedParent; 6022 }; 6023 6024 } 6025 6026 /// \brief Generate diagnostics for an invalid function redeclaration. 6027 /// 6028 /// This routine handles generating the diagnostic messages for an invalid 6029 /// function redeclaration, including finding possible similar declarations 6030 /// or performing typo correction if there are no previous declarations with 6031 /// the same name. 6032 /// 6033 /// Returns a NamedDecl iff typo correction was performed and substituting in 6034 /// the new declaration name does not cause new errors. 6035 static NamedDecl *DiagnoseInvalidRedeclaration( 6036 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6037 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6038 DeclarationName Name = NewFD->getDeclName(); 6039 DeclContext *NewDC = NewFD->getDeclContext(); 6040 SmallVector<unsigned, 1> MismatchedParams; 6041 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6042 TypoCorrection Correction; 6043 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6044 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6045 : diag::err_member_decl_does_not_match; 6046 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6047 IsLocalFriend ? Sema::LookupLocalFriendName 6048 : Sema::LookupOrdinaryName, 6049 Sema::ForRedeclaration); 6050 6051 NewFD->setInvalidDecl(); 6052 if (IsLocalFriend) 6053 SemaRef.LookupName(Prev, S); 6054 else 6055 SemaRef.LookupQualifiedName(Prev, NewDC); 6056 assert(!Prev.isAmbiguous() && 6057 "Cannot have an ambiguity in previous-declaration lookup"); 6058 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6059 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6060 MD ? MD->getParent() : 0); 6061 if (!Prev.empty()) { 6062 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6063 Func != FuncEnd; ++Func) { 6064 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6065 if (FD && 6066 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6067 // Add 1 to the index so that 0 can mean the mismatch didn't 6068 // involve a parameter 6069 unsigned ParamNum = 6070 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6071 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6072 } 6073 } 6074 // If the qualified name lookup yielded nothing, try typo correction 6075 } else if ((Correction = SemaRef.CorrectTypo( 6076 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6077 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6078 IsLocalFriend ? 0 : NewDC))) { 6079 // Set up everything for the call to ActOnFunctionDeclarator 6080 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6081 ExtraArgs.D.getIdentifierLoc()); 6082 Previous.clear(); 6083 Previous.setLookupName(Correction.getCorrection()); 6084 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6085 CDeclEnd = Correction.end(); 6086 CDecl != CDeclEnd; ++CDecl) { 6087 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6088 if (FD && !FD->hasBody() && 6089 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6090 Previous.addDecl(FD); 6091 } 6092 } 6093 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6094 6095 NamedDecl *Result; 6096 // Retry building the function declaration with the new previous 6097 // declarations, and with errors suppressed. 6098 { 6099 // Trap errors. 6100 Sema::SFINAETrap Trap(SemaRef); 6101 6102 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6103 // pieces need to verify the typo-corrected C++ declaration and hopefully 6104 // eliminate the need for the parameter pack ExtraArgs. 6105 Result = SemaRef.ActOnFunctionDeclarator( 6106 ExtraArgs.S, ExtraArgs.D, 6107 Correction.getCorrectionDecl()->getDeclContext(), 6108 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6109 ExtraArgs.AddToScope); 6110 6111 if (Trap.hasErrorOccurred()) 6112 Result = 0; 6113 } 6114 6115 if (Result) { 6116 // Determine which correction we picked. 6117 Decl *Canonical = Result->getCanonicalDecl(); 6118 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6119 I != E; ++I) 6120 if ((*I)->getCanonicalDecl() == Canonical) 6121 Correction.setCorrectionDecl(*I); 6122 6123 SemaRef.diagnoseTypo( 6124 Correction, 6125 SemaRef.PDiag(IsLocalFriend 6126 ? diag::err_no_matching_local_friend_suggest 6127 : diag::err_member_decl_does_not_match_suggest) 6128 << Name << NewDC << IsDefinition); 6129 return Result; 6130 } 6131 6132 // Pretend the typo correction never occurred 6133 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6134 ExtraArgs.D.getIdentifierLoc()); 6135 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6136 Previous.clear(); 6137 Previous.setLookupName(Name); 6138 } 6139 6140 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6141 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6142 6143 bool NewFDisConst = false; 6144 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6145 NewFDisConst = NewMD->isConst(); 6146 6147 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6148 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6149 NearMatch != NearMatchEnd; ++NearMatch) { 6150 FunctionDecl *FD = NearMatch->first; 6151 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6152 bool FDisConst = MD && MD->isConst(); 6153 bool IsMember = MD || !IsLocalFriend; 6154 6155 // FIXME: These notes are poorly worded for the local friend case. 6156 if (unsigned Idx = NearMatch->second) { 6157 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6158 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6159 if (Loc.isInvalid()) Loc = FD->getLocation(); 6160 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6161 : diag::note_local_decl_close_param_match) 6162 << Idx << FDParam->getType() 6163 << NewFD->getParamDecl(Idx - 1)->getType(); 6164 } else if (FDisConst != NewFDisConst) { 6165 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6166 << NewFDisConst << FD->getSourceRange().getEnd(); 6167 } else 6168 SemaRef.Diag(FD->getLocation(), 6169 IsMember ? diag::note_member_def_close_match 6170 : diag::note_local_decl_close_match); 6171 } 6172 return 0; 6173 } 6174 6175 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6176 Declarator &D) { 6177 switch (D.getDeclSpec().getStorageClassSpec()) { 6178 default: llvm_unreachable("Unknown storage class!"); 6179 case DeclSpec::SCS_auto: 6180 case DeclSpec::SCS_register: 6181 case DeclSpec::SCS_mutable: 6182 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6183 diag::err_typecheck_sclass_func); 6184 D.setInvalidType(); 6185 break; 6186 case DeclSpec::SCS_unspecified: break; 6187 case DeclSpec::SCS_extern: 6188 if (D.getDeclSpec().isExternInLinkageSpec()) 6189 return SC_None; 6190 return SC_Extern; 6191 case DeclSpec::SCS_static: { 6192 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6193 // C99 6.7.1p5: 6194 // The declaration of an identifier for a function that has 6195 // block scope shall have no explicit storage-class specifier 6196 // other than extern 6197 // See also (C++ [dcl.stc]p4). 6198 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6199 diag::err_static_block_func); 6200 break; 6201 } else 6202 return SC_Static; 6203 } 6204 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6205 } 6206 6207 // No explicit storage class has already been returned 6208 return SC_None; 6209 } 6210 6211 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6212 DeclContext *DC, QualType &R, 6213 TypeSourceInfo *TInfo, 6214 FunctionDecl::StorageClass SC, 6215 bool &IsVirtualOkay) { 6216 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6217 DeclarationName Name = NameInfo.getName(); 6218 6219 FunctionDecl *NewFD = 0; 6220 bool isInline = D.getDeclSpec().isInlineSpecified(); 6221 6222 if (!SemaRef.getLangOpts().CPlusPlus) { 6223 // Determine whether the function was written with a 6224 // prototype. This true when: 6225 // - there is a prototype in the declarator, or 6226 // - the type R of the function is some kind of typedef or other reference 6227 // to a type name (which eventually refers to a function type). 6228 bool HasPrototype = 6229 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6230 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6231 6232 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6233 D.getLocStart(), NameInfo, R, 6234 TInfo, SC, isInline, 6235 HasPrototype, false); 6236 if (D.isInvalidType()) 6237 NewFD->setInvalidDecl(); 6238 6239 // Set the lexical context. 6240 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6241 6242 return NewFD; 6243 } 6244 6245 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6246 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6247 6248 // Check that the return type is not an abstract class type. 6249 // For record types, this is done by the AbstractClassUsageDiagnoser once 6250 // the class has been completely parsed. 6251 if (!DC->isRecord() && 6252 SemaRef.RequireNonAbstractType( 6253 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6254 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6255 D.setInvalidType(); 6256 6257 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6258 // This is a C++ constructor declaration. 6259 assert(DC->isRecord() && 6260 "Constructors can only be declared in a member context"); 6261 6262 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6263 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6264 D.getLocStart(), NameInfo, 6265 R, TInfo, isExplicit, isInline, 6266 /*isImplicitlyDeclared=*/false, 6267 isConstexpr); 6268 6269 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6270 // This is a C++ destructor declaration. 6271 if (DC->isRecord()) { 6272 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6273 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6274 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6275 SemaRef.Context, Record, 6276 D.getLocStart(), 6277 NameInfo, R, TInfo, isInline, 6278 /*isImplicitlyDeclared=*/false); 6279 6280 // If the class is complete, then we now create the implicit exception 6281 // specification. If the class is incomplete or dependent, we can't do 6282 // it yet. 6283 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6284 Record->getDefinition() && !Record->isBeingDefined() && 6285 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6286 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6287 } 6288 6289 // The Microsoft ABI requires that we perform the destructor body 6290 // checks (i.e. operator delete() lookup) at every declaration, as 6291 // any translation unit may need to emit a deleting destructor. 6292 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() && 6293 !Record->isDependentType() && Record->getDefinition() && 6294 !Record->isBeingDefined() && !NewDD->isDeleted()) { 6295 SemaRef.CheckDestructor(NewDD); 6296 } 6297 6298 IsVirtualOkay = true; 6299 return NewDD; 6300 6301 } else { 6302 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6303 D.setInvalidType(); 6304 6305 // Create a FunctionDecl to satisfy the function definition parsing 6306 // code path. 6307 return FunctionDecl::Create(SemaRef.Context, DC, 6308 D.getLocStart(), 6309 D.getIdentifierLoc(), Name, R, TInfo, 6310 SC, isInline, 6311 /*hasPrototype=*/true, isConstexpr); 6312 } 6313 6314 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6315 if (!DC->isRecord()) { 6316 SemaRef.Diag(D.getIdentifierLoc(), 6317 diag::err_conv_function_not_member); 6318 return 0; 6319 } 6320 6321 SemaRef.CheckConversionDeclarator(D, R, SC); 6322 IsVirtualOkay = true; 6323 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6324 D.getLocStart(), NameInfo, 6325 R, TInfo, isInline, isExplicit, 6326 isConstexpr, SourceLocation()); 6327 6328 } else if (DC->isRecord()) { 6329 // If the name of the function is the same as the name of the record, 6330 // then this must be an invalid constructor that has a return type. 6331 // (The parser checks for a return type and makes the declarator a 6332 // constructor if it has no return type). 6333 if (Name.getAsIdentifierInfo() && 6334 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6335 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6336 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6337 << SourceRange(D.getIdentifierLoc()); 6338 return 0; 6339 } 6340 6341 // This is a C++ method declaration. 6342 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6343 cast<CXXRecordDecl>(DC), 6344 D.getLocStart(), NameInfo, R, 6345 TInfo, SC, isInline, 6346 isConstexpr, SourceLocation()); 6347 IsVirtualOkay = !Ret->isStatic(); 6348 return Ret; 6349 } else { 6350 // Determine whether the function was written with a 6351 // prototype. This true when: 6352 // - we're in C++ (where every function has a prototype), 6353 return FunctionDecl::Create(SemaRef.Context, DC, 6354 D.getLocStart(), 6355 NameInfo, R, TInfo, SC, isInline, 6356 true/*HasPrototype*/, isConstexpr); 6357 } 6358 } 6359 6360 void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 6361 // In C++, the empty parameter-type-list must be spelled "void"; a 6362 // typedef of void is not permitted. 6363 if (getLangOpts().CPlusPlus && 6364 Param->getType().getUnqualifiedType() != Context.VoidTy) { 6365 bool IsTypeAlias = false; 6366 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 6367 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 6368 else if (const TemplateSpecializationType *TST = 6369 Param->getType()->getAs<TemplateSpecializationType>()) 6370 IsTypeAlias = TST->isTypeAlias(); 6371 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 6372 << IsTypeAlias; 6373 } 6374 } 6375 6376 enum OpenCLParamType { 6377 ValidKernelParam, 6378 PtrPtrKernelParam, 6379 PtrKernelParam, 6380 InvalidKernelParam, 6381 RecordKernelParam 6382 }; 6383 6384 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6385 if (PT->isPointerType()) { 6386 QualType PointeeType = PT->getPointeeType(); 6387 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam; 6388 } 6389 6390 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6391 // be used as builtin types. 6392 6393 if (PT->isImageType()) 6394 return PtrKernelParam; 6395 6396 if (PT->isBooleanType()) 6397 return InvalidKernelParam; 6398 6399 if (PT->isEventT()) 6400 return InvalidKernelParam; 6401 6402 if (PT->isHalfType()) 6403 return InvalidKernelParam; 6404 6405 if (PT->isRecordType()) 6406 return RecordKernelParam; 6407 6408 return ValidKernelParam; 6409 } 6410 6411 static void checkIsValidOpenCLKernelParameter( 6412 Sema &S, 6413 Declarator &D, 6414 ParmVarDecl *Param, 6415 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6416 QualType PT = Param->getType(); 6417 6418 // Cache the valid types we encounter to avoid rechecking structs that are 6419 // used again 6420 if (ValidTypes.count(PT.getTypePtr())) 6421 return; 6422 6423 switch (getOpenCLKernelParameterType(PT)) { 6424 case PtrPtrKernelParam: 6425 // OpenCL v1.2 s6.9.a: 6426 // A kernel function argument cannot be declared as a 6427 // pointer to a pointer type. 6428 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6429 D.setInvalidType(); 6430 return; 6431 6432 // OpenCL v1.2 s6.9.k: 6433 // Arguments to kernel functions in a program cannot be declared with the 6434 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6435 // uintptr_t or a struct and/or union that contain fields declared to be 6436 // one of these built-in scalar types. 6437 6438 case InvalidKernelParam: 6439 // OpenCL v1.2 s6.8 n: 6440 // A kernel function argument cannot be declared 6441 // of event_t type. 6442 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6443 D.setInvalidType(); 6444 return; 6445 6446 case PtrKernelParam: 6447 case ValidKernelParam: 6448 ValidTypes.insert(PT.getTypePtr()); 6449 return; 6450 6451 case RecordKernelParam: 6452 break; 6453 } 6454 6455 // Track nested structs we will inspect 6456 SmallVector<const Decl *, 4> VisitStack; 6457 6458 // Track where we are in the nested structs. Items will migrate from 6459 // VisitStack to HistoryStack as we do the DFS for bad field. 6460 SmallVector<const FieldDecl *, 4> HistoryStack; 6461 HistoryStack.push_back((const FieldDecl *) 0); 6462 6463 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6464 VisitStack.push_back(PD); 6465 6466 assert(VisitStack.back() && "First decl null?"); 6467 6468 do { 6469 const Decl *Next = VisitStack.pop_back_val(); 6470 if (!Next) { 6471 assert(!HistoryStack.empty()); 6472 // Found a marker, we have gone up a level 6473 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6474 ValidTypes.insert(Hist->getType().getTypePtr()); 6475 6476 continue; 6477 } 6478 6479 // Adds everything except the original parameter declaration (which is not a 6480 // field itself) to the history stack. 6481 const RecordDecl *RD; 6482 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6483 HistoryStack.push_back(Field); 6484 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6485 } else { 6486 RD = cast<RecordDecl>(Next); 6487 } 6488 6489 // Add a null marker so we know when we've gone back up a level 6490 VisitStack.push_back((const Decl *) 0); 6491 6492 for (RecordDecl::field_iterator I = RD->field_begin(), 6493 E = RD->field_end(); I != E; ++I) { 6494 const FieldDecl *FD = *I; 6495 QualType QT = FD->getType(); 6496 6497 if (ValidTypes.count(QT.getTypePtr())) 6498 continue; 6499 6500 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6501 if (ParamType == ValidKernelParam) 6502 continue; 6503 6504 if (ParamType == RecordKernelParam) { 6505 VisitStack.push_back(FD); 6506 continue; 6507 } 6508 6509 // OpenCL v1.2 s6.9.p: 6510 // Arguments to kernel functions that are declared to be a struct or union 6511 // do not allow OpenCL objects to be passed as elements of the struct or 6512 // union. 6513 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) { 6514 S.Diag(Param->getLocation(), 6515 diag::err_record_with_pointers_kernel_param) 6516 << PT->isUnionType() 6517 << PT; 6518 } else { 6519 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6520 } 6521 6522 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6523 << PD->getDeclName(); 6524 6525 // We have an error, now let's go back up through history and show where 6526 // the offending field came from 6527 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6528 E = HistoryStack.end(); I != E; ++I) { 6529 const FieldDecl *OuterField = *I; 6530 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6531 << OuterField->getType(); 6532 } 6533 6534 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6535 << QT->isPointerType() 6536 << QT; 6537 D.setInvalidType(); 6538 return; 6539 } 6540 } while (!VisitStack.empty()); 6541 } 6542 6543 NamedDecl* 6544 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6545 TypeSourceInfo *TInfo, LookupResult &Previous, 6546 MultiTemplateParamsArg TemplateParamLists, 6547 bool &AddToScope) { 6548 QualType R = TInfo->getType(); 6549 6550 assert(R.getTypePtr()->isFunctionType()); 6551 6552 // TODO: consider using NameInfo for diagnostic. 6553 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6554 DeclarationName Name = NameInfo.getName(); 6555 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6556 6557 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6558 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6559 diag::err_invalid_thread) 6560 << DeclSpec::getSpecifierName(TSCS); 6561 6562 if (D.isFirstDeclarationOfMember()) 6563 adjustMemberFunctionCC(R, D.isStaticMember()); 6564 6565 bool isFriend = false; 6566 FunctionTemplateDecl *FunctionTemplate = 0; 6567 bool isExplicitSpecialization = false; 6568 bool isFunctionTemplateSpecialization = false; 6569 6570 bool isDependentClassScopeExplicitSpecialization = false; 6571 bool HasExplicitTemplateArgs = false; 6572 TemplateArgumentListInfo TemplateArgs; 6573 6574 bool isVirtualOkay = false; 6575 6576 DeclContext *OriginalDC = DC; 6577 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6578 6579 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6580 isVirtualOkay); 6581 if (!NewFD) return 0; 6582 6583 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6584 NewFD->setTopLevelDeclInObjCContainer(); 6585 6586 // Set the lexical context. If this is a function-scope declaration, or has a 6587 // C++ scope specifier, or is the object of a friend declaration, the lexical 6588 // context will be different from the semantic context. 6589 NewFD->setLexicalDeclContext(CurContext); 6590 6591 if (IsLocalExternDecl) 6592 NewFD->setLocalExternDecl(); 6593 6594 if (getLangOpts().CPlusPlus) { 6595 bool isInline = D.getDeclSpec().isInlineSpecified(); 6596 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6597 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6598 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6599 isFriend = D.getDeclSpec().isFriendSpecified(); 6600 if (isFriend && !isInline && D.isFunctionDefinition()) { 6601 // C++ [class.friend]p5 6602 // A function can be defined in a friend declaration of a 6603 // class . . . . Such a function is implicitly inline. 6604 NewFD->setImplicitlyInline(); 6605 } 6606 6607 // If this is a method defined in an __interface, and is not a constructor 6608 // or an overloaded operator, then set the pure flag (isVirtual will already 6609 // return true). 6610 if (const CXXRecordDecl *Parent = 6611 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6612 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6613 NewFD->setPure(true); 6614 } 6615 6616 SetNestedNameSpecifier(NewFD, D); 6617 isExplicitSpecialization = false; 6618 isFunctionTemplateSpecialization = false; 6619 if (D.isInvalidType()) 6620 NewFD->setInvalidDecl(); 6621 6622 // Match up the template parameter lists with the scope specifier, then 6623 // determine whether we have a template or a template specialization. 6624 bool Invalid = false; 6625 if (TemplateParameterList *TemplateParams = 6626 MatchTemplateParametersToScopeSpecifier( 6627 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6628 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6629 isExplicitSpecialization, Invalid)) { 6630 if (TemplateParams->size() > 0) { 6631 // This is a function template 6632 6633 // Check that we can declare a template here. 6634 if (CheckTemplateDeclScope(S, TemplateParams)) 6635 return 0; 6636 6637 // A destructor cannot be a template. 6638 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6639 Diag(NewFD->getLocation(), diag::err_destructor_template); 6640 return 0; 6641 } 6642 6643 // If we're adding a template to a dependent context, we may need to 6644 // rebuilding some of the types used within the template parameter list, 6645 // now that we know what the current instantiation is. 6646 if (DC->isDependentContext()) { 6647 ContextRAII SavedContext(*this, DC); 6648 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6649 Invalid = true; 6650 } 6651 6652 6653 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6654 NewFD->getLocation(), 6655 Name, TemplateParams, 6656 NewFD); 6657 FunctionTemplate->setLexicalDeclContext(CurContext); 6658 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6659 6660 // For source fidelity, store the other template param lists. 6661 if (TemplateParamLists.size() > 1) { 6662 NewFD->setTemplateParameterListsInfo(Context, 6663 TemplateParamLists.size() - 1, 6664 TemplateParamLists.data()); 6665 } 6666 } else { 6667 // This is a function template specialization. 6668 isFunctionTemplateSpecialization = true; 6669 // For source fidelity, store all the template param lists. 6670 NewFD->setTemplateParameterListsInfo(Context, 6671 TemplateParamLists.size(), 6672 TemplateParamLists.data()); 6673 6674 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6675 if (isFriend) { 6676 // We want to remove the "template<>", found here. 6677 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6678 6679 // If we remove the template<> and the name is not a 6680 // template-id, we're actually silently creating a problem: 6681 // the friend declaration will refer to an untemplated decl, 6682 // and clearly the user wants a template specialization. So 6683 // we need to insert '<>' after the name. 6684 SourceLocation InsertLoc; 6685 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6686 InsertLoc = D.getName().getSourceRange().getEnd(); 6687 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6688 } 6689 6690 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6691 << Name << RemoveRange 6692 << FixItHint::CreateRemoval(RemoveRange) 6693 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6694 } 6695 } 6696 } 6697 else { 6698 // All template param lists were matched against the scope specifier: 6699 // this is NOT (an explicit specialization of) a template. 6700 if (TemplateParamLists.size() > 0) 6701 // For source fidelity, store all the template param lists. 6702 NewFD->setTemplateParameterListsInfo(Context, 6703 TemplateParamLists.size(), 6704 TemplateParamLists.data()); 6705 } 6706 6707 if (Invalid) { 6708 NewFD->setInvalidDecl(); 6709 if (FunctionTemplate) 6710 FunctionTemplate->setInvalidDecl(); 6711 } 6712 6713 // C++ [dcl.fct.spec]p5: 6714 // The virtual specifier shall only be used in declarations of 6715 // nonstatic class member functions that appear within a 6716 // member-specification of a class declaration; see 10.3. 6717 // 6718 if (isVirtual && !NewFD->isInvalidDecl()) { 6719 if (!isVirtualOkay) { 6720 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6721 diag::err_virtual_non_function); 6722 } else if (!CurContext->isRecord()) { 6723 // 'virtual' was specified outside of the class. 6724 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6725 diag::err_virtual_out_of_class) 6726 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6727 } else if (NewFD->getDescribedFunctionTemplate()) { 6728 // C++ [temp.mem]p3: 6729 // A member function template shall not be virtual. 6730 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6731 diag::err_virtual_member_function_template) 6732 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6733 } else { 6734 // Okay: Add virtual to the method. 6735 NewFD->setVirtualAsWritten(true); 6736 } 6737 6738 if (getLangOpts().CPlusPlus1y && 6739 NewFD->getReturnType()->isUndeducedType()) 6740 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6741 } 6742 6743 if (getLangOpts().CPlusPlus1y && 6744 (NewFD->isDependentContext() || 6745 (isFriend && CurContext->isDependentContext())) && 6746 NewFD->getReturnType()->isUndeducedType()) { 6747 // If the function template is referenced directly (for instance, as a 6748 // member of the current instantiation), pretend it has a dependent type. 6749 // This is not really justified by the standard, but is the only sane 6750 // thing to do. 6751 // FIXME: For a friend function, we have not marked the function as being 6752 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6753 const FunctionProtoType *FPT = 6754 NewFD->getType()->castAs<FunctionProtoType>(); 6755 QualType Result = 6756 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6757 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6758 FPT->getExtProtoInfo())); 6759 } 6760 6761 // C++ [dcl.fct.spec]p3: 6762 // The inline specifier shall not appear on a block scope function 6763 // declaration. 6764 if (isInline && !NewFD->isInvalidDecl()) { 6765 if (CurContext->isFunctionOrMethod()) { 6766 // 'inline' is not allowed on block scope function declaration. 6767 Diag(D.getDeclSpec().getInlineSpecLoc(), 6768 diag::err_inline_declaration_block_scope) << Name 6769 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6770 } 6771 } 6772 6773 // C++ [dcl.fct.spec]p6: 6774 // The explicit specifier shall be used only in the declaration of a 6775 // constructor or conversion function within its class definition; 6776 // see 12.3.1 and 12.3.2. 6777 if (isExplicit && !NewFD->isInvalidDecl()) { 6778 if (!CurContext->isRecord()) { 6779 // 'explicit' was specified outside of the class. 6780 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6781 diag::err_explicit_out_of_class) 6782 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6783 } else if (!isa<CXXConstructorDecl>(NewFD) && 6784 !isa<CXXConversionDecl>(NewFD)) { 6785 // 'explicit' was specified on a function that wasn't a constructor 6786 // or conversion function. 6787 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6788 diag::err_explicit_non_ctor_or_conv_function) 6789 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6790 } 6791 } 6792 6793 if (isConstexpr) { 6794 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6795 // are implicitly inline. 6796 NewFD->setImplicitlyInline(); 6797 6798 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6799 // be either constructors or to return a literal type. Therefore, 6800 // destructors cannot be declared constexpr. 6801 if (isa<CXXDestructorDecl>(NewFD)) 6802 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6803 } 6804 6805 // If __module_private__ was specified, mark the function accordingly. 6806 if (D.getDeclSpec().isModulePrivateSpecified()) { 6807 if (isFunctionTemplateSpecialization) { 6808 SourceLocation ModulePrivateLoc 6809 = D.getDeclSpec().getModulePrivateSpecLoc(); 6810 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6811 << 0 6812 << FixItHint::CreateRemoval(ModulePrivateLoc); 6813 } else { 6814 NewFD->setModulePrivate(); 6815 if (FunctionTemplate) 6816 FunctionTemplate->setModulePrivate(); 6817 } 6818 } 6819 6820 if (isFriend) { 6821 if (FunctionTemplate) { 6822 FunctionTemplate->setObjectOfFriendDecl(); 6823 FunctionTemplate->setAccess(AS_public); 6824 } 6825 NewFD->setObjectOfFriendDecl(); 6826 NewFD->setAccess(AS_public); 6827 } 6828 6829 // If a function is defined as defaulted or deleted, mark it as such now. 6830 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6831 // definition kind to FDK_Definition. 6832 switch (D.getFunctionDefinitionKind()) { 6833 case FDK_Declaration: 6834 case FDK_Definition: 6835 break; 6836 6837 case FDK_Defaulted: 6838 NewFD->setDefaulted(); 6839 break; 6840 6841 case FDK_Deleted: 6842 NewFD->setDeletedAsWritten(); 6843 break; 6844 } 6845 6846 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6847 D.isFunctionDefinition()) { 6848 // C++ [class.mfct]p2: 6849 // A member function may be defined (8.4) in its class definition, in 6850 // which case it is an inline member function (7.1.2) 6851 NewFD->setImplicitlyInline(); 6852 } 6853 6854 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6855 !CurContext->isRecord()) { 6856 // C++ [class.static]p1: 6857 // A data or function member of a class may be declared static 6858 // in a class definition, in which case it is a static member of 6859 // the class. 6860 6861 // Complain about the 'static' specifier if it's on an out-of-line 6862 // member function definition. 6863 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6864 diag::err_static_out_of_line) 6865 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6866 } 6867 6868 // C++11 [except.spec]p15: 6869 // A deallocation function with no exception-specification is treated 6870 // as if it were specified with noexcept(true). 6871 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6872 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6873 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6874 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6875 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6876 EPI.ExceptionSpecType = EST_BasicNoexcept; 6877 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 6878 FPT->getParamTypes(), EPI)); 6879 } 6880 } 6881 6882 // Filter out previous declarations that don't match the scope. 6883 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6884 D.getCXXScopeSpec().isNotEmpty() || 6885 isExplicitSpecialization || 6886 isFunctionTemplateSpecialization); 6887 6888 // Handle GNU asm-label extension (encoded as an attribute). 6889 if (Expr *E = (Expr*) D.getAsmLabel()) { 6890 // The parser guarantees this is a string. 6891 StringLiteral *SE = cast<StringLiteral>(E); 6892 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6893 SE->getString(), 0)); 6894 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6895 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6896 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6897 if (I != ExtnameUndeclaredIdentifiers.end()) { 6898 NewFD->addAttr(I->second); 6899 ExtnameUndeclaredIdentifiers.erase(I); 6900 } 6901 } 6902 6903 // Copy the parameter declarations from the declarator D to the function 6904 // declaration NewFD, if they are available. First scavenge them into Params. 6905 SmallVector<ParmVarDecl*, 16> Params; 6906 if (D.isFunctionDeclarator()) { 6907 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6908 6909 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6910 // function that takes no arguments, not a function that takes a 6911 // single void argument. 6912 // We let through "const void" here because Sema::GetTypeForDeclarator 6913 // already checks for that case. 6914 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6915 FTI.ArgInfo[0].Param && 6916 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6917 // Empty arg list, don't push any params. 6918 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6919 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6920 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6921 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6922 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6923 Param->setDeclContext(NewFD); 6924 Params.push_back(Param); 6925 6926 if (Param->isInvalidDecl()) 6927 NewFD->setInvalidDecl(); 6928 } 6929 } 6930 6931 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6932 // When we're declaring a function with a typedef, typeof, etc as in the 6933 // following example, we'll need to synthesize (unnamed) 6934 // parameters for use in the declaration. 6935 // 6936 // @code 6937 // typedef void fn(int); 6938 // fn f; 6939 // @endcode 6940 6941 // Synthesize a parameter for each argument type. 6942 for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(), 6943 AE = FT->param_type_end(); 6944 AI != AE; ++AI) { 6945 ParmVarDecl *Param = 6946 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6947 Param->setScopeInfo(0, Params.size()); 6948 Params.push_back(Param); 6949 } 6950 } else { 6951 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6952 "Should not need args for typedef of non-prototype fn"); 6953 } 6954 6955 // Finally, we know we have the right number of parameters, install them. 6956 NewFD->setParams(Params); 6957 6958 // Find all anonymous symbols defined during the declaration of this function 6959 // and add to NewFD. This lets us track decls such 'enum Y' in: 6960 // 6961 // void f(enum Y {AA} x) {} 6962 // 6963 // which would otherwise incorrectly end up in the translation unit scope. 6964 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6965 DeclsInPrototypeScope.clear(); 6966 6967 if (D.getDeclSpec().isNoreturnSpecified()) 6968 NewFD->addAttr( 6969 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6970 Context, 0)); 6971 6972 // Functions returning a variably modified type violate C99 6.7.5.2p2 6973 // because all functions have linkage. 6974 if (!NewFD->isInvalidDecl() && 6975 NewFD->getReturnType()->isVariablyModifiedType()) { 6976 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6977 NewFD->setInvalidDecl(); 6978 } 6979 6980 // Handle attributes. 6981 ProcessDeclAttributes(S, NewFD, D); 6982 6983 QualType RetType = NewFD->getReturnType(); 6984 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6985 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6986 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6987 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6988 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6989 // Attach WarnUnusedResult to functions returning types with that attribute. 6990 // Don't apply the attribute to that type's own non-static member functions 6991 // (to avoid warning on things like assignment operators) 6992 if (!MD || MD->getParent() != Ret) 6993 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 6994 } 6995 6996 if (getLangOpts().OpenCL) { 6997 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 6998 // type declaration will generate a compilation error. 6999 unsigned AddressSpace = RetType.getAddressSpace(); 7000 if (AddressSpace == LangAS::opencl_local || 7001 AddressSpace == LangAS::opencl_global || 7002 AddressSpace == LangAS::opencl_constant) { 7003 Diag(NewFD->getLocation(), 7004 diag::err_opencl_return_value_with_address_space); 7005 NewFD->setInvalidDecl(); 7006 } 7007 } 7008 7009 if (!getLangOpts().CPlusPlus) { 7010 // Perform semantic checking on the function declaration. 7011 bool isExplicitSpecialization=false; 7012 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7013 CheckMain(NewFD, D.getDeclSpec()); 7014 7015 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7016 CheckMSVCRTEntryPoint(NewFD); 7017 7018 if (!NewFD->isInvalidDecl()) 7019 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7020 isExplicitSpecialization)); 7021 else if (!Previous.empty()) 7022 // Make graceful recovery from an invalid redeclaration. 7023 D.setRedeclaration(true); 7024 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7025 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7026 "previous declaration set still overloaded"); 7027 } else { 7028 // C++11 [replacement.functions]p3: 7029 // The program's definitions shall not be specified as inline. 7030 // 7031 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7032 // 7033 // Suppress the diagnostic if the function is __attribute__((used)), since 7034 // that forces an external definition to be emitted. 7035 if (D.getDeclSpec().isInlineSpecified() && 7036 NewFD->isReplaceableGlobalAllocationFunction() && 7037 !NewFD->hasAttr<UsedAttr>()) 7038 Diag(D.getDeclSpec().getInlineSpecLoc(), 7039 diag::ext_operator_new_delete_declared_inline) 7040 << NewFD->getDeclName(); 7041 7042 // If the declarator is a template-id, translate the parser's template 7043 // argument list into our AST format. 7044 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7045 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7046 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7047 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7048 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7049 TemplateId->NumArgs); 7050 translateTemplateArguments(TemplateArgsPtr, 7051 TemplateArgs); 7052 7053 HasExplicitTemplateArgs = true; 7054 7055 if (NewFD->isInvalidDecl()) { 7056 HasExplicitTemplateArgs = false; 7057 } else if (FunctionTemplate) { 7058 // Function template with explicit template arguments. 7059 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7060 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7061 7062 HasExplicitTemplateArgs = false; 7063 } else if (!isFunctionTemplateSpecialization && 7064 !D.getDeclSpec().isFriendSpecified()) { 7065 // We have encountered something that the user meant to be a 7066 // specialization (because it has explicitly-specified template 7067 // arguments) but that was not introduced with a "template<>" (or had 7068 // too few of them). 7069 // FIXME: Differentiate between attempts for explicit instantiations 7070 // (starting with "template") and the rest. 7071 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7072 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7073 << FixItHint::CreateInsertion( 7074 D.getDeclSpec().getLocStart(), 7075 "template<> "); 7076 isFunctionTemplateSpecialization = true; 7077 } else { 7078 // "friend void foo<>(int);" is an implicit specialization decl. 7079 isFunctionTemplateSpecialization = true; 7080 } 7081 } else if (isFriend && isFunctionTemplateSpecialization) { 7082 // This combination is only possible in a recovery case; the user 7083 // wrote something like: 7084 // template <> friend void foo(int); 7085 // which we're recovering from as if the user had written: 7086 // friend void foo<>(int); 7087 // Go ahead and fake up a template id. 7088 HasExplicitTemplateArgs = true; 7089 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7090 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7091 } 7092 7093 // If it's a friend (and only if it's a friend), it's possible 7094 // that either the specialized function type or the specialized 7095 // template is dependent, and therefore matching will fail. In 7096 // this case, don't check the specialization yet. 7097 bool InstantiationDependent = false; 7098 if (isFunctionTemplateSpecialization && isFriend && 7099 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7100 TemplateSpecializationType::anyDependentTemplateArguments( 7101 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7102 InstantiationDependent))) { 7103 assert(HasExplicitTemplateArgs && 7104 "friend function specialization without template args"); 7105 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7106 Previous)) 7107 NewFD->setInvalidDecl(); 7108 } else if (isFunctionTemplateSpecialization) { 7109 if (CurContext->isDependentContext() && CurContext->isRecord() 7110 && !isFriend) { 7111 isDependentClassScopeExplicitSpecialization = true; 7112 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7113 diag::ext_function_specialization_in_class : 7114 diag::err_function_specialization_in_class) 7115 << NewFD->getDeclName(); 7116 } else if (CheckFunctionTemplateSpecialization(NewFD, 7117 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7118 Previous)) 7119 NewFD->setInvalidDecl(); 7120 7121 // C++ [dcl.stc]p1: 7122 // A storage-class-specifier shall not be specified in an explicit 7123 // specialization (14.7.3) 7124 FunctionTemplateSpecializationInfo *Info = 7125 NewFD->getTemplateSpecializationInfo(); 7126 if (Info && SC != SC_None) { 7127 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7128 Diag(NewFD->getLocation(), 7129 diag::err_explicit_specialization_inconsistent_storage_class) 7130 << SC 7131 << FixItHint::CreateRemoval( 7132 D.getDeclSpec().getStorageClassSpecLoc()); 7133 7134 else 7135 Diag(NewFD->getLocation(), 7136 diag::ext_explicit_specialization_storage_class) 7137 << FixItHint::CreateRemoval( 7138 D.getDeclSpec().getStorageClassSpecLoc()); 7139 } 7140 7141 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7142 if (CheckMemberSpecialization(NewFD, Previous)) 7143 NewFD->setInvalidDecl(); 7144 } 7145 7146 // Perform semantic checking on the function declaration. 7147 if (!isDependentClassScopeExplicitSpecialization) { 7148 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7149 CheckMain(NewFD, D.getDeclSpec()); 7150 7151 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7152 CheckMSVCRTEntryPoint(NewFD); 7153 7154 if (!NewFD->isInvalidDecl()) 7155 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7156 isExplicitSpecialization)); 7157 } 7158 7159 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7160 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7161 "previous declaration set still overloaded"); 7162 7163 NamedDecl *PrincipalDecl = (FunctionTemplate 7164 ? cast<NamedDecl>(FunctionTemplate) 7165 : NewFD); 7166 7167 if (isFriend && D.isRedeclaration()) { 7168 AccessSpecifier Access = AS_public; 7169 if (!NewFD->isInvalidDecl()) 7170 Access = NewFD->getPreviousDecl()->getAccess(); 7171 7172 NewFD->setAccess(Access); 7173 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7174 } 7175 7176 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7177 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7178 PrincipalDecl->setNonMemberOperator(); 7179 7180 // If we have a function template, check the template parameter 7181 // list. This will check and merge default template arguments. 7182 if (FunctionTemplate) { 7183 FunctionTemplateDecl *PrevTemplate = 7184 FunctionTemplate->getPreviousDecl(); 7185 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7186 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7187 D.getDeclSpec().isFriendSpecified() 7188 ? (D.isFunctionDefinition() 7189 ? TPC_FriendFunctionTemplateDefinition 7190 : TPC_FriendFunctionTemplate) 7191 : (D.getCXXScopeSpec().isSet() && 7192 DC && DC->isRecord() && 7193 DC->isDependentContext()) 7194 ? TPC_ClassTemplateMember 7195 : TPC_FunctionTemplate); 7196 } 7197 7198 if (NewFD->isInvalidDecl()) { 7199 // Ignore all the rest of this. 7200 } else if (!D.isRedeclaration()) { 7201 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7202 AddToScope }; 7203 // Fake up an access specifier if it's supposed to be a class member. 7204 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7205 NewFD->setAccess(AS_public); 7206 7207 // Qualified decls generally require a previous declaration. 7208 if (D.getCXXScopeSpec().isSet()) { 7209 // ...with the major exception of templated-scope or 7210 // dependent-scope friend declarations. 7211 7212 // TODO: we currently also suppress this check in dependent 7213 // contexts because (1) the parameter depth will be off when 7214 // matching friend templates and (2) we might actually be 7215 // selecting a friend based on a dependent factor. But there 7216 // are situations where these conditions don't apply and we 7217 // can actually do this check immediately. 7218 if (isFriend && 7219 (TemplateParamLists.size() || 7220 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7221 CurContext->isDependentContext())) { 7222 // ignore these 7223 } else { 7224 // The user tried to provide an out-of-line definition for a 7225 // function that is a member of a class or namespace, but there 7226 // was no such member function declared (C++ [class.mfct]p2, 7227 // C++ [namespace.memdef]p2). For example: 7228 // 7229 // class X { 7230 // void f() const; 7231 // }; 7232 // 7233 // void X::f() { } // ill-formed 7234 // 7235 // Complain about this problem, and attempt to suggest close 7236 // matches (e.g., those that differ only in cv-qualifiers and 7237 // whether the parameter types are references). 7238 7239 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7240 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7241 AddToScope = ExtraArgs.AddToScope; 7242 return Result; 7243 } 7244 } 7245 7246 // Unqualified local friend declarations are required to resolve 7247 // to something. 7248 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7249 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7250 *this, Previous, NewFD, ExtraArgs, true, S)) { 7251 AddToScope = ExtraArgs.AddToScope; 7252 return Result; 7253 } 7254 } 7255 7256 } else if (!D.isFunctionDefinition() && 7257 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7258 !isFriend && !isFunctionTemplateSpecialization && 7259 !isExplicitSpecialization) { 7260 // An out-of-line member function declaration must also be a 7261 // definition (C++ [class.mfct]p2). 7262 // Note that this is not the case for explicit specializations of 7263 // function templates or member functions of class templates, per 7264 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7265 // extension for compatibility with old SWIG code which likes to 7266 // generate them. 7267 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7268 << D.getCXXScopeSpec().getRange(); 7269 } 7270 } 7271 7272 ProcessPragmaWeak(S, NewFD); 7273 checkAttributesAfterMerging(*this, *NewFD); 7274 7275 AddKnownFunctionAttributes(NewFD); 7276 7277 if (NewFD->hasAttr<OverloadableAttr>() && 7278 !NewFD->getType()->getAs<FunctionProtoType>()) { 7279 Diag(NewFD->getLocation(), 7280 diag::err_attribute_overloadable_no_prototype) 7281 << NewFD; 7282 7283 // Turn this into a variadic function with no parameters. 7284 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7285 FunctionProtoType::ExtProtoInfo EPI( 7286 Context.getDefaultCallingConvention(true, false)); 7287 EPI.Variadic = true; 7288 EPI.ExtInfo = FT->getExtInfo(); 7289 7290 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7291 NewFD->setType(R); 7292 } 7293 7294 // If there's a #pragma GCC visibility in scope, and this isn't a class 7295 // member, set the visibility of this function. 7296 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7297 AddPushedVisibilityAttribute(NewFD); 7298 7299 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7300 // marking the function. 7301 AddCFAuditedAttribute(NewFD); 7302 7303 // If this is the first declaration of an extern C variable, update 7304 // the map of such variables. 7305 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7306 isIncompleteDeclExternC(*this, NewFD)) 7307 RegisterLocallyScopedExternCDecl(NewFD, S); 7308 7309 // Set this FunctionDecl's range up to the right paren. 7310 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7311 7312 if (getLangOpts().CPlusPlus) { 7313 if (FunctionTemplate) { 7314 if (NewFD->isInvalidDecl()) 7315 FunctionTemplate->setInvalidDecl(); 7316 return FunctionTemplate; 7317 } 7318 } 7319 7320 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7321 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7322 if ((getLangOpts().OpenCLVersion >= 120) 7323 && (SC == SC_Static)) { 7324 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7325 D.setInvalidType(); 7326 } 7327 7328 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7329 if (!NewFD->getReturnType()->isVoidType()) { 7330 Diag(D.getIdentifierLoc(), 7331 diag::err_expected_kernel_void_return_type); 7332 D.setInvalidType(); 7333 } 7334 7335 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7336 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 7337 PE = NewFD->param_end(); PI != PE; ++PI) { 7338 ParmVarDecl *Param = *PI; 7339 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7340 } 7341 } 7342 7343 MarkUnusedFileScopedDecl(NewFD); 7344 7345 if (getLangOpts().CUDA) 7346 if (IdentifierInfo *II = NewFD->getIdentifier()) 7347 if (!NewFD->isInvalidDecl() && 7348 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7349 if (II->isStr("cudaConfigureCall")) { 7350 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7351 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7352 7353 Context.setcudaConfigureCallDecl(NewFD); 7354 } 7355 } 7356 7357 // Here we have an function template explicit specialization at class scope. 7358 // The actually specialization will be postponed to template instatiation 7359 // time via the ClassScopeFunctionSpecializationDecl node. 7360 if (isDependentClassScopeExplicitSpecialization) { 7361 ClassScopeFunctionSpecializationDecl *NewSpec = 7362 ClassScopeFunctionSpecializationDecl::Create( 7363 Context, CurContext, SourceLocation(), 7364 cast<CXXMethodDecl>(NewFD), 7365 HasExplicitTemplateArgs, TemplateArgs); 7366 CurContext->addDecl(NewSpec); 7367 AddToScope = false; 7368 } 7369 7370 return NewFD; 7371 } 7372 7373 /// \brief Perform semantic checking of a new function declaration. 7374 /// 7375 /// Performs semantic analysis of the new function declaration 7376 /// NewFD. This routine performs all semantic checking that does not 7377 /// require the actual declarator involved in the declaration, and is 7378 /// used both for the declaration of functions as they are parsed 7379 /// (called via ActOnDeclarator) and for the declaration of functions 7380 /// that have been instantiated via C++ template instantiation (called 7381 /// via InstantiateDecl). 7382 /// 7383 /// \param IsExplicitSpecialization whether this new function declaration is 7384 /// an explicit specialization of the previous declaration. 7385 /// 7386 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7387 /// 7388 /// \returns true if the function declaration is a redeclaration. 7389 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7390 LookupResult &Previous, 7391 bool IsExplicitSpecialization) { 7392 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7393 "Variably modified return types are not handled here"); 7394 7395 // Determine whether the type of this function should be merged with 7396 // a previous visible declaration. This never happens for functions in C++, 7397 // and always happens in C if the previous declaration was visible. 7398 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7399 !Previous.isShadowed(); 7400 7401 // Filter out any non-conflicting previous declarations. 7402 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7403 7404 bool Redeclaration = false; 7405 NamedDecl *OldDecl = 0; 7406 7407 // Merge or overload the declaration with an existing declaration of 7408 // the same name, if appropriate. 7409 if (!Previous.empty()) { 7410 // Determine whether NewFD is an overload of PrevDecl or 7411 // a declaration that requires merging. If it's an overload, 7412 // there's no more work to do here; we'll just add the new 7413 // function to the scope. 7414 if (!AllowOverloadingOfFunction(Previous, Context)) { 7415 NamedDecl *Candidate = Previous.getFoundDecl(); 7416 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7417 Redeclaration = true; 7418 OldDecl = Candidate; 7419 } 7420 } else { 7421 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7422 /*NewIsUsingDecl*/ false)) { 7423 case Ovl_Match: 7424 Redeclaration = true; 7425 break; 7426 7427 case Ovl_NonFunction: 7428 Redeclaration = true; 7429 break; 7430 7431 case Ovl_Overload: 7432 Redeclaration = false; 7433 break; 7434 } 7435 7436 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7437 // If a function name is overloadable in C, then every function 7438 // with that name must be marked "overloadable". 7439 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7440 << Redeclaration << NewFD; 7441 NamedDecl *OverloadedDecl = 0; 7442 if (Redeclaration) 7443 OverloadedDecl = OldDecl; 7444 else if (!Previous.empty()) 7445 OverloadedDecl = Previous.getRepresentativeDecl(); 7446 if (OverloadedDecl) 7447 Diag(OverloadedDecl->getLocation(), 7448 diag::note_attribute_overloadable_prev_overload); 7449 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7450 } 7451 } 7452 } 7453 7454 // Check for a previous extern "C" declaration with this name. 7455 if (!Redeclaration && 7456 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7457 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7458 if (!Previous.empty()) { 7459 // This is an extern "C" declaration with the same name as a previous 7460 // declaration, and thus redeclares that entity... 7461 Redeclaration = true; 7462 OldDecl = Previous.getFoundDecl(); 7463 MergeTypeWithPrevious = false; 7464 7465 // ... except in the presence of __attribute__((overloadable)). 7466 if (OldDecl->hasAttr<OverloadableAttr>()) { 7467 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7468 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7469 << Redeclaration << NewFD; 7470 Diag(Previous.getFoundDecl()->getLocation(), 7471 diag::note_attribute_overloadable_prev_overload); 7472 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7473 } 7474 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7475 Redeclaration = false; 7476 OldDecl = 0; 7477 } 7478 } 7479 } 7480 } 7481 7482 // C++11 [dcl.constexpr]p8: 7483 // A constexpr specifier for a non-static member function that is not 7484 // a constructor declares that member function to be const. 7485 // 7486 // This needs to be delayed until we know whether this is an out-of-line 7487 // definition of a static member function. 7488 // 7489 // This rule is not present in C++1y, so we produce a backwards 7490 // compatibility warning whenever it happens in C++11. 7491 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7492 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7493 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7494 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7495 CXXMethodDecl *OldMD = 0; 7496 if (OldDecl) 7497 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7498 if (!OldMD || !OldMD->isStatic()) { 7499 const FunctionProtoType *FPT = 7500 MD->getType()->castAs<FunctionProtoType>(); 7501 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7502 EPI.TypeQuals |= Qualifiers::Const; 7503 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7504 FPT->getParamTypes(), EPI)); 7505 7506 // Warn that we did this, if we're not performing template instantiation. 7507 // In that case, we'll have warned already when the template was defined. 7508 if (ActiveTemplateInstantiations.empty()) { 7509 SourceLocation AddConstLoc; 7510 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7511 .IgnoreParens().getAs<FunctionTypeLoc>()) 7512 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7513 7514 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7515 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7516 } 7517 } 7518 } 7519 7520 if (Redeclaration) { 7521 // NewFD and OldDecl represent declarations that need to be 7522 // merged. 7523 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7524 NewFD->setInvalidDecl(); 7525 return Redeclaration; 7526 } 7527 7528 Previous.clear(); 7529 Previous.addDecl(OldDecl); 7530 7531 if (FunctionTemplateDecl *OldTemplateDecl 7532 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7533 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7534 FunctionTemplateDecl *NewTemplateDecl 7535 = NewFD->getDescribedFunctionTemplate(); 7536 assert(NewTemplateDecl && "Template/non-template mismatch"); 7537 if (CXXMethodDecl *Method 7538 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7539 Method->setAccess(OldTemplateDecl->getAccess()); 7540 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7541 } 7542 7543 // If this is an explicit specialization of a member that is a function 7544 // template, mark it as a member specialization. 7545 if (IsExplicitSpecialization && 7546 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7547 NewTemplateDecl->setMemberSpecialization(); 7548 assert(OldTemplateDecl->isMemberSpecialization()); 7549 } 7550 7551 } else { 7552 // This needs to happen first so that 'inline' propagates. 7553 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7554 7555 if (isa<CXXMethodDecl>(NewFD)) { 7556 // A valid redeclaration of a C++ method must be out-of-line, 7557 // but (unfortunately) it's not necessarily a definition 7558 // because of templates, which means that the previous 7559 // declaration is not necessarily from the class definition. 7560 7561 // For just setting the access, that doesn't matter. 7562 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7563 NewFD->setAccess(oldMethod->getAccess()); 7564 7565 // Update the key-function state if necessary for this ABI. 7566 if (NewFD->isInlined() && 7567 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7568 // setNonKeyFunction needs to work with the original 7569 // declaration from the class definition, and isVirtual() is 7570 // just faster in that case, so map back to that now. 7571 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7572 if (oldMethod->isVirtual()) { 7573 Context.setNonKeyFunction(oldMethod); 7574 } 7575 } 7576 } 7577 } 7578 } 7579 7580 // Semantic checking for this function declaration (in isolation). 7581 if (getLangOpts().CPlusPlus) { 7582 // C++-specific checks. 7583 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7584 CheckConstructor(Constructor); 7585 } else if (CXXDestructorDecl *Destructor = 7586 dyn_cast<CXXDestructorDecl>(NewFD)) { 7587 CXXRecordDecl *Record = Destructor->getParent(); 7588 QualType ClassType = Context.getTypeDeclType(Record); 7589 7590 // FIXME: Shouldn't we be able to perform this check even when the class 7591 // type is dependent? Both gcc and edg can handle that. 7592 if (!ClassType->isDependentType()) { 7593 DeclarationName Name 7594 = Context.DeclarationNames.getCXXDestructorName( 7595 Context.getCanonicalType(ClassType)); 7596 if (NewFD->getDeclName() != Name) { 7597 Diag(NewFD->getLocation(), diag::err_destructor_name); 7598 NewFD->setInvalidDecl(); 7599 return Redeclaration; 7600 } 7601 } 7602 } else if (CXXConversionDecl *Conversion 7603 = dyn_cast<CXXConversionDecl>(NewFD)) { 7604 ActOnConversionDeclarator(Conversion); 7605 } 7606 7607 // Find any virtual functions that this function overrides. 7608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7609 if (!Method->isFunctionTemplateSpecialization() && 7610 !Method->getDescribedFunctionTemplate() && 7611 Method->isCanonicalDecl()) { 7612 if (AddOverriddenMethods(Method->getParent(), Method)) { 7613 // If the function was marked as "static", we have a problem. 7614 if (NewFD->getStorageClass() == SC_Static) { 7615 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7616 } 7617 } 7618 } 7619 7620 if (Method->isStatic()) 7621 checkThisInStaticMemberFunctionType(Method); 7622 } 7623 7624 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7625 if (NewFD->isOverloadedOperator() && 7626 CheckOverloadedOperatorDeclaration(NewFD)) { 7627 NewFD->setInvalidDecl(); 7628 return Redeclaration; 7629 } 7630 7631 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7632 if (NewFD->getLiteralIdentifier() && 7633 CheckLiteralOperatorDeclaration(NewFD)) { 7634 NewFD->setInvalidDecl(); 7635 return Redeclaration; 7636 } 7637 7638 // In C++, check default arguments now that we have merged decls. Unless 7639 // the lexical context is the class, because in this case this is done 7640 // during delayed parsing anyway. 7641 if (!CurContext->isRecord()) 7642 CheckCXXDefaultArguments(NewFD); 7643 7644 // If this function declares a builtin function, check the type of this 7645 // declaration against the expected type for the builtin. 7646 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7647 ASTContext::GetBuiltinTypeError Error; 7648 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7649 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7650 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7651 // The type of this function differs from the type of the builtin, 7652 // so forget about the builtin entirely. 7653 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7654 } 7655 } 7656 7657 // If this function is declared as being extern "C", then check to see if 7658 // the function returns a UDT (class, struct, or union type) that is not C 7659 // compatible, and if it does, warn the user. 7660 // But, issue any diagnostic on the first declaration only. 7661 if (NewFD->isExternC() && Previous.empty()) { 7662 QualType R = NewFD->getReturnType(); 7663 if (R->isIncompleteType() && !R->isVoidType()) 7664 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7665 << NewFD << R; 7666 else if (!R.isPODType(Context) && !R->isVoidType() && 7667 !R->isObjCObjectPointerType()) 7668 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7669 } 7670 } 7671 return Redeclaration; 7672 } 7673 7674 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7675 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7676 if (!TSI) 7677 return SourceRange(); 7678 7679 TypeLoc TL = TSI->getTypeLoc(); 7680 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7681 if (!FunctionTL) 7682 return SourceRange(); 7683 7684 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7685 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7686 return ResultTL.getSourceRange(); 7687 7688 return SourceRange(); 7689 } 7690 7691 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7692 // C++11 [basic.start.main]p3: 7693 // A program that [...] declares main to be inline, static or 7694 // constexpr is ill-formed. 7695 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7696 // appear in a declaration of main. 7697 // static main is not an error under C99, but we should warn about it. 7698 // We accept _Noreturn main as an extension. 7699 if (FD->getStorageClass() == SC_Static) 7700 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7701 ? diag::err_static_main : diag::warn_static_main) 7702 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7703 if (FD->isInlineSpecified()) 7704 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7705 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7706 if (DS.isNoreturnSpecified()) { 7707 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7708 SourceRange NoreturnRange(NoreturnLoc, 7709 PP.getLocForEndOfToken(NoreturnLoc)); 7710 Diag(NoreturnLoc, diag::ext_noreturn_main); 7711 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7712 << FixItHint::CreateRemoval(NoreturnRange); 7713 } 7714 if (FD->isConstexpr()) { 7715 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7716 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7717 FD->setConstexpr(false); 7718 } 7719 7720 if (getLangOpts().OpenCL) { 7721 Diag(FD->getLocation(), diag::err_opencl_no_main) 7722 << FD->hasAttr<OpenCLKernelAttr>(); 7723 FD->setInvalidDecl(); 7724 return; 7725 } 7726 7727 QualType T = FD->getType(); 7728 assert(T->isFunctionType() && "function decl is not of function type"); 7729 const FunctionType* FT = T->castAs<FunctionType>(); 7730 7731 // All the standards say that main() should should return 'int'. 7732 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7733 // In C and C++, main magically returns 0 if you fall off the end; 7734 // set the flag which tells us that. 7735 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7736 FD->setHasImplicitReturnZero(true); 7737 7738 // In C with GNU extensions we allow main() to have non-integer return 7739 // type, but we should warn about the extension, and we disable the 7740 // implicit-return-zero rule. 7741 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7742 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7743 7744 SourceRange ResultRange = getResultSourceRange(FD); 7745 if (ResultRange.isValid()) 7746 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7747 << FixItHint::CreateReplacement(ResultRange, "int"); 7748 7749 // Otherwise, this is just a flat-out error. 7750 } else { 7751 SourceRange ResultRange = getResultSourceRange(FD); 7752 if (ResultRange.isValid()) 7753 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7754 << FixItHint::CreateReplacement(ResultRange, "int"); 7755 else 7756 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7757 7758 FD->setInvalidDecl(true); 7759 } 7760 7761 // Treat protoless main() as nullary. 7762 if (isa<FunctionNoProtoType>(FT)) return; 7763 7764 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7765 unsigned nparams = FTP->getNumParams(); 7766 assert(FD->getNumParams() == nparams); 7767 7768 bool HasExtraParameters = (nparams > 3); 7769 7770 // Darwin passes an undocumented fourth argument of type char**. If 7771 // other platforms start sprouting these, the logic below will start 7772 // getting shifty. 7773 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7774 HasExtraParameters = false; 7775 7776 if (HasExtraParameters) { 7777 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7778 FD->setInvalidDecl(true); 7779 nparams = 3; 7780 } 7781 7782 // FIXME: a lot of the following diagnostics would be improved 7783 // if we had some location information about types. 7784 7785 QualType CharPP = 7786 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7787 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7788 7789 for (unsigned i = 0; i < nparams; ++i) { 7790 QualType AT = FTP->getParamType(i); 7791 7792 bool mismatch = true; 7793 7794 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7795 mismatch = false; 7796 else if (Expected[i] == CharPP) { 7797 // As an extension, the following forms are okay: 7798 // char const ** 7799 // char const * const * 7800 // char * const * 7801 7802 QualifierCollector qs; 7803 const PointerType* PT; 7804 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7805 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7806 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7807 Context.CharTy)) { 7808 qs.removeConst(); 7809 mismatch = !qs.empty(); 7810 } 7811 } 7812 7813 if (mismatch) { 7814 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7815 // TODO: suggest replacing given type with expected type 7816 FD->setInvalidDecl(true); 7817 } 7818 } 7819 7820 if (nparams == 1 && !FD->isInvalidDecl()) { 7821 Diag(FD->getLocation(), diag::warn_main_one_arg); 7822 } 7823 7824 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7825 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7826 FD->setInvalidDecl(); 7827 } 7828 } 7829 7830 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7831 QualType T = FD->getType(); 7832 assert(T->isFunctionType() && "function decl is not of function type"); 7833 const FunctionType *FT = T->castAs<FunctionType>(); 7834 7835 // Set an implicit return of 'zero' if the function can return some integral, 7836 // enumeration, pointer or nullptr type. 7837 if (FT->getReturnType()->isIntegralOrEnumerationType() || 7838 FT->getReturnType()->isAnyPointerType() || 7839 FT->getReturnType()->isNullPtrType()) 7840 // DllMain is exempt because a return value of zero means it failed. 7841 if (FD->getName() != "DllMain") 7842 FD->setHasImplicitReturnZero(true); 7843 7844 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7845 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7846 FD->setInvalidDecl(); 7847 } 7848 } 7849 7850 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7851 // FIXME: Need strict checking. In C89, we need to check for 7852 // any assignment, increment, decrement, function-calls, or 7853 // commas outside of a sizeof. In C99, it's the same list, 7854 // except that the aforementioned are allowed in unevaluated 7855 // expressions. Everything else falls under the 7856 // "may accept other forms of constant expressions" exception. 7857 // (We never end up here for C++, so the constant expression 7858 // rules there don't matter.) 7859 if (Init->isConstantInitializer(Context, false)) 7860 return false; 7861 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7862 << Init->getSourceRange(); 7863 return true; 7864 } 7865 7866 namespace { 7867 // Visits an initialization expression to see if OrigDecl is evaluated in 7868 // its own initialization and throws a warning if it does. 7869 class SelfReferenceChecker 7870 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7871 Sema &S; 7872 Decl *OrigDecl; 7873 bool isRecordType; 7874 bool isPODType; 7875 bool isReferenceType; 7876 7877 public: 7878 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7879 7880 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7881 S(S), OrigDecl(OrigDecl) { 7882 isPODType = false; 7883 isRecordType = false; 7884 isReferenceType = false; 7885 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7886 isPODType = VD->getType().isPODType(S.Context); 7887 isRecordType = VD->getType()->isRecordType(); 7888 isReferenceType = VD->getType()->isReferenceType(); 7889 } 7890 } 7891 7892 // For most expressions, the cast is directly above the DeclRefExpr. 7893 // For conditional operators, the cast can be outside the conditional 7894 // operator if both expressions are DeclRefExpr's. 7895 void HandleValue(Expr *E) { 7896 if (isReferenceType) 7897 return; 7898 E = E->IgnoreParenImpCasts(); 7899 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7900 HandleDeclRefExpr(DRE); 7901 return; 7902 } 7903 7904 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7905 HandleValue(CO->getTrueExpr()); 7906 HandleValue(CO->getFalseExpr()); 7907 return; 7908 } 7909 7910 if (isa<MemberExpr>(E)) { 7911 Expr *Base = E->IgnoreParenImpCasts(); 7912 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7913 // Check for static member variables and don't warn on them. 7914 if (!isa<FieldDecl>(ME->getMemberDecl())) 7915 return; 7916 Base = ME->getBase()->IgnoreParenImpCasts(); 7917 } 7918 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7919 HandleDeclRefExpr(DRE); 7920 return; 7921 } 7922 } 7923 7924 // Reference types are handled here since all uses of references are 7925 // bad, not just r-value uses. 7926 void VisitDeclRefExpr(DeclRefExpr *E) { 7927 if (isReferenceType) 7928 HandleDeclRefExpr(E); 7929 } 7930 7931 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7932 if (E->getCastKind() == CK_LValueToRValue || 7933 (isRecordType && E->getCastKind() == CK_NoOp)) 7934 HandleValue(E->getSubExpr()); 7935 7936 Inherited::VisitImplicitCastExpr(E); 7937 } 7938 7939 void VisitMemberExpr(MemberExpr *E) { 7940 // Don't warn on arrays since they can be treated as pointers. 7941 if (E->getType()->canDecayToPointerType()) return; 7942 7943 // Warn when a non-static method call is followed by non-static member 7944 // field accesses, which is followed by a DeclRefExpr. 7945 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7946 bool Warn = (MD && !MD->isStatic()); 7947 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7948 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7949 if (!isa<FieldDecl>(ME->getMemberDecl())) 7950 Warn = false; 7951 Base = ME->getBase()->IgnoreParenImpCasts(); 7952 } 7953 7954 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7955 if (Warn) 7956 HandleDeclRefExpr(DRE); 7957 return; 7958 } 7959 7960 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7961 // Visit that expression. 7962 Visit(Base); 7963 } 7964 7965 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7966 if (E->getNumArgs() > 0) 7967 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7968 HandleDeclRefExpr(DRE); 7969 7970 Inherited::VisitCXXOperatorCallExpr(E); 7971 } 7972 7973 void VisitUnaryOperator(UnaryOperator *E) { 7974 // For POD record types, addresses of its own members are well-defined. 7975 if (E->getOpcode() == UO_AddrOf && isRecordType && 7976 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7977 if (!isPODType) 7978 HandleValue(E->getSubExpr()); 7979 return; 7980 } 7981 Inherited::VisitUnaryOperator(E); 7982 } 7983 7984 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7985 7986 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7987 Decl* ReferenceDecl = DRE->getDecl(); 7988 if (OrigDecl != ReferenceDecl) return; 7989 unsigned diag; 7990 if (isReferenceType) { 7991 diag = diag::warn_uninit_self_reference_in_reference_init; 7992 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7993 diag = diag::warn_static_self_reference_in_init; 7994 } else { 7995 diag = diag::warn_uninit_self_reference_in_init; 7996 } 7997 7998 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7999 S.PDiag(diag) 8000 << DRE->getNameInfo().getName() 8001 << OrigDecl->getLocation() 8002 << DRE->getSourceRange()); 8003 } 8004 }; 8005 8006 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8007 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8008 bool DirectInit) { 8009 // Parameters arguments are occassionially constructed with itself, 8010 // for instance, in recursive functions. Skip them. 8011 if (isa<ParmVarDecl>(OrigDecl)) 8012 return; 8013 8014 E = E->IgnoreParens(); 8015 8016 // Skip checking T a = a where T is not a record or reference type. 8017 // Doing so is a way to silence uninitialized warnings. 8018 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8019 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8020 if (ICE->getCastKind() == CK_LValueToRValue) 8021 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8022 if (DRE->getDecl() == OrigDecl) 8023 return; 8024 8025 SelfReferenceChecker(S, OrigDecl).Visit(E); 8026 } 8027 } 8028 8029 /// AddInitializerToDecl - Adds the initializer Init to the 8030 /// declaration dcl. If DirectInit is true, this is C++ direct 8031 /// initialization rather than copy initialization. 8032 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8033 bool DirectInit, bool TypeMayContainAuto) { 8034 // If there is no declaration, there was an error parsing it. Just ignore 8035 // the initializer. 8036 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8037 return; 8038 8039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8040 // With declarators parsed the way they are, the parser cannot 8041 // distinguish between a normal initializer and a pure-specifier. 8042 // Thus this grotesque test. 8043 IntegerLiteral *IL; 8044 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8045 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8046 CheckPureMethod(Method, Init->getSourceRange()); 8047 else { 8048 Diag(Method->getLocation(), diag::err_member_function_initialization) 8049 << Method->getDeclName() << Init->getSourceRange(); 8050 Method->setInvalidDecl(); 8051 } 8052 return; 8053 } 8054 8055 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8056 if (!VDecl) { 8057 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8058 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8059 RealDecl->setInvalidDecl(); 8060 return; 8061 } 8062 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8063 8064 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8065 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8066 Expr *DeduceInit = Init; 8067 // Initializer could be a C++ direct-initializer. Deduction only works if it 8068 // contains exactly one expression. 8069 if (CXXDirectInit) { 8070 if (CXXDirectInit->getNumExprs() == 0) { 8071 // It isn't possible to write this directly, but it is possible to 8072 // end up in this situation with "auto x(some_pack...);" 8073 Diag(CXXDirectInit->getLocStart(), 8074 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8075 : diag::err_auto_var_init_no_expression) 8076 << VDecl->getDeclName() << VDecl->getType() 8077 << VDecl->getSourceRange(); 8078 RealDecl->setInvalidDecl(); 8079 return; 8080 } else if (CXXDirectInit->getNumExprs() > 1) { 8081 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8082 VDecl->isInitCapture() 8083 ? diag::err_init_capture_multiple_expressions 8084 : diag::err_auto_var_init_multiple_expressions) 8085 << VDecl->getDeclName() << VDecl->getType() 8086 << VDecl->getSourceRange(); 8087 RealDecl->setInvalidDecl(); 8088 return; 8089 } else { 8090 DeduceInit = CXXDirectInit->getExpr(0); 8091 } 8092 } 8093 8094 // Expressions default to 'id' when we're in a debugger. 8095 bool DefaultedToAuto = false; 8096 if (getLangOpts().DebuggerCastResultToId && 8097 Init->getType() == Context.UnknownAnyTy) { 8098 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8099 if (Result.isInvalid()) { 8100 VDecl->setInvalidDecl(); 8101 return; 8102 } 8103 Init = Result.take(); 8104 DefaultedToAuto = true; 8105 } 8106 8107 QualType DeducedType; 8108 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8109 DAR_Failed) 8110 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8111 if (DeducedType.isNull()) { 8112 RealDecl->setInvalidDecl(); 8113 return; 8114 } 8115 VDecl->setType(DeducedType); 8116 assert(VDecl->isLinkageValid()); 8117 8118 // In ARC, infer lifetime. 8119 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8120 VDecl->setInvalidDecl(); 8121 8122 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8123 // 'id' instead of a specific object type prevents most of our usual checks. 8124 // We only want to warn outside of template instantiations, though: 8125 // inside a template, the 'id' could have come from a parameter. 8126 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8127 DeducedType->isObjCIdType()) { 8128 SourceLocation Loc = 8129 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8130 Diag(Loc, diag::warn_auto_var_is_id) 8131 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8132 } 8133 8134 // If this is a redeclaration, check that the type we just deduced matches 8135 // the previously declared type. 8136 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8137 // We never need to merge the type, because we cannot form an incomplete 8138 // array of auto, nor deduce such a type. 8139 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8140 } 8141 8142 // Check the deduced type is valid for a variable declaration. 8143 CheckVariableDeclarationType(VDecl); 8144 if (VDecl->isInvalidDecl()) 8145 return; 8146 } 8147 8148 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8149 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8150 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8151 VDecl->setInvalidDecl(); 8152 return; 8153 } 8154 8155 if (!VDecl->getType()->isDependentType()) { 8156 // A definition must end up with a complete type, which means it must be 8157 // complete with the restriction that an array type might be completed by 8158 // the initializer; note that later code assumes this restriction. 8159 QualType BaseDeclType = VDecl->getType(); 8160 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8161 BaseDeclType = Array->getElementType(); 8162 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8163 diag::err_typecheck_decl_incomplete_type)) { 8164 RealDecl->setInvalidDecl(); 8165 return; 8166 } 8167 8168 // The variable can not have an abstract class type. 8169 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8170 diag::err_abstract_type_in_decl, 8171 AbstractVariableType)) 8172 VDecl->setInvalidDecl(); 8173 } 8174 8175 const VarDecl *Def; 8176 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8177 Diag(VDecl->getLocation(), diag::err_redefinition) 8178 << VDecl->getDeclName(); 8179 Diag(Def->getLocation(), diag::note_previous_definition); 8180 VDecl->setInvalidDecl(); 8181 return; 8182 } 8183 8184 const VarDecl* PrevInit = 0; 8185 if (getLangOpts().CPlusPlus) { 8186 // C++ [class.static.data]p4 8187 // If a static data member is of const integral or const 8188 // enumeration type, its declaration in the class definition can 8189 // specify a constant-initializer which shall be an integral 8190 // constant expression (5.19). In that case, the member can appear 8191 // in integral constant expressions. The member shall still be 8192 // defined in a namespace scope if it is used in the program and the 8193 // namespace scope definition shall not contain an initializer. 8194 // 8195 // We already performed a redefinition check above, but for static 8196 // data members we also need to check whether there was an in-class 8197 // declaration with an initializer. 8198 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8199 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8200 << VDecl->getDeclName(); 8201 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8202 return; 8203 } 8204 8205 if (VDecl->hasLocalStorage()) 8206 getCurFunction()->setHasBranchProtectedScope(); 8207 8208 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8209 VDecl->setInvalidDecl(); 8210 return; 8211 } 8212 } 8213 8214 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8215 // a kernel function cannot be initialized." 8216 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8217 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8218 VDecl->setInvalidDecl(); 8219 return; 8220 } 8221 8222 // Get the decls type and save a reference for later, since 8223 // CheckInitializerTypes may change it. 8224 QualType DclT = VDecl->getType(), SavT = DclT; 8225 8226 // Expressions default to 'id' when we're in a debugger 8227 // and we are assigning it to a variable of Objective-C pointer type. 8228 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8229 Init->getType() == Context.UnknownAnyTy) { 8230 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8231 if (Result.isInvalid()) { 8232 VDecl->setInvalidDecl(); 8233 return; 8234 } 8235 Init = Result.take(); 8236 } 8237 8238 // Perform the initialization. 8239 if (!VDecl->isInvalidDecl()) { 8240 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8241 InitializationKind Kind 8242 = DirectInit ? 8243 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8244 Init->getLocStart(), 8245 Init->getLocEnd()) 8246 : InitializationKind::CreateDirectList( 8247 VDecl->getLocation()) 8248 : InitializationKind::CreateCopy(VDecl->getLocation(), 8249 Init->getLocStart()); 8250 8251 MultiExprArg Args = Init; 8252 if (CXXDirectInit) 8253 Args = MultiExprArg(CXXDirectInit->getExprs(), 8254 CXXDirectInit->getNumExprs()); 8255 8256 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8257 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8258 if (Result.isInvalid()) { 8259 VDecl->setInvalidDecl(); 8260 return; 8261 } 8262 8263 Init = Result.takeAs<Expr>(); 8264 } 8265 8266 // Check for self-references within variable initializers. 8267 // Variables declared within a function/method body (except for references) 8268 // are handled by a dataflow analysis. 8269 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8270 VDecl->getType()->isReferenceType()) { 8271 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8272 } 8273 8274 // If the type changed, it means we had an incomplete type that was 8275 // completed by the initializer. For example: 8276 // int ary[] = { 1, 3, 5 }; 8277 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8278 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8279 VDecl->setType(DclT); 8280 8281 if (!VDecl->isInvalidDecl()) { 8282 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8283 8284 if (VDecl->hasAttr<BlocksAttr>()) 8285 checkRetainCycles(VDecl, Init); 8286 8287 // It is safe to assign a weak reference into a strong variable. 8288 // Although this code can still have problems: 8289 // id x = self.weakProp; 8290 // id y = self.weakProp; 8291 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8292 // paths through the function. This should be revisited if 8293 // -Wrepeated-use-of-weak is made flow-sensitive. 8294 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8295 DiagnosticsEngine::Level Level = 8296 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8297 Init->getLocStart()); 8298 if (Level != DiagnosticsEngine::Ignored) 8299 getCurFunction()->markSafeWeakUse(Init); 8300 } 8301 } 8302 8303 // The initialization is usually a full-expression. 8304 // 8305 // FIXME: If this is a braced initialization of an aggregate, it is not 8306 // an expression, and each individual field initializer is a separate 8307 // full-expression. For instance, in: 8308 // 8309 // struct Temp { ~Temp(); }; 8310 // struct S { S(Temp); }; 8311 // struct T { S a, b; } t = { Temp(), Temp() } 8312 // 8313 // we should destroy the first Temp before constructing the second. 8314 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8315 false, 8316 VDecl->isConstexpr()); 8317 if (Result.isInvalid()) { 8318 VDecl->setInvalidDecl(); 8319 return; 8320 } 8321 Init = Result.take(); 8322 8323 // Attach the initializer to the decl. 8324 VDecl->setInit(Init); 8325 8326 if (VDecl->isLocalVarDecl()) { 8327 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8328 // static storage duration shall be constant expressions or string literals. 8329 // C++ does not have this restriction. 8330 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8331 if (VDecl->getStorageClass() == SC_Static) 8332 CheckForConstantInitializer(Init, DclT); 8333 // C89 is stricter than C99 for non-static aggregate types. 8334 // C89 6.5.7p3: All the expressions [...] in an initializer list 8335 // for an object that has aggregate or union type shall be 8336 // constant expressions. 8337 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8338 isa<InitListExpr>(Init) && 8339 !Init->isConstantInitializer(Context, false)) 8340 Diag(Init->getExprLoc(), 8341 diag::ext_aggregate_init_not_constant) 8342 << Init->getSourceRange(); 8343 } 8344 } else if (VDecl->isStaticDataMember() && 8345 VDecl->getLexicalDeclContext()->isRecord()) { 8346 // This is an in-class initialization for a static data member, e.g., 8347 // 8348 // struct S { 8349 // static const int value = 17; 8350 // }; 8351 8352 // C++ [class.mem]p4: 8353 // A member-declarator can contain a constant-initializer only 8354 // if it declares a static member (9.4) of const integral or 8355 // const enumeration type, see 9.4.2. 8356 // 8357 // C++11 [class.static.data]p3: 8358 // If a non-volatile const static data member is of integral or 8359 // enumeration type, its declaration in the class definition can 8360 // specify a brace-or-equal-initializer in which every initalizer-clause 8361 // that is an assignment-expression is a constant expression. A static 8362 // data member of literal type can be declared in the class definition 8363 // with the constexpr specifier; if so, its declaration shall specify a 8364 // brace-or-equal-initializer in which every initializer-clause that is 8365 // an assignment-expression is a constant expression. 8366 8367 // Do nothing on dependent types. 8368 if (DclT->isDependentType()) { 8369 8370 // Allow any 'static constexpr' members, whether or not they are of literal 8371 // type. We separately check that every constexpr variable is of literal 8372 // type. 8373 } else if (VDecl->isConstexpr()) { 8374 8375 // Require constness. 8376 } else if (!DclT.isConstQualified()) { 8377 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8378 << Init->getSourceRange(); 8379 VDecl->setInvalidDecl(); 8380 8381 // We allow integer constant expressions in all cases. 8382 } else if (DclT->isIntegralOrEnumerationType()) { 8383 // Check whether the expression is a constant expression. 8384 SourceLocation Loc; 8385 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8386 // In C++11, a non-constexpr const static data member with an 8387 // in-class initializer cannot be volatile. 8388 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8389 else if (Init->isValueDependent()) 8390 ; // Nothing to check. 8391 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8392 ; // Ok, it's an ICE! 8393 else if (Init->isEvaluatable(Context)) { 8394 // If we can constant fold the initializer through heroics, accept it, 8395 // but report this as a use of an extension for -pedantic. 8396 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8397 << Init->getSourceRange(); 8398 } else { 8399 // Otherwise, this is some crazy unknown case. Report the issue at the 8400 // location provided by the isIntegerConstantExpr failed check. 8401 Diag(Loc, diag::err_in_class_initializer_non_constant) 8402 << Init->getSourceRange(); 8403 VDecl->setInvalidDecl(); 8404 } 8405 8406 // We allow foldable floating-point constants as an extension. 8407 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8408 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8409 // it anyway and provide a fixit to add the 'constexpr'. 8410 if (getLangOpts().CPlusPlus11) { 8411 Diag(VDecl->getLocation(), 8412 diag::ext_in_class_initializer_float_type_cxx11) 8413 << DclT << Init->getSourceRange(); 8414 Diag(VDecl->getLocStart(), 8415 diag::note_in_class_initializer_float_type_cxx11) 8416 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8417 } else { 8418 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8419 << DclT << Init->getSourceRange(); 8420 8421 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8422 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8423 << Init->getSourceRange(); 8424 VDecl->setInvalidDecl(); 8425 } 8426 } 8427 8428 // Suggest adding 'constexpr' in C++11 for literal types. 8429 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8430 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8431 << DclT << Init->getSourceRange() 8432 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8433 VDecl->setConstexpr(true); 8434 8435 } else { 8436 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8437 << DclT << Init->getSourceRange(); 8438 VDecl->setInvalidDecl(); 8439 } 8440 } else if (VDecl->isFileVarDecl()) { 8441 if (VDecl->getStorageClass() == SC_Extern && 8442 (!getLangOpts().CPlusPlus || 8443 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8444 VDecl->isExternC())) && 8445 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8446 Diag(VDecl->getLocation(), diag::warn_extern_init); 8447 8448 // C99 6.7.8p4. All file scoped initializers need to be constant. 8449 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8450 CheckForConstantInitializer(Init, DclT); 8451 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8452 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8453 !Init->isValueDependent() && !VDecl->isConstexpr() && 8454 !Init->isConstantInitializer( 8455 Context, VDecl->getType()->isReferenceType())) { 8456 // GNU C++98 edits for __thread, [basic.start.init]p4: 8457 // An object of thread storage duration shall not require dynamic 8458 // initialization. 8459 // FIXME: Need strict checking here. 8460 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8461 if (getLangOpts().CPlusPlus11) 8462 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8463 } 8464 } 8465 8466 // We will represent direct-initialization similarly to copy-initialization: 8467 // int x(1); -as-> int x = 1; 8468 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8469 // 8470 // Clients that want to distinguish between the two forms, can check for 8471 // direct initializer using VarDecl::getInitStyle(). 8472 // A major benefit is that clients that don't particularly care about which 8473 // exactly form was it (like the CodeGen) can handle both cases without 8474 // special case code. 8475 8476 // C++ 8.5p11: 8477 // The form of initialization (using parentheses or '=') is generally 8478 // insignificant, but does matter when the entity being initialized has a 8479 // class type. 8480 if (CXXDirectInit) { 8481 assert(DirectInit && "Call-style initializer must be direct init."); 8482 VDecl->setInitStyle(VarDecl::CallInit); 8483 } else if (DirectInit) { 8484 // This must be list-initialization. No other way is direct-initialization. 8485 VDecl->setInitStyle(VarDecl::ListInit); 8486 } 8487 8488 CheckCompleteVariableDeclaration(VDecl); 8489 } 8490 8491 /// ActOnInitializerError - Given that there was an error parsing an 8492 /// initializer for the given declaration, try to return to some form 8493 /// of sanity. 8494 void Sema::ActOnInitializerError(Decl *D) { 8495 // Our main concern here is re-establishing invariants like "a 8496 // variable's type is either dependent or complete". 8497 if (!D || D->isInvalidDecl()) return; 8498 8499 VarDecl *VD = dyn_cast<VarDecl>(D); 8500 if (!VD) return; 8501 8502 // Auto types are meaningless if we can't make sense of the initializer. 8503 if (ParsingInitForAutoVars.count(D)) { 8504 D->setInvalidDecl(); 8505 return; 8506 } 8507 8508 QualType Ty = VD->getType(); 8509 if (Ty->isDependentType()) return; 8510 8511 // Require a complete type. 8512 if (RequireCompleteType(VD->getLocation(), 8513 Context.getBaseElementType(Ty), 8514 diag::err_typecheck_decl_incomplete_type)) { 8515 VD->setInvalidDecl(); 8516 return; 8517 } 8518 8519 // Require an abstract type. 8520 if (RequireNonAbstractType(VD->getLocation(), Ty, 8521 diag::err_abstract_type_in_decl, 8522 AbstractVariableType)) { 8523 VD->setInvalidDecl(); 8524 return; 8525 } 8526 8527 // Don't bother complaining about constructors or destructors, 8528 // though. 8529 } 8530 8531 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8532 bool TypeMayContainAuto) { 8533 // If there is no declaration, there was an error parsing it. Just ignore it. 8534 if (RealDecl == 0) 8535 return; 8536 8537 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8538 QualType Type = Var->getType(); 8539 8540 // C++11 [dcl.spec.auto]p3 8541 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8542 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8543 << Var->getDeclName() << Type; 8544 Var->setInvalidDecl(); 8545 return; 8546 } 8547 8548 // C++11 [class.static.data]p3: A static data member can be declared with 8549 // the constexpr specifier; if so, its declaration shall specify 8550 // a brace-or-equal-initializer. 8551 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8552 // the definition of a variable [...] or the declaration of a static data 8553 // member. 8554 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8555 if (Var->isStaticDataMember()) 8556 Diag(Var->getLocation(), 8557 diag::err_constexpr_static_mem_var_requires_init) 8558 << Var->getDeclName(); 8559 else 8560 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8561 Var->setInvalidDecl(); 8562 return; 8563 } 8564 8565 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8566 // be initialized. 8567 if (!Var->isInvalidDecl() && 8568 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8569 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8570 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 8571 Var->setInvalidDecl(); 8572 return; 8573 } 8574 8575 switch (Var->isThisDeclarationADefinition()) { 8576 case VarDecl::Definition: 8577 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8578 break; 8579 8580 // We have an out-of-line definition of a static data member 8581 // that has an in-class initializer, so we type-check this like 8582 // a declaration. 8583 // 8584 // Fall through 8585 8586 case VarDecl::DeclarationOnly: 8587 // It's only a declaration. 8588 8589 // Block scope. C99 6.7p7: If an identifier for an object is 8590 // declared with no linkage (C99 6.2.2p6), the type for the 8591 // object shall be complete. 8592 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8593 !Var->hasLinkage() && !Var->isInvalidDecl() && 8594 RequireCompleteType(Var->getLocation(), Type, 8595 diag::err_typecheck_decl_incomplete_type)) 8596 Var->setInvalidDecl(); 8597 8598 // Make sure that the type is not abstract. 8599 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8600 RequireNonAbstractType(Var->getLocation(), Type, 8601 diag::err_abstract_type_in_decl, 8602 AbstractVariableType)) 8603 Var->setInvalidDecl(); 8604 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8605 Var->getStorageClass() == SC_PrivateExtern) { 8606 Diag(Var->getLocation(), diag::warn_private_extern); 8607 Diag(Var->getLocation(), diag::note_private_extern); 8608 } 8609 8610 return; 8611 8612 case VarDecl::TentativeDefinition: 8613 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8614 // object that has file scope without an initializer, and without a 8615 // storage-class specifier or with the storage-class specifier "static", 8616 // constitutes a tentative definition. Note: A tentative definition with 8617 // external linkage is valid (C99 6.2.2p5). 8618 if (!Var->isInvalidDecl()) { 8619 if (const IncompleteArrayType *ArrayT 8620 = Context.getAsIncompleteArrayType(Type)) { 8621 if (RequireCompleteType(Var->getLocation(), 8622 ArrayT->getElementType(), 8623 diag::err_illegal_decl_array_incomplete_type)) 8624 Var->setInvalidDecl(); 8625 } else if (Var->getStorageClass() == SC_Static) { 8626 // C99 6.9.2p3: If the declaration of an identifier for an object is 8627 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8628 // declared type shall not be an incomplete type. 8629 // NOTE: code such as the following 8630 // static struct s; 8631 // struct s { int a; }; 8632 // is accepted by gcc. Hence here we issue a warning instead of 8633 // an error and we do not invalidate the static declaration. 8634 // NOTE: to avoid multiple warnings, only check the first declaration. 8635 if (Var->isFirstDecl()) 8636 RequireCompleteType(Var->getLocation(), Type, 8637 diag::ext_typecheck_decl_incomplete_type); 8638 } 8639 } 8640 8641 // Record the tentative definition; we're done. 8642 if (!Var->isInvalidDecl()) 8643 TentativeDefinitions.push_back(Var); 8644 return; 8645 } 8646 8647 // Provide a specific diagnostic for uninitialized variable 8648 // definitions with incomplete array type. 8649 if (Type->isIncompleteArrayType()) { 8650 Diag(Var->getLocation(), 8651 diag::err_typecheck_incomplete_array_needs_initializer); 8652 Var->setInvalidDecl(); 8653 return; 8654 } 8655 8656 // Provide a specific diagnostic for uninitialized variable 8657 // definitions with reference type. 8658 if (Type->isReferenceType()) { 8659 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8660 << Var->getDeclName() 8661 << SourceRange(Var->getLocation(), Var->getLocation()); 8662 Var->setInvalidDecl(); 8663 return; 8664 } 8665 8666 // Do not attempt to type-check the default initializer for a 8667 // variable with dependent type. 8668 if (Type->isDependentType()) 8669 return; 8670 8671 if (Var->isInvalidDecl()) 8672 return; 8673 8674 if (RequireCompleteType(Var->getLocation(), 8675 Context.getBaseElementType(Type), 8676 diag::err_typecheck_decl_incomplete_type)) { 8677 Var->setInvalidDecl(); 8678 return; 8679 } 8680 8681 // The variable can not have an abstract class type. 8682 if (RequireNonAbstractType(Var->getLocation(), Type, 8683 diag::err_abstract_type_in_decl, 8684 AbstractVariableType)) { 8685 Var->setInvalidDecl(); 8686 return; 8687 } 8688 8689 // Check for jumps past the implicit initializer. C++0x 8690 // clarifies that this applies to a "variable with automatic 8691 // storage duration", not a "local variable". 8692 // C++11 [stmt.dcl]p3 8693 // A program that jumps from a point where a variable with automatic 8694 // storage duration is not in scope to a point where it is in scope is 8695 // ill-formed unless the variable has scalar type, class type with a 8696 // trivial default constructor and a trivial destructor, a cv-qualified 8697 // version of one of these types, or an array of one of the preceding 8698 // types and is declared without an initializer. 8699 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8700 if (const RecordType *Record 8701 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8702 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8703 // Mark the function for further checking even if the looser rules of 8704 // C++11 do not require such checks, so that we can diagnose 8705 // incompatibilities with C++98. 8706 if (!CXXRecord->isPOD()) 8707 getCurFunction()->setHasBranchProtectedScope(); 8708 } 8709 } 8710 8711 // C++03 [dcl.init]p9: 8712 // If no initializer is specified for an object, and the 8713 // object is of (possibly cv-qualified) non-POD class type (or 8714 // array thereof), the object shall be default-initialized; if 8715 // the object is of const-qualified type, the underlying class 8716 // type shall have a user-declared default 8717 // constructor. Otherwise, if no initializer is specified for 8718 // a non- static object, the object and its subobjects, if 8719 // any, have an indeterminate initial value); if the object 8720 // or any of its subobjects are of const-qualified type, the 8721 // program is ill-formed. 8722 // C++0x [dcl.init]p11: 8723 // If no initializer is specified for an object, the object is 8724 // default-initialized; [...]. 8725 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8726 InitializationKind Kind 8727 = InitializationKind::CreateDefault(Var->getLocation()); 8728 8729 InitializationSequence InitSeq(*this, Entity, Kind, None); 8730 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8731 if (Init.isInvalid()) 8732 Var->setInvalidDecl(); 8733 else if (Init.get()) { 8734 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8735 // This is important for template substitution. 8736 Var->setInitStyle(VarDecl::CallInit); 8737 } 8738 8739 CheckCompleteVariableDeclaration(Var); 8740 } 8741 } 8742 8743 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8744 VarDecl *VD = dyn_cast<VarDecl>(D); 8745 if (!VD) { 8746 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8747 D->setInvalidDecl(); 8748 return; 8749 } 8750 8751 VD->setCXXForRangeDecl(true); 8752 8753 // for-range-declaration cannot be given a storage class specifier. 8754 int Error = -1; 8755 switch (VD->getStorageClass()) { 8756 case SC_None: 8757 break; 8758 case SC_Extern: 8759 Error = 0; 8760 break; 8761 case SC_Static: 8762 Error = 1; 8763 break; 8764 case SC_PrivateExtern: 8765 Error = 2; 8766 break; 8767 case SC_Auto: 8768 Error = 3; 8769 break; 8770 case SC_Register: 8771 Error = 4; 8772 break; 8773 case SC_OpenCLWorkGroupLocal: 8774 llvm_unreachable("Unexpected storage class"); 8775 } 8776 if (VD->isConstexpr()) 8777 Error = 5; 8778 if (Error != -1) { 8779 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8780 << VD->getDeclName() << Error; 8781 D->setInvalidDecl(); 8782 } 8783 } 8784 8785 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8786 if (var->isInvalidDecl()) return; 8787 8788 // In ARC, don't allow jumps past the implicit initialization of a 8789 // local retaining variable. 8790 if (getLangOpts().ObjCAutoRefCount && 8791 var->hasLocalStorage()) { 8792 switch (var->getType().getObjCLifetime()) { 8793 case Qualifiers::OCL_None: 8794 case Qualifiers::OCL_ExplicitNone: 8795 case Qualifiers::OCL_Autoreleasing: 8796 break; 8797 8798 case Qualifiers::OCL_Weak: 8799 case Qualifiers::OCL_Strong: 8800 getCurFunction()->setHasBranchProtectedScope(); 8801 break; 8802 } 8803 } 8804 8805 // Warn about externally-visible variables being defined without a 8806 // prior declaration. We only want to do this for global 8807 // declarations, but we also specifically need to avoid doing it for 8808 // class members because the linkage of an anonymous class can 8809 // change if it's later given a typedef name. 8810 if (var->isThisDeclarationADefinition() && 8811 var->getDeclContext()->getRedeclContext()->isFileContext() && 8812 var->isExternallyVisible() && var->hasLinkage() && 8813 getDiagnostics().getDiagnosticLevel( 8814 diag::warn_missing_variable_declarations, 8815 var->getLocation())) { 8816 // Find a previous declaration that's not a definition. 8817 VarDecl *prev = var->getPreviousDecl(); 8818 while (prev && prev->isThisDeclarationADefinition()) 8819 prev = prev->getPreviousDecl(); 8820 8821 if (!prev) 8822 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8823 } 8824 8825 if (var->getTLSKind() == VarDecl::TLS_Static && 8826 var->getType().isDestructedType()) { 8827 // GNU C++98 edits for __thread, [basic.start.term]p3: 8828 // The type of an object with thread storage duration shall not 8829 // have a non-trivial destructor. 8830 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8831 if (getLangOpts().CPlusPlus11) 8832 Diag(var->getLocation(), diag::note_use_thread_local); 8833 } 8834 8835 // All the following checks are C++ only. 8836 if (!getLangOpts().CPlusPlus) return; 8837 8838 QualType type = var->getType(); 8839 if (type->isDependentType()) return; 8840 8841 // __block variables might require us to capture a copy-initializer. 8842 if (var->hasAttr<BlocksAttr>()) { 8843 // It's currently invalid to ever have a __block variable with an 8844 // array type; should we diagnose that here? 8845 8846 // Regardless, we don't want to ignore array nesting when 8847 // constructing this copy. 8848 if (type->isStructureOrClassType()) { 8849 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8850 SourceLocation poi = var->getLocation(); 8851 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8852 ExprResult result 8853 = PerformMoveOrCopyInitialization( 8854 InitializedEntity::InitializeBlock(poi, type, false), 8855 var, var->getType(), varRef, /*AllowNRVO=*/true); 8856 if (!result.isInvalid()) { 8857 result = MaybeCreateExprWithCleanups(result); 8858 Expr *init = result.takeAs<Expr>(); 8859 Context.setBlockVarCopyInits(var, init); 8860 } 8861 } 8862 } 8863 8864 Expr *Init = var->getInit(); 8865 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8866 QualType baseType = Context.getBaseElementType(type); 8867 8868 if (!var->getDeclContext()->isDependentContext() && 8869 Init && !Init->isValueDependent()) { 8870 if (IsGlobal && !var->isConstexpr() && 8871 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8872 var->getLocation()) 8873 != DiagnosticsEngine::Ignored) { 8874 // Warn about globals which don't have a constant initializer. Don't 8875 // warn about globals with a non-trivial destructor because we already 8876 // warned about them. 8877 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8878 if (!(RD && !RD->hasTrivialDestructor()) && 8879 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8880 Diag(var->getLocation(), diag::warn_global_constructor) 8881 << Init->getSourceRange(); 8882 } 8883 8884 if (var->isConstexpr()) { 8885 SmallVector<PartialDiagnosticAt, 8> Notes; 8886 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8887 SourceLocation DiagLoc = var->getLocation(); 8888 // If the note doesn't add any useful information other than a source 8889 // location, fold it into the primary diagnostic. 8890 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 8891 diag::note_invalid_subexpr_in_const_expr) { 8892 DiagLoc = Notes[0].first; 8893 Notes.clear(); 8894 } 8895 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 8896 << var << Init->getSourceRange(); 8897 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 8898 Diag(Notes[I].first, Notes[I].second); 8899 } 8900 } else if (var->isUsableInConstantExpressions(Context)) { 8901 // Check whether the initializer of a const variable of integral or 8902 // enumeration type is an ICE now, since we can't tell whether it was 8903 // initialized by a constant expression if we check later. 8904 var->checkInitIsICE(); 8905 } 8906 } 8907 8908 // Require the destructor. 8909 if (const RecordType *recordType = baseType->getAs<RecordType>()) 8910 FinalizeVarWithDestructor(var, recordType); 8911 } 8912 8913 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 8914 /// any semantic actions necessary after any initializer has been attached. 8915 void 8916 Sema::FinalizeDeclaration(Decl *ThisDecl) { 8917 // Note that we are no longer parsing the initializer for this declaration. 8918 ParsingInitForAutoVars.erase(ThisDecl); 8919 8920 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 8921 if (!VD) 8922 return; 8923 8924 checkAttributesAfterMerging(*this, *VD); 8925 8926 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 8927 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 8928 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 8929 VD->dropAttr<UsedAttr>(); 8930 } 8931 } 8932 8933 if (!VD->isInvalidDecl() && 8934 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 8935 if (const VarDecl *Def = VD->getDefinition()) { 8936 if (Def->hasAttr<AliasAttr>()) { 8937 Diag(VD->getLocation(), diag::err_tentative_after_alias) 8938 << VD->getDeclName(); 8939 Diag(Def->getLocation(), diag::note_previous_definition); 8940 VD->setInvalidDecl(); 8941 } 8942 } 8943 } 8944 8945 const DeclContext *DC = VD->getDeclContext(); 8946 // If there's a #pragma GCC visibility in scope, and this isn't a class 8947 // member, set the visibility of this variable. 8948 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 8949 AddPushedVisibilityAttribute(VD); 8950 8951 if (VD->isFileVarDecl()) 8952 MarkUnusedFileScopedDecl(VD); 8953 8954 // Now we have parsed the initializer and can update the table of magic 8955 // tag values. 8956 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8957 !VD->getType()->isIntegralOrEnumerationType()) 8958 return; 8959 8960 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8961 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8962 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8963 I != E; ++I) { 8964 const Expr *MagicValueExpr = VD->getInit(); 8965 if (!MagicValueExpr) { 8966 continue; 8967 } 8968 llvm::APSInt MagicValueInt; 8969 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8970 Diag(I->getRange().getBegin(), 8971 diag::err_type_tag_for_datatype_not_ice) 8972 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8973 continue; 8974 } 8975 if (MagicValueInt.getActiveBits() > 64) { 8976 Diag(I->getRange().getBegin(), 8977 diag::err_type_tag_for_datatype_too_large) 8978 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8979 continue; 8980 } 8981 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8982 RegisterTypeTagForDatatype(I->getArgumentKind(), 8983 MagicValue, 8984 I->getMatchingCType(), 8985 I->getLayoutCompatible(), 8986 I->getMustBeNull()); 8987 } 8988 } 8989 8990 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8991 ArrayRef<Decl *> Group) { 8992 SmallVector<Decl*, 8> Decls; 8993 8994 if (DS.isTypeSpecOwned()) 8995 Decls.push_back(DS.getRepAsDecl()); 8996 8997 DeclaratorDecl *FirstDeclaratorInGroup = 0; 8998 for (unsigned i = 0, e = Group.size(); i != e; ++i) 8999 if (Decl *D = Group[i]) { 9000 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9001 if (!FirstDeclaratorInGroup) 9002 FirstDeclaratorInGroup = DD; 9003 Decls.push_back(D); 9004 } 9005 9006 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9007 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9008 HandleTagNumbering(*this, Tag); 9009 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9010 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9011 } 9012 } 9013 9014 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9015 } 9016 9017 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9018 /// group, performing any necessary semantic checking. 9019 Sema::DeclGroupPtrTy 9020 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 9021 bool TypeMayContainAuto) { 9022 // C++0x [dcl.spec.auto]p7: 9023 // If the type deduced for the template parameter U is not the same in each 9024 // deduction, the program is ill-formed. 9025 // FIXME: When initializer-list support is added, a distinction is needed 9026 // between the deduced type U and the deduced type which 'auto' stands for. 9027 // auto a = 0, b = { 1, 2, 3 }; 9028 // is legal because the deduced type U is 'int' in both cases. 9029 if (TypeMayContainAuto && Group.size() > 1) { 9030 QualType Deduced; 9031 CanQualType DeducedCanon; 9032 VarDecl *DeducedDecl = 0; 9033 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9034 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9035 AutoType *AT = D->getType()->getContainedAutoType(); 9036 // Don't reissue diagnostics when instantiating a template. 9037 if (AT && D->isInvalidDecl()) 9038 break; 9039 QualType U = AT ? AT->getDeducedType() : QualType(); 9040 if (!U.isNull()) { 9041 CanQualType UCanon = Context.getCanonicalType(U); 9042 if (Deduced.isNull()) { 9043 Deduced = U; 9044 DeducedCanon = UCanon; 9045 DeducedDecl = D; 9046 } else if (DeducedCanon != UCanon) { 9047 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9048 diag::err_auto_different_deductions) 9049 << (AT->isDecltypeAuto() ? 1 : 0) 9050 << Deduced << DeducedDecl->getDeclName() 9051 << U << D->getDeclName() 9052 << DeducedDecl->getInit()->getSourceRange() 9053 << D->getInit()->getSourceRange(); 9054 D->setInvalidDecl(); 9055 break; 9056 } 9057 } 9058 } 9059 } 9060 } 9061 9062 ActOnDocumentableDecls(Group); 9063 9064 return DeclGroupPtrTy::make( 9065 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9066 } 9067 9068 void Sema::ActOnDocumentableDecl(Decl *D) { 9069 ActOnDocumentableDecls(D); 9070 } 9071 9072 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9073 // Don't parse the comment if Doxygen diagnostics are ignored. 9074 if (Group.empty() || !Group[0]) 9075 return; 9076 9077 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9078 Group[0]->getLocation()) 9079 == DiagnosticsEngine::Ignored) 9080 return; 9081 9082 if (Group.size() >= 2) { 9083 // This is a decl group. Normally it will contain only declarations 9084 // produced from declarator list. But in case we have any definitions or 9085 // additional declaration references: 9086 // 'typedef struct S {} S;' 9087 // 'typedef struct S *S;' 9088 // 'struct S *pS;' 9089 // FinalizeDeclaratorGroup adds these as separate declarations. 9090 Decl *MaybeTagDecl = Group[0]; 9091 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9092 Group = Group.slice(1); 9093 } 9094 } 9095 9096 // See if there are any new comments that are not attached to a decl. 9097 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9098 if (!Comments.empty() && 9099 !Comments.back()->isAttached()) { 9100 // There is at least one comment that not attached to a decl. 9101 // Maybe it should be attached to one of these decls? 9102 // 9103 // Note that this way we pick up not only comments that precede the 9104 // declaration, but also comments that *follow* the declaration -- thanks to 9105 // the lookahead in the lexer: we've consumed the semicolon and looked 9106 // ahead through comments. 9107 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9108 Context.getCommentForDecl(Group[i], &PP); 9109 } 9110 } 9111 9112 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9113 /// to introduce parameters into function prototype scope. 9114 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9115 const DeclSpec &DS = D.getDeclSpec(); 9116 9117 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9118 9119 // C++03 [dcl.stc]p2 also permits 'auto'. 9120 VarDecl::StorageClass StorageClass = SC_None; 9121 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9122 StorageClass = SC_Register; 9123 } else if (getLangOpts().CPlusPlus && 9124 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9125 StorageClass = SC_Auto; 9126 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9127 Diag(DS.getStorageClassSpecLoc(), 9128 diag::err_invalid_storage_class_in_func_decl); 9129 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9130 } 9131 9132 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9133 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9134 << DeclSpec::getSpecifierName(TSCS); 9135 if (DS.isConstexprSpecified()) 9136 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9137 << 0; 9138 9139 DiagnoseFunctionSpecifiers(DS); 9140 9141 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9142 QualType parmDeclType = TInfo->getType(); 9143 9144 if (getLangOpts().CPlusPlus) { 9145 // Check that there are no default arguments inside the type of this 9146 // parameter. 9147 CheckExtraCXXDefaultArguments(D); 9148 9149 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9150 if (D.getCXXScopeSpec().isSet()) { 9151 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9152 << D.getCXXScopeSpec().getRange(); 9153 D.getCXXScopeSpec().clear(); 9154 } 9155 } 9156 9157 // Ensure we have a valid name 9158 IdentifierInfo *II = 0; 9159 if (D.hasName()) { 9160 II = D.getIdentifier(); 9161 if (!II) { 9162 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9163 << GetNameForDeclarator(D).getName(); 9164 D.setInvalidType(true); 9165 } 9166 } 9167 9168 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9169 if (II) { 9170 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9171 ForRedeclaration); 9172 LookupName(R, S); 9173 if (R.isSingleResult()) { 9174 NamedDecl *PrevDecl = R.getFoundDecl(); 9175 if (PrevDecl->isTemplateParameter()) { 9176 // Maybe we will complain about the shadowed template parameter. 9177 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9178 // Just pretend that we didn't see the previous declaration. 9179 PrevDecl = 0; 9180 } else if (S->isDeclScope(PrevDecl)) { 9181 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9182 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9183 9184 // Recover by removing the name 9185 II = 0; 9186 D.SetIdentifier(0, D.getIdentifierLoc()); 9187 D.setInvalidType(true); 9188 } 9189 } 9190 } 9191 9192 // Temporarily put parameter variables in the translation unit, not 9193 // the enclosing context. This prevents them from accidentally 9194 // looking like class members in C++. 9195 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9196 D.getLocStart(), 9197 D.getIdentifierLoc(), II, 9198 parmDeclType, TInfo, 9199 StorageClass); 9200 9201 if (D.isInvalidType()) 9202 New->setInvalidDecl(); 9203 9204 assert(S->isFunctionPrototypeScope()); 9205 assert(S->getFunctionPrototypeDepth() >= 1); 9206 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9207 S->getNextFunctionPrototypeIndex()); 9208 9209 // Add the parameter declaration into this scope. 9210 S->AddDecl(New); 9211 if (II) 9212 IdResolver.AddDecl(New); 9213 9214 ProcessDeclAttributes(S, New, D); 9215 9216 if (D.getDeclSpec().isModulePrivateSpecified()) 9217 Diag(New->getLocation(), diag::err_module_private_local) 9218 << 1 << New->getDeclName() 9219 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9220 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9221 9222 if (New->hasAttr<BlocksAttr>()) { 9223 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9224 } 9225 return New; 9226 } 9227 9228 /// \brief Synthesizes a variable for a parameter arising from a 9229 /// typedef. 9230 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9231 SourceLocation Loc, 9232 QualType T) { 9233 /* FIXME: setting StartLoc == Loc. 9234 Would it be worth to modify callers so as to provide proper source 9235 location for the unnamed parameters, embedding the parameter's type? */ 9236 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9237 T, Context.getTrivialTypeSourceInfo(T, Loc), 9238 SC_None, 0); 9239 Param->setImplicit(); 9240 return Param; 9241 } 9242 9243 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9244 ParmVarDecl * const *ParamEnd) { 9245 // Don't diagnose unused-parameter errors in template instantiations; we 9246 // will already have done so in the template itself. 9247 if (!ActiveTemplateInstantiations.empty()) 9248 return; 9249 9250 for (; Param != ParamEnd; ++Param) { 9251 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9252 !(*Param)->hasAttr<UnusedAttr>()) { 9253 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9254 << (*Param)->getDeclName(); 9255 } 9256 } 9257 } 9258 9259 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9260 ParmVarDecl * const *ParamEnd, 9261 QualType ReturnTy, 9262 NamedDecl *D) { 9263 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9264 return; 9265 9266 // Warn if the return value is pass-by-value and larger than the specified 9267 // threshold. 9268 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9269 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9270 if (Size > LangOpts.NumLargeByValueCopy) 9271 Diag(D->getLocation(), diag::warn_return_value_size) 9272 << D->getDeclName() << Size; 9273 } 9274 9275 // Warn if any parameter is pass-by-value and larger than the specified 9276 // threshold. 9277 for (; Param != ParamEnd; ++Param) { 9278 QualType T = (*Param)->getType(); 9279 if (T->isDependentType() || !T.isPODType(Context)) 9280 continue; 9281 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9282 if (Size > LangOpts.NumLargeByValueCopy) 9283 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9284 << (*Param)->getDeclName() << Size; 9285 } 9286 } 9287 9288 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9289 SourceLocation NameLoc, IdentifierInfo *Name, 9290 QualType T, TypeSourceInfo *TSInfo, 9291 VarDecl::StorageClass StorageClass) { 9292 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9293 if (getLangOpts().ObjCAutoRefCount && 9294 T.getObjCLifetime() == Qualifiers::OCL_None && 9295 T->isObjCLifetimeType()) { 9296 9297 Qualifiers::ObjCLifetime lifetime; 9298 9299 // Special cases for arrays: 9300 // - if it's const, use __unsafe_unretained 9301 // - otherwise, it's an error 9302 if (T->isArrayType()) { 9303 if (!T.isConstQualified()) { 9304 DelayedDiagnostics.add( 9305 sema::DelayedDiagnostic::makeForbiddenType( 9306 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9307 } 9308 lifetime = Qualifiers::OCL_ExplicitNone; 9309 } else { 9310 lifetime = T->getObjCARCImplicitLifetime(); 9311 } 9312 T = Context.getLifetimeQualifiedType(T, lifetime); 9313 } 9314 9315 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9316 Context.getAdjustedParameterType(T), 9317 TSInfo, 9318 StorageClass, 0); 9319 9320 // Parameters can not be abstract class types. 9321 // For record types, this is done by the AbstractClassUsageDiagnoser once 9322 // the class has been completely parsed. 9323 if (!CurContext->isRecord() && 9324 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9325 AbstractParamType)) 9326 New->setInvalidDecl(); 9327 9328 // Parameter declarators cannot be interface types. All ObjC objects are 9329 // passed by reference. 9330 if (T->isObjCObjectType()) { 9331 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9332 Diag(NameLoc, 9333 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9334 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9335 T = Context.getObjCObjectPointerType(T); 9336 New->setType(T); 9337 } 9338 9339 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9340 // duration shall not be qualified by an address-space qualifier." 9341 // Since all parameters have automatic store duration, they can not have 9342 // an address space. 9343 if (T.getAddressSpace() != 0) { 9344 Diag(NameLoc, diag::err_arg_with_address_space); 9345 New->setInvalidDecl(); 9346 } 9347 9348 return New; 9349 } 9350 9351 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9352 SourceLocation LocAfterDecls) { 9353 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9354 9355 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9356 // for a K&R function. 9357 if (!FTI.hasPrototype) { 9358 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 9359 --i; 9360 if (FTI.ArgInfo[i].Param == 0) { 9361 SmallString<256> Code; 9362 llvm::raw_svector_ostream(Code) << " int " 9363 << FTI.ArgInfo[i].Ident->getName() 9364 << ";\n"; 9365 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 9366 << FTI.ArgInfo[i].Ident 9367 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9368 9369 // Implicitly declare the argument as type 'int' for lack of a better 9370 // type. 9371 AttributeFactory attrs; 9372 DeclSpec DS(attrs); 9373 const char* PrevSpec; // unused 9374 unsigned DiagID; // unused 9375 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 9376 PrevSpec, DiagID, Context.getPrintingPolicy()); 9377 // Use the identifier location for the type source range. 9378 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 9379 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 9380 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9381 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 9382 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 9383 } 9384 } 9385 } 9386 } 9387 9388 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9389 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9390 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9391 Scope *ParentScope = FnBodyScope->getParent(); 9392 9393 D.setFunctionDefinitionKind(FDK_Definition); 9394 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9395 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9396 } 9397 9398 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9399 const FunctionDecl*& PossibleZeroParamPrototype) { 9400 // Don't warn about invalid declarations. 9401 if (FD->isInvalidDecl()) 9402 return false; 9403 9404 // Or declarations that aren't global. 9405 if (!FD->isGlobal()) 9406 return false; 9407 9408 // Don't warn about C++ member functions. 9409 if (isa<CXXMethodDecl>(FD)) 9410 return false; 9411 9412 // Don't warn about 'main'. 9413 if (FD->isMain()) 9414 return false; 9415 9416 // Don't warn about inline functions. 9417 if (FD->isInlined()) 9418 return false; 9419 9420 // Don't warn about function templates. 9421 if (FD->getDescribedFunctionTemplate()) 9422 return false; 9423 9424 // Don't warn about function template specializations. 9425 if (FD->isFunctionTemplateSpecialization()) 9426 return false; 9427 9428 // Don't warn for OpenCL kernels. 9429 if (FD->hasAttr<OpenCLKernelAttr>()) 9430 return false; 9431 9432 bool MissingPrototype = true; 9433 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9434 Prev; Prev = Prev->getPreviousDecl()) { 9435 // Ignore any declarations that occur in function or method 9436 // scope, because they aren't visible from the header. 9437 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9438 continue; 9439 9440 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9441 if (FD->getNumParams() == 0) 9442 PossibleZeroParamPrototype = Prev; 9443 break; 9444 } 9445 9446 return MissingPrototype; 9447 } 9448 9449 void 9450 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9451 const FunctionDecl *EffectiveDefinition) { 9452 // Don't complain if we're in GNU89 mode and the previous definition 9453 // was an extern inline function. 9454 const FunctionDecl *Definition = EffectiveDefinition; 9455 if (!Definition) 9456 if (!FD->isDefined(Definition)) 9457 return; 9458 9459 if (canRedefineFunction(Definition, getLangOpts())) 9460 return; 9461 9462 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9463 Definition->getStorageClass() == SC_Extern) 9464 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9465 << FD->getDeclName() << getLangOpts().CPlusPlus; 9466 else 9467 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9468 9469 Diag(Definition->getLocation(), diag::note_previous_definition); 9470 FD->setInvalidDecl(); 9471 } 9472 9473 9474 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9475 Sema &S) { 9476 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9477 9478 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9479 LSI->CallOperator = CallOperator; 9480 LSI->Lambda = LambdaClass; 9481 LSI->ReturnType = CallOperator->getReturnType(); 9482 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9483 9484 if (LCD == LCD_None) 9485 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9486 else if (LCD == LCD_ByCopy) 9487 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9488 else if (LCD == LCD_ByRef) 9489 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9490 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9491 9492 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9493 LSI->Mutable = !CallOperator->isConst(); 9494 9495 // Add the captures to the LSI so they can be noted as already 9496 // captured within tryCaptureVar. 9497 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(), 9498 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) { 9499 if (C->capturesVariable()) { 9500 VarDecl *VD = C->getCapturedVar(); 9501 if (VD->isInitCapture()) 9502 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9503 QualType CaptureType = VD->getType(); 9504 const bool ByRef = C->getCaptureKind() == LCK_ByRef; 9505 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9506 /*RefersToEnclosingLocal*/true, C->getLocation(), 9507 /*EllipsisLoc*/C->isPackExpansion() 9508 ? C->getEllipsisLoc() : SourceLocation(), 9509 CaptureType, /*Expr*/ 0); 9510 9511 } else if (C->capturesThis()) { 9512 LSI->addThisCapture(/*Nested*/ false, C->getLocation(), 9513 S.getCurrentThisType(), /*Expr*/ 0); 9514 } 9515 } 9516 } 9517 9518 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9519 // Clear the last template instantiation error context. 9520 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9521 9522 if (!D) 9523 return D; 9524 FunctionDecl *FD = 0; 9525 9526 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9527 FD = FunTmpl->getTemplatedDecl(); 9528 else 9529 FD = cast<FunctionDecl>(D); 9530 // If we are instantiating a generic lambda call operator, push 9531 // a LambdaScopeInfo onto the function stack. But use the information 9532 // that's already been calculated (ActOnLambdaExpr) to prime the current 9533 // LambdaScopeInfo. 9534 // When the template operator is being specialized, the LambdaScopeInfo, 9535 // has to be properly restored so that tryCaptureVariable doesn't try 9536 // and capture any new variables. In addition when calculating potential 9537 // captures during transformation of nested lambdas, it is necessary to 9538 // have the LSI properly restored. 9539 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9540 assert(ActiveTemplateInstantiations.size() && 9541 "There should be an active template instantiation on the stack " 9542 "when instantiating a generic lambda!"); 9543 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9544 } 9545 else 9546 // Enter a new function scope 9547 PushFunctionScope(); 9548 9549 // See if this is a redefinition. 9550 if (!FD->isLateTemplateParsed()) 9551 CheckForFunctionRedefinition(FD); 9552 9553 // Builtin functions cannot be defined. 9554 if (unsigned BuiltinID = FD->getBuiltinID()) { 9555 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9556 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9557 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9558 FD->setInvalidDecl(); 9559 } 9560 } 9561 9562 // The return type of a function definition must be complete 9563 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9564 QualType ResultType = FD->getReturnType(); 9565 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9566 !FD->isInvalidDecl() && 9567 RequireCompleteType(FD->getLocation(), ResultType, 9568 diag::err_func_def_incomplete_result)) 9569 FD->setInvalidDecl(); 9570 9571 // GNU warning -Wmissing-prototypes: 9572 // Warn if a global function is defined without a previous 9573 // prototype declaration. This warning is issued even if the 9574 // definition itself provides a prototype. The aim is to detect 9575 // global functions that fail to be declared in header files. 9576 const FunctionDecl *PossibleZeroParamPrototype = 0; 9577 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9578 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9579 9580 if (PossibleZeroParamPrototype) { 9581 // We found a declaration that is not a prototype, 9582 // but that could be a zero-parameter prototype 9583 if (TypeSourceInfo *TI = 9584 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9585 TypeLoc TL = TI->getTypeLoc(); 9586 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9587 Diag(PossibleZeroParamPrototype->getLocation(), 9588 diag::note_declaration_not_a_prototype) 9589 << PossibleZeroParamPrototype 9590 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9591 } 9592 } 9593 } 9594 9595 if (FnBodyScope) 9596 PushDeclContext(FnBodyScope, FD); 9597 9598 // Check the validity of our function parameters 9599 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9600 /*CheckParameterNames=*/true); 9601 9602 // Introduce our parameters into the function scope 9603 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 9604 ParmVarDecl *Param = FD->getParamDecl(p); 9605 Param->setOwningFunction(FD); 9606 9607 // If this has an identifier, add it to the scope stack. 9608 if (Param->getIdentifier() && FnBodyScope) { 9609 CheckShadow(FnBodyScope, Param); 9610 9611 PushOnScopeChains(Param, FnBodyScope); 9612 } 9613 } 9614 9615 // If we had any tags defined in the function prototype, 9616 // introduce them into the function scope. 9617 if (FnBodyScope) { 9618 for (ArrayRef<NamedDecl *>::iterator 9619 I = FD->getDeclsInPrototypeScope().begin(), 9620 E = FD->getDeclsInPrototypeScope().end(); 9621 I != E; ++I) { 9622 NamedDecl *D = *I; 9623 9624 // Some of these decls (like enums) may have been pinned to the translation unit 9625 // for lack of a real context earlier. If so, remove from the translation unit 9626 // and reattach to the current context. 9627 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9628 // Is the decl actually in the context? 9629 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 9630 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 9631 if (*DI == D) { 9632 Context.getTranslationUnitDecl()->removeDecl(D); 9633 break; 9634 } 9635 } 9636 // Either way, reassign the lexical decl context to our FunctionDecl. 9637 D->setLexicalDeclContext(CurContext); 9638 } 9639 9640 // If the decl has a non-null name, make accessible in the current scope. 9641 if (!D->getName().empty()) 9642 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9643 9644 // Similarly, dive into enums and fish their constants out, making them 9645 // accessible in this scope. 9646 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 9647 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 9648 EE = ED->enumerator_end(); EI != EE; ++EI) 9649 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 9650 } 9651 } 9652 } 9653 9654 // Ensure that the function's exception specification is instantiated. 9655 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9656 ResolveExceptionSpec(D->getLocation(), FPT); 9657 9658 // Checking attributes of current function definition 9659 // dllimport attribute. 9660 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9661 if (DA && (!FD->hasAttr<DLLExportAttr>())) { 9662 // dllimport attribute cannot be directly applied to definition. 9663 // Microsoft accepts dllimport for functions defined within class scope. 9664 if (!DA->isInherited() && 9665 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9666 Diag(FD->getLocation(), 9667 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9668 << DA; 9669 FD->setInvalidDecl(); 9670 return D; 9671 } 9672 9673 // Visual C++ appears to not think this is an issue, so only issue 9674 // a warning when Microsoft extensions are disabled. 9675 if (!LangOpts.MicrosoftExt) { 9676 // If a symbol previously declared dllimport is later defined, the 9677 // attribute is ignored in subsequent references, and a warning is 9678 // emitted. 9679 Diag(FD->getLocation(), 9680 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 9681 << FD << DA; 9682 } 9683 } 9684 // We want to attach documentation to original Decl (which might be 9685 // a function template). 9686 ActOnDocumentableDecl(D); 9687 return D; 9688 } 9689 9690 /// \brief Given the set of return statements within a function body, 9691 /// compute the variables that are subject to the named return value 9692 /// optimization. 9693 /// 9694 /// Each of the variables that is subject to the named return value 9695 /// optimization will be marked as NRVO variables in the AST, and any 9696 /// return statement that has a marked NRVO variable as its NRVO candidate can 9697 /// use the named return value optimization. 9698 /// 9699 /// This function applies a very simplistic algorithm for NRVO: if every return 9700 /// statement in the function has the same NRVO candidate, that candidate is 9701 /// the NRVO variable. 9702 /// 9703 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9704 /// statements and the lifetimes of the NRVO candidates. We should be able to 9705 /// find a maximal set of NRVO variables. 9706 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9707 ReturnStmt **Returns = Scope->Returns.data(); 9708 9709 const VarDecl *NRVOCandidate = 0; 9710 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9711 if (!Returns[I]->getNRVOCandidate()) 9712 return; 9713 9714 if (!NRVOCandidate) 9715 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9716 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9717 return; 9718 } 9719 9720 if (NRVOCandidate) 9721 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9722 } 9723 9724 bool Sema::canSkipFunctionBody(Decl *D) { 9725 // We cannot skip the body of a function (or function template) which is 9726 // constexpr, since we may need to evaluate its body in order to parse the 9727 // rest of the file. 9728 // We cannot skip the body of a function with an undeduced return type, 9729 // because any callers of that function need to know the type. 9730 if (const FunctionDecl *FD = D->getAsFunction()) 9731 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9732 return false; 9733 return Consumer.shouldSkipFunctionBody(D); 9734 } 9735 9736 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9737 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9738 FD->setHasSkippedBody(); 9739 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9740 MD->setHasSkippedBody(); 9741 return ActOnFinishFunctionBody(Decl, 0); 9742 } 9743 9744 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9745 return ActOnFinishFunctionBody(D, BodyArg, false); 9746 } 9747 9748 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9749 bool IsInstantiation) { 9750 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0; 9751 9752 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9753 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9754 9755 if (FD) { 9756 FD->setBody(Body); 9757 9758 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9759 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 9760 // If the function has a deduced result type but contains no 'return' 9761 // statements, the result type as written must be exactly 'auto', and 9762 // the deduced result type is 'void'. 9763 if (!FD->getReturnType()->getAs<AutoType>()) { 9764 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9765 << FD->getReturnType(); 9766 FD->setInvalidDecl(); 9767 } else { 9768 // Substitute 'void' for the 'auto' in the type. 9769 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9770 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 9771 Context.adjustDeducedFunctionResultType( 9772 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9773 } 9774 } 9775 9776 // The only way to be included in UndefinedButUsed is if there is an 9777 // ODR use before the definition. Avoid the expensive map lookup if this 9778 // is the first declaration. 9779 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9780 if (!FD->isExternallyVisible()) 9781 UndefinedButUsed.erase(FD); 9782 else if (FD->isInlined() && 9783 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9784 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9785 UndefinedButUsed.erase(FD); 9786 } 9787 9788 // If the function implicitly returns zero (like 'main') or is naked, 9789 // don't complain about missing return statements. 9790 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9791 WP.disableCheckFallThrough(); 9792 9793 // MSVC permits the use of pure specifier (=0) on function definition, 9794 // defined at class scope, warn about this non-standard construct. 9795 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9796 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9797 9798 if (!FD->isInvalidDecl()) { 9799 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9800 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9801 FD->getReturnType(), FD); 9802 9803 // If this is a constructor, we need a vtable. 9804 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9805 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9806 9807 // Try to apply the named return value optimization. We have to check 9808 // if we can do this here because lambdas keep return statements around 9809 // to deduce an implicit return type. 9810 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 9811 !FD->isDependentContext()) 9812 computeNRVO(Body, getCurFunction()); 9813 } 9814 9815 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9816 "Function parsing confused"); 9817 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9818 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9819 MD->setBody(Body); 9820 if (!MD->isInvalidDecl()) { 9821 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9822 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9823 MD->getReturnType(), MD); 9824 9825 if (Body) 9826 computeNRVO(Body, getCurFunction()); 9827 } 9828 if (getCurFunction()->ObjCShouldCallSuper) { 9829 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9830 << MD->getSelector().getAsString(); 9831 getCurFunction()->ObjCShouldCallSuper = false; 9832 } 9833 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 9834 const ObjCMethodDecl *InitMethod = 0; 9835 bool isDesignated = 9836 MD->isDesignatedInitializerForTheInterface(&InitMethod); 9837 assert(isDesignated && InitMethod); 9838 (void)isDesignated; 9839 Diag(MD->getLocation(), 9840 diag::warn_objc_designated_init_missing_super_call); 9841 Diag(InitMethod->getLocation(), 9842 diag::note_objc_designated_init_marked_here); 9843 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 9844 } 9845 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 9846 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 9847 getCurFunction()->ObjCWarnForNoInitDelegation = false; 9848 } 9849 } else { 9850 return 0; 9851 } 9852 9853 assert(!getCurFunction()->ObjCShouldCallSuper && 9854 "This should only be set for ObjC methods, which should have been " 9855 "handled in the block above."); 9856 9857 // Verify and clean out per-function state. 9858 if (Body) { 9859 // C++ constructors that have function-try-blocks can't have return 9860 // statements in the handlers of that block. (C++ [except.handle]p14) 9861 // Verify this. 9862 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 9863 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 9864 9865 // Verify that gotos and switch cases don't jump into scopes illegally. 9866 if (getCurFunction()->NeedsScopeChecking() && 9867 !dcl->isInvalidDecl() && 9868 !hasAnyUnrecoverableErrorsInThisFunction() && 9869 !PP.isCodeCompletionEnabled()) 9870 DiagnoseInvalidJumps(Body); 9871 9872 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 9873 if (!Destructor->getParent()->isDependentType()) 9874 CheckDestructor(Destructor); 9875 9876 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9877 Destructor->getParent()); 9878 } 9879 9880 // If any errors have occurred, clear out any temporaries that may have 9881 // been leftover. This ensures that these temporaries won't be picked up for 9882 // deletion in some later function. 9883 if (PP.getDiagnostics().hasErrorOccurred() || 9884 PP.getDiagnostics().getSuppressAllDiagnostics()) { 9885 DiscardCleanupsInEvaluationContext(); 9886 } 9887 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 9888 !isa<FunctionTemplateDecl>(dcl)) { 9889 // Since the body is valid, issue any analysis-based warnings that are 9890 // enabled. 9891 ActivePolicy = &WP; 9892 } 9893 9894 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 9895 (!CheckConstexprFunctionDecl(FD) || 9896 !CheckConstexprFunctionBody(FD, Body))) 9897 FD->setInvalidDecl(); 9898 9899 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 9900 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 9901 assert(MaybeODRUseExprs.empty() && 9902 "Leftover expressions for odr-use checking"); 9903 } 9904 9905 if (!IsInstantiation) 9906 PopDeclContext(); 9907 9908 PopFunctionScopeInfo(ActivePolicy, dcl); 9909 // If any errors have occurred, clear out any temporaries that may have 9910 // been leftover. This ensures that these temporaries won't be picked up for 9911 // deletion in some later function. 9912 if (getDiagnostics().hasErrorOccurred()) { 9913 DiscardCleanupsInEvaluationContext(); 9914 } 9915 9916 return dcl; 9917 } 9918 9919 9920 /// When we finish delayed parsing of an attribute, we must attach it to the 9921 /// relevant Decl. 9922 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 9923 ParsedAttributes &Attrs) { 9924 // Always attach attributes to the underlying decl. 9925 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9926 D = TD->getTemplatedDecl(); 9927 ProcessDeclAttributeList(S, D, Attrs.getList()); 9928 9929 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 9930 if (Method->isStatic()) 9931 checkThisInStaticMemberFunctionAttributes(Method); 9932 } 9933 9934 9935 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 9936 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 9937 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 9938 IdentifierInfo &II, Scope *S) { 9939 // Before we produce a declaration for an implicitly defined 9940 // function, see whether there was a locally-scoped declaration of 9941 // this name as a function or variable. If so, use that 9942 // (non-visible) declaration, and complain about it. 9943 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 9944 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 9945 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 9946 return ExternCPrev; 9947 } 9948 9949 // Extension in C99. Legal in C90, but warn about it. 9950 unsigned diag_id; 9951 if (II.getName().startswith("__builtin_")) 9952 diag_id = diag::warn_builtin_unknown; 9953 else if (getLangOpts().C99) 9954 diag_id = diag::ext_implicit_function_decl; 9955 else 9956 diag_id = diag::warn_implicit_function_decl; 9957 Diag(Loc, diag_id) << &II; 9958 9959 // Because typo correction is expensive, only do it if the implicit 9960 // function declaration is going to be treated as an error. 9961 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 9962 TypoCorrection Corrected; 9963 DeclFilterCCC<FunctionDecl> Validator; 9964 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 9965 LookupOrdinaryName, S, 0, Validator))) 9966 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 9967 /*ErrorRecovery*/false); 9968 } 9969 9970 // Set a Declarator for the implicit definition: int foo(); 9971 const char *Dummy; 9972 AttributeFactory attrFactory; 9973 DeclSpec DS(attrFactory); 9974 unsigned DiagID; 9975 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 9976 Context.getPrintingPolicy()); 9977 (void)Error; // Silence warning. 9978 assert(!Error && "Error setting up implicit decl!"); 9979 SourceLocation NoLoc; 9980 Declarator D(DS, Declarator::BlockContext); 9981 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 9982 /*IsAmbiguous=*/false, 9983 /*RParenLoc=*/NoLoc, 9984 /*ArgInfo=*/0, 9985 /*NumArgs=*/0, 9986 /*EllipsisLoc=*/NoLoc, 9987 /*RParenLoc=*/NoLoc, 9988 /*TypeQuals=*/0, 9989 /*RefQualifierIsLvalueRef=*/true, 9990 /*RefQualifierLoc=*/NoLoc, 9991 /*ConstQualifierLoc=*/NoLoc, 9992 /*VolatileQualifierLoc=*/NoLoc, 9993 /*MutableLoc=*/NoLoc, 9994 EST_None, 9995 /*ESpecLoc=*/NoLoc, 9996 /*Exceptions=*/0, 9997 /*ExceptionRanges=*/0, 9998 /*NumExceptions=*/0, 9999 /*NoexceptExpr=*/0, 10000 Loc, Loc, D), 10001 DS.getAttributes(), 10002 SourceLocation()); 10003 D.SetIdentifier(&II, Loc); 10004 10005 // Insert this function into translation-unit scope. 10006 10007 DeclContext *PrevDC = CurContext; 10008 CurContext = Context.getTranslationUnitDecl(); 10009 10010 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10011 FD->setImplicit(); 10012 10013 CurContext = PrevDC; 10014 10015 AddKnownFunctionAttributes(FD); 10016 10017 return FD; 10018 } 10019 10020 /// \brief Adds any function attributes that we know a priori based on 10021 /// the declaration of this function. 10022 /// 10023 /// These attributes can apply both to implicitly-declared builtins 10024 /// (like __builtin___printf_chk) or to library-declared functions 10025 /// like NSLog or printf. 10026 /// 10027 /// We need to check for duplicate attributes both here and where user-written 10028 /// attributes are applied to declarations. 10029 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10030 if (FD->isInvalidDecl()) 10031 return; 10032 10033 // If this is a built-in function, map its builtin attributes to 10034 // actual attributes. 10035 if (unsigned BuiltinID = FD->getBuiltinID()) { 10036 // Handle printf-formatting attributes. 10037 unsigned FormatIdx; 10038 bool HasVAListArg; 10039 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10040 if (!FD->hasAttr<FormatAttr>()) { 10041 const char *fmt = "printf"; 10042 unsigned int NumParams = FD->getNumParams(); 10043 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10044 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10045 fmt = "NSString"; 10046 FD->addAttr(FormatAttr::CreateImplicit(Context, 10047 &Context.Idents.get(fmt), 10048 FormatIdx+1, 10049 HasVAListArg ? 0 : FormatIdx+2, 10050 FD->getLocation())); 10051 } 10052 } 10053 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10054 HasVAListArg)) { 10055 if (!FD->hasAttr<FormatAttr>()) 10056 FD->addAttr(FormatAttr::CreateImplicit(Context, 10057 &Context.Idents.get("scanf"), 10058 FormatIdx+1, 10059 HasVAListArg ? 0 : FormatIdx+2, 10060 FD->getLocation())); 10061 } 10062 10063 // Mark const if we don't care about errno and that is the only 10064 // thing preventing the function from being const. This allows 10065 // IRgen to use LLVM intrinsics for such functions. 10066 if (!getLangOpts().MathErrno && 10067 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10068 if (!FD->hasAttr<ConstAttr>()) 10069 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10070 } 10071 10072 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10073 !FD->hasAttr<ReturnsTwiceAttr>()) 10074 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10075 FD->getLocation())); 10076 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10077 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10078 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10079 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10080 } 10081 10082 IdentifierInfo *Name = FD->getIdentifier(); 10083 if (!Name) 10084 return; 10085 if ((!getLangOpts().CPlusPlus && 10086 FD->getDeclContext()->isTranslationUnit()) || 10087 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10088 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10089 LinkageSpecDecl::lang_c)) { 10090 // Okay: this could be a libc/libm/Objective-C function we know 10091 // about. 10092 } else 10093 return; 10094 10095 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10096 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10097 // target-specific builtins, perhaps? 10098 if (!FD->hasAttr<FormatAttr>()) 10099 FD->addAttr(FormatAttr::CreateImplicit(Context, 10100 &Context.Idents.get("printf"), 2, 10101 Name->isStr("vasprintf") ? 0 : 3, 10102 FD->getLocation())); 10103 } 10104 10105 if (Name->isStr("__CFStringMakeConstantString")) { 10106 // We already have a __builtin___CFStringMakeConstantString, 10107 // but builds that use -fno-constant-cfstrings don't go through that. 10108 if (!FD->hasAttr<FormatArgAttr>()) 10109 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10110 FD->getLocation())); 10111 } 10112 } 10113 10114 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10115 TypeSourceInfo *TInfo) { 10116 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10117 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10118 10119 if (!TInfo) { 10120 assert(D.isInvalidType() && "no declarator info for valid type"); 10121 TInfo = Context.getTrivialTypeSourceInfo(T); 10122 } 10123 10124 // Scope manipulation handled by caller. 10125 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10126 D.getLocStart(), 10127 D.getIdentifierLoc(), 10128 D.getIdentifier(), 10129 TInfo); 10130 10131 // Bail out immediately if we have an invalid declaration. 10132 if (D.isInvalidType()) { 10133 NewTD->setInvalidDecl(); 10134 return NewTD; 10135 } 10136 10137 if (D.getDeclSpec().isModulePrivateSpecified()) { 10138 if (CurContext->isFunctionOrMethod()) 10139 Diag(NewTD->getLocation(), diag::err_module_private_local) 10140 << 2 << NewTD->getDeclName() 10141 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10142 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10143 else 10144 NewTD->setModulePrivate(); 10145 } 10146 10147 // C++ [dcl.typedef]p8: 10148 // If the typedef declaration defines an unnamed class (or 10149 // enum), the first typedef-name declared by the declaration 10150 // to be that class type (or enum type) is used to denote the 10151 // class type (or enum type) for linkage purposes only. 10152 // We need to check whether the type was declared in the declaration. 10153 switch (D.getDeclSpec().getTypeSpecType()) { 10154 case TST_enum: 10155 case TST_struct: 10156 case TST_interface: 10157 case TST_union: 10158 case TST_class: { 10159 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10160 10161 // Do nothing if the tag is not anonymous or already has an 10162 // associated typedef (from an earlier typedef in this decl group). 10163 if (tagFromDeclSpec->getIdentifier()) break; 10164 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10165 10166 // A well-formed anonymous tag must always be a TUK_Definition. 10167 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10168 10169 // The type must match the tag exactly; no qualifiers allowed. 10170 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10171 break; 10172 10173 // If we've already computed linkage for the anonymous tag, then 10174 // adding a typedef name for the anonymous decl can change that 10175 // linkage, which might be a serious problem. Diagnose this as 10176 // unsupported and ignore the typedef name. TODO: we should 10177 // pursue this as a language defect and establish a formal rule 10178 // for how to handle it. 10179 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10180 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10181 10182 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10183 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(), 10184 getLangOpts()); 10185 10186 llvm::SmallString<40> textToInsert; 10187 textToInsert += ' '; 10188 textToInsert += D.getIdentifier()->getName(); 10189 Diag(tagLoc, diag::note_typedef_changes_linkage) 10190 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10191 break; 10192 } 10193 10194 // Otherwise, set this is the anon-decl typedef for the tag. 10195 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10196 break; 10197 } 10198 10199 default: 10200 break; 10201 } 10202 10203 return NewTD; 10204 } 10205 10206 10207 /// \brief Check that this is a valid underlying type for an enum declaration. 10208 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10209 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10210 QualType T = TI->getType(); 10211 10212 if (T->isDependentType()) 10213 return false; 10214 10215 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10216 if (BT->isInteger()) 10217 return false; 10218 10219 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10220 return true; 10221 } 10222 10223 /// Check whether this is a valid redeclaration of a previous enumeration. 10224 /// \return true if the redeclaration was invalid. 10225 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10226 QualType EnumUnderlyingTy, 10227 const EnumDecl *Prev) { 10228 bool IsFixed = !EnumUnderlyingTy.isNull(); 10229 10230 if (IsScoped != Prev->isScoped()) { 10231 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10232 << Prev->isScoped(); 10233 Diag(Prev->getLocation(), diag::note_previous_declaration); 10234 return true; 10235 } 10236 10237 if (IsFixed && Prev->isFixed()) { 10238 if (!EnumUnderlyingTy->isDependentType() && 10239 !Prev->getIntegerType()->isDependentType() && 10240 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10241 Prev->getIntegerType())) { 10242 // TODO: Highlight the underlying type of the redeclaration. 10243 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10244 << EnumUnderlyingTy << Prev->getIntegerType(); 10245 Diag(Prev->getLocation(), diag::note_previous_declaration) 10246 << Prev->getIntegerTypeRange(); 10247 return true; 10248 } 10249 } else if (IsFixed != Prev->isFixed()) { 10250 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10251 << Prev->isFixed(); 10252 Diag(Prev->getLocation(), diag::note_previous_declaration); 10253 return true; 10254 } 10255 10256 return false; 10257 } 10258 10259 /// \brief Get diagnostic %select index for tag kind for 10260 /// redeclaration diagnostic message. 10261 /// WARNING: Indexes apply to particular diagnostics only! 10262 /// 10263 /// \returns diagnostic %select index. 10264 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10265 switch (Tag) { 10266 case TTK_Struct: return 0; 10267 case TTK_Interface: return 1; 10268 case TTK_Class: return 2; 10269 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10270 } 10271 } 10272 10273 /// \brief Determine if tag kind is a class-key compatible with 10274 /// class for redeclaration (class, struct, or __interface). 10275 /// 10276 /// \returns true iff the tag kind is compatible. 10277 static bool isClassCompatTagKind(TagTypeKind Tag) 10278 { 10279 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10280 } 10281 10282 /// \brief Determine whether a tag with a given kind is acceptable 10283 /// as a redeclaration of the given tag declaration. 10284 /// 10285 /// \returns true if the new tag kind is acceptable, false otherwise. 10286 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10287 TagTypeKind NewTag, bool isDefinition, 10288 SourceLocation NewTagLoc, 10289 const IdentifierInfo &Name) { 10290 // C++ [dcl.type.elab]p3: 10291 // The class-key or enum keyword present in the 10292 // elaborated-type-specifier shall agree in kind with the 10293 // declaration to which the name in the elaborated-type-specifier 10294 // refers. This rule also applies to the form of 10295 // elaborated-type-specifier that declares a class-name or 10296 // friend class since it can be construed as referring to the 10297 // definition of the class. Thus, in any 10298 // elaborated-type-specifier, the enum keyword shall be used to 10299 // refer to an enumeration (7.2), the union class-key shall be 10300 // used to refer to a union (clause 9), and either the class or 10301 // struct class-key shall be used to refer to a class (clause 9) 10302 // declared using the class or struct class-key. 10303 TagTypeKind OldTag = Previous->getTagKind(); 10304 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10305 if (OldTag == NewTag) 10306 return true; 10307 10308 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10309 // Warn about the struct/class tag mismatch. 10310 bool isTemplate = false; 10311 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10312 isTemplate = Record->getDescribedClassTemplate(); 10313 10314 if (!ActiveTemplateInstantiations.empty()) { 10315 // In a template instantiation, do not offer fix-its for tag mismatches 10316 // since they usually mess up the template instead of fixing the problem. 10317 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10318 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10319 << getRedeclDiagFromTagKind(OldTag); 10320 return true; 10321 } 10322 10323 if (isDefinition) { 10324 // On definitions, check previous tags and issue a fix-it for each 10325 // one that doesn't match the current tag. 10326 if (Previous->getDefinition()) { 10327 // Don't suggest fix-its for redefinitions. 10328 return true; 10329 } 10330 10331 bool previousMismatch = false; 10332 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 10333 E(Previous->redecls_end()); I != E; ++I) { 10334 if (I->getTagKind() != NewTag) { 10335 if (!previousMismatch) { 10336 previousMismatch = true; 10337 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10338 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10339 << getRedeclDiagFromTagKind(I->getTagKind()); 10340 } 10341 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10342 << getRedeclDiagFromTagKind(NewTag) 10343 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10344 TypeWithKeyword::getTagTypeKindName(NewTag)); 10345 } 10346 } 10347 return true; 10348 } 10349 10350 // Check for a previous definition. If current tag and definition 10351 // are same type, do nothing. If no definition, but disagree with 10352 // with previous tag type, give a warning, but no fix-it. 10353 const TagDecl *Redecl = Previous->getDefinition() ? 10354 Previous->getDefinition() : Previous; 10355 if (Redecl->getTagKind() == NewTag) { 10356 return true; 10357 } 10358 10359 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10360 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10361 << getRedeclDiagFromTagKind(OldTag); 10362 Diag(Redecl->getLocation(), diag::note_previous_use); 10363 10364 // If there is a previous definition, suggest a fix-it. 10365 if (Previous->getDefinition()) { 10366 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10367 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10368 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10369 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10370 } 10371 10372 return true; 10373 } 10374 return false; 10375 } 10376 10377 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10378 /// former case, Name will be non-null. In the later case, Name will be null. 10379 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10380 /// reference/declaration/definition of a tag. 10381 /// 10382 /// IsTypeSpecifier is true if this is a type-specifier (or 10383 /// trailing-type-specifier) other than one in an alias-declaration. 10384 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10385 SourceLocation KWLoc, CXXScopeSpec &SS, 10386 IdentifierInfo *Name, SourceLocation NameLoc, 10387 AttributeList *Attr, AccessSpecifier AS, 10388 SourceLocation ModulePrivateLoc, 10389 MultiTemplateParamsArg TemplateParameterLists, 10390 bool &OwnedDecl, bool &IsDependent, 10391 SourceLocation ScopedEnumKWLoc, 10392 bool ScopedEnumUsesClassTag, 10393 TypeResult UnderlyingType, 10394 bool IsTypeSpecifier) { 10395 // If this is not a definition, it must have a name. 10396 IdentifierInfo *OrigName = Name; 10397 assert((Name != 0 || TUK == TUK_Definition) && 10398 "Nameless record must be a definition!"); 10399 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10400 10401 OwnedDecl = false; 10402 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10403 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10404 10405 // FIXME: Check explicit specializations more carefully. 10406 bool isExplicitSpecialization = false; 10407 bool Invalid = false; 10408 10409 // We only need to do this matching if we have template parameters 10410 // or a scope specifier, which also conveniently avoids this work 10411 // for non-C++ cases. 10412 if (TemplateParameterLists.size() > 0 || 10413 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10414 if (TemplateParameterList *TemplateParams = 10415 MatchTemplateParametersToScopeSpecifier( 10416 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10417 isExplicitSpecialization, Invalid)) { 10418 if (Kind == TTK_Enum) { 10419 Diag(KWLoc, diag::err_enum_template); 10420 return 0; 10421 } 10422 10423 if (TemplateParams->size() > 0) { 10424 // This is a declaration or definition of a class template (which may 10425 // be a member of another template). 10426 10427 if (Invalid) 10428 return 0; 10429 10430 OwnedDecl = false; 10431 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10432 SS, Name, NameLoc, Attr, 10433 TemplateParams, AS, 10434 ModulePrivateLoc, 10435 TemplateParameterLists.size()-1, 10436 TemplateParameterLists.data()); 10437 return Result.get(); 10438 } else { 10439 // The "template<>" header is extraneous. 10440 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10441 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10442 isExplicitSpecialization = true; 10443 } 10444 } 10445 } 10446 10447 // Figure out the underlying type if this a enum declaration. We need to do 10448 // this early, because it's needed to detect if this is an incompatible 10449 // redeclaration. 10450 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10451 10452 if (Kind == TTK_Enum) { 10453 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10454 // No underlying type explicitly specified, or we failed to parse the 10455 // type, default to int. 10456 EnumUnderlying = Context.IntTy.getTypePtr(); 10457 else if (UnderlyingType.get()) { 10458 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10459 // integral type; any cv-qualification is ignored. 10460 TypeSourceInfo *TI = 0; 10461 GetTypeFromParser(UnderlyingType.get(), &TI); 10462 EnumUnderlying = TI; 10463 10464 if (CheckEnumUnderlyingType(TI)) 10465 // Recover by falling back to int. 10466 EnumUnderlying = Context.IntTy.getTypePtr(); 10467 10468 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10469 UPPC_FixedUnderlyingType)) 10470 EnumUnderlying = Context.IntTy.getTypePtr(); 10471 10472 } else if (getLangOpts().MSVCCompat) 10473 // Microsoft enums are always of int type. 10474 EnumUnderlying = Context.IntTy.getTypePtr(); 10475 } 10476 10477 DeclContext *SearchDC = CurContext; 10478 DeclContext *DC = CurContext; 10479 bool isStdBadAlloc = false; 10480 10481 RedeclarationKind Redecl = ForRedeclaration; 10482 if (TUK == TUK_Friend || TUK == TUK_Reference) 10483 Redecl = NotForRedeclaration; 10484 10485 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10486 bool FriendSawTagOutsideEnclosingNamespace = false; 10487 if (Name && SS.isNotEmpty()) { 10488 // We have a nested-name tag ('struct foo::bar'). 10489 10490 // Check for invalid 'foo::'. 10491 if (SS.isInvalid()) { 10492 Name = 0; 10493 goto CreateNewDecl; 10494 } 10495 10496 // If this is a friend or a reference to a class in a dependent 10497 // context, don't try to make a decl for it. 10498 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10499 DC = computeDeclContext(SS, false); 10500 if (!DC) { 10501 IsDependent = true; 10502 return 0; 10503 } 10504 } else { 10505 DC = computeDeclContext(SS, true); 10506 if (!DC) { 10507 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10508 << SS.getRange(); 10509 return 0; 10510 } 10511 } 10512 10513 if (RequireCompleteDeclContext(SS, DC)) 10514 return 0; 10515 10516 SearchDC = DC; 10517 // Look-up name inside 'foo::'. 10518 LookupQualifiedName(Previous, DC); 10519 10520 if (Previous.isAmbiguous()) 10521 return 0; 10522 10523 if (Previous.empty()) { 10524 // Name lookup did not find anything. However, if the 10525 // nested-name-specifier refers to the current instantiation, 10526 // and that current instantiation has any dependent base 10527 // classes, we might find something at instantiation time: treat 10528 // this as a dependent elaborated-type-specifier. 10529 // But this only makes any sense for reference-like lookups. 10530 if (Previous.wasNotFoundInCurrentInstantiation() && 10531 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10532 IsDependent = true; 10533 return 0; 10534 } 10535 10536 // A tag 'foo::bar' must already exist. 10537 Diag(NameLoc, diag::err_not_tag_in_scope) 10538 << Kind << Name << DC << SS.getRange(); 10539 Name = 0; 10540 Invalid = true; 10541 goto CreateNewDecl; 10542 } 10543 } else if (Name) { 10544 // If this is a named struct, check to see if there was a previous forward 10545 // declaration or definition. 10546 // FIXME: We're looking into outer scopes here, even when we 10547 // shouldn't be. Doing so can result in ambiguities that we 10548 // shouldn't be diagnosing. 10549 LookupName(Previous, S); 10550 10551 // When declaring or defining a tag, ignore ambiguities introduced 10552 // by types using'ed into this scope. 10553 if (Previous.isAmbiguous() && 10554 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10555 LookupResult::Filter F = Previous.makeFilter(); 10556 while (F.hasNext()) { 10557 NamedDecl *ND = F.next(); 10558 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10559 F.erase(); 10560 } 10561 F.done(); 10562 } 10563 10564 // C++11 [namespace.memdef]p3: 10565 // If the name in a friend declaration is neither qualified nor 10566 // a template-id and the declaration is a function or an 10567 // elaborated-type-specifier, the lookup to determine whether 10568 // the entity has been previously declared shall not consider 10569 // any scopes outside the innermost enclosing namespace. 10570 // 10571 // Does it matter that this should be by scope instead of by 10572 // semantic context? 10573 if (!Previous.empty() && TUK == TUK_Friend) { 10574 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10575 LookupResult::Filter F = Previous.makeFilter(); 10576 while (F.hasNext()) { 10577 NamedDecl *ND = F.next(); 10578 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10579 if (DC->isFileContext() && 10580 !EnclosingNS->Encloses(ND->getDeclContext())) { 10581 F.erase(); 10582 FriendSawTagOutsideEnclosingNamespace = true; 10583 } 10584 } 10585 F.done(); 10586 } 10587 10588 // Note: there used to be some attempt at recovery here. 10589 if (Previous.isAmbiguous()) 10590 return 0; 10591 10592 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10593 // FIXME: This makes sure that we ignore the contexts associated 10594 // with C structs, unions, and enums when looking for a matching 10595 // tag declaration or definition. See the similar lookup tweak 10596 // in Sema::LookupName; is there a better way to deal with this? 10597 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10598 SearchDC = SearchDC->getParent(); 10599 } 10600 } else if (S->isFunctionPrototypeScope()) { 10601 // If this is an enum declaration in function prototype scope, set its 10602 // initial context to the translation unit. 10603 // FIXME: [citation needed] 10604 SearchDC = Context.getTranslationUnitDecl(); 10605 } 10606 10607 if (Previous.isSingleResult() && 10608 Previous.getFoundDecl()->isTemplateParameter()) { 10609 // Maybe we will complain about the shadowed template parameter. 10610 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10611 // Just pretend that we didn't see the previous declaration. 10612 Previous.clear(); 10613 } 10614 10615 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10616 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10617 // This is a declaration of or a reference to "std::bad_alloc". 10618 isStdBadAlloc = true; 10619 10620 if (Previous.empty() && StdBadAlloc) { 10621 // std::bad_alloc has been implicitly declared (but made invisible to 10622 // name lookup). Fill in this implicit declaration as the previous 10623 // declaration, so that the declarations get chained appropriately. 10624 Previous.addDecl(getStdBadAlloc()); 10625 } 10626 } 10627 10628 // If we didn't find a previous declaration, and this is a reference 10629 // (or friend reference), move to the correct scope. In C++, we 10630 // also need to do a redeclaration lookup there, just in case 10631 // there's a shadow friend decl. 10632 if (Name && Previous.empty() && 10633 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10634 if (Invalid) goto CreateNewDecl; 10635 assert(SS.isEmpty()); 10636 10637 if (TUK == TUK_Reference) { 10638 // C++ [basic.scope.pdecl]p5: 10639 // -- for an elaborated-type-specifier of the form 10640 // 10641 // class-key identifier 10642 // 10643 // if the elaborated-type-specifier is used in the 10644 // decl-specifier-seq or parameter-declaration-clause of a 10645 // function defined in namespace scope, the identifier is 10646 // declared as a class-name in the namespace that contains 10647 // the declaration; otherwise, except as a friend 10648 // declaration, the identifier is declared in the smallest 10649 // non-class, non-function-prototype scope that contains the 10650 // declaration. 10651 // 10652 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10653 // C structs and unions. 10654 // 10655 // It is an error in C++ to declare (rather than define) an enum 10656 // type, including via an elaborated type specifier. We'll 10657 // diagnose that later; for now, declare the enum in the same 10658 // scope as we would have picked for any other tag type. 10659 // 10660 // GNU C also supports this behavior as part of its incomplete 10661 // enum types extension, while GNU C++ does not. 10662 // 10663 // Find the context where we'll be declaring the tag. 10664 // FIXME: We would like to maintain the current DeclContext as the 10665 // lexical context, 10666 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10667 SearchDC = SearchDC->getParent(); 10668 10669 // Find the scope where we'll be declaring the tag. 10670 while (S->isClassScope() || 10671 (getLangOpts().CPlusPlus && 10672 S->isFunctionPrototypeScope()) || 10673 ((S->getFlags() & Scope::DeclScope) == 0) || 10674 (S->getEntity() && S->getEntity()->isTransparentContext())) 10675 S = S->getParent(); 10676 } else { 10677 assert(TUK == TUK_Friend); 10678 // C++ [namespace.memdef]p3: 10679 // If a friend declaration in a non-local class first declares a 10680 // class or function, the friend class or function is a member of 10681 // the innermost enclosing namespace. 10682 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10683 } 10684 10685 // In C++, we need to do a redeclaration lookup to properly 10686 // diagnose some problems. 10687 if (getLangOpts().CPlusPlus) { 10688 Previous.setRedeclarationKind(ForRedeclaration); 10689 LookupQualifiedName(Previous, SearchDC); 10690 } 10691 } 10692 10693 if (!Previous.empty()) { 10694 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10695 NamedDecl *DirectPrevDecl = 10696 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10697 10698 // It's okay to have a tag decl in the same scope as a typedef 10699 // which hides a tag decl in the same scope. Finding this 10700 // insanity with a redeclaration lookup can only actually happen 10701 // in C++. 10702 // 10703 // This is also okay for elaborated-type-specifiers, which is 10704 // technically forbidden by the current standard but which is 10705 // okay according to the likely resolution of an open issue; 10706 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10707 if (getLangOpts().CPlusPlus) { 10708 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10709 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10710 TagDecl *Tag = TT->getDecl(); 10711 if (Tag->getDeclName() == Name && 10712 Tag->getDeclContext()->getRedeclContext() 10713 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10714 PrevDecl = Tag; 10715 Previous.clear(); 10716 Previous.addDecl(Tag); 10717 Previous.resolveKind(); 10718 } 10719 } 10720 } 10721 } 10722 10723 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10724 // If this is a use of a previous tag, or if the tag is already declared 10725 // in the same scope (so that the definition/declaration completes or 10726 // rementions the tag), reuse the decl. 10727 if (TUK == TUK_Reference || TUK == TUK_Friend || 10728 isDeclInScope(DirectPrevDecl, SearchDC, S, 10729 SS.isNotEmpty() || isExplicitSpecialization)) { 10730 // Make sure that this wasn't declared as an enum and now used as a 10731 // struct or something similar. 10732 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10733 TUK == TUK_Definition, KWLoc, 10734 *Name)) { 10735 bool SafeToContinue 10736 = (PrevTagDecl->getTagKind() != TTK_Enum && 10737 Kind != TTK_Enum); 10738 if (SafeToContinue) 10739 Diag(KWLoc, diag::err_use_with_wrong_tag) 10740 << Name 10741 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10742 PrevTagDecl->getKindName()); 10743 else 10744 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10745 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10746 10747 if (SafeToContinue) 10748 Kind = PrevTagDecl->getTagKind(); 10749 else { 10750 // Recover by making this an anonymous redefinition. 10751 Name = 0; 10752 Previous.clear(); 10753 Invalid = true; 10754 } 10755 } 10756 10757 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10758 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10759 10760 // If this is an elaborated-type-specifier for a scoped enumeration, 10761 // the 'class' keyword is not necessary and not permitted. 10762 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10763 if (ScopedEnum) 10764 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10765 << PrevEnum->isScoped() 10766 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10767 return PrevTagDecl; 10768 } 10769 10770 QualType EnumUnderlyingTy; 10771 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10772 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 10773 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10774 EnumUnderlyingTy = QualType(T, 0); 10775 10776 // All conflicts with previous declarations are recovered by 10777 // returning the previous declaration, unless this is a definition, 10778 // in which case we want the caller to bail out. 10779 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10780 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10781 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10782 } 10783 10784 // C++11 [class.mem]p1: 10785 // A member shall not be declared twice in the member-specification, 10786 // except that a nested class or member class template can be declared 10787 // and then later defined. 10788 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10789 S->isDeclScope(PrevDecl)) { 10790 Diag(NameLoc, diag::ext_member_redeclared); 10791 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10792 } 10793 10794 if (!Invalid) { 10795 // If this is a use, just return the declaration we found. 10796 10797 // FIXME: In the future, return a variant or some other clue 10798 // for the consumer of this Decl to know it doesn't own it. 10799 // For our current ASTs this shouldn't be a problem, but will 10800 // need to be changed with DeclGroups. 10801 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10802 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10803 return PrevTagDecl; 10804 10805 // Diagnose attempts to redefine a tag. 10806 if (TUK == TUK_Definition) { 10807 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10808 // If we're defining a specialization and the previous definition 10809 // is from an implicit instantiation, don't emit an error 10810 // here; we'll catch this in the general case below. 10811 bool IsExplicitSpecializationAfterInstantiation = false; 10812 if (isExplicitSpecialization) { 10813 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10814 IsExplicitSpecializationAfterInstantiation = 10815 RD->getTemplateSpecializationKind() != 10816 TSK_ExplicitSpecialization; 10817 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10818 IsExplicitSpecializationAfterInstantiation = 10819 ED->getTemplateSpecializationKind() != 10820 TSK_ExplicitSpecialization; 10821 } 10822 10823 if (!IsExplicitSpecializationAfterInstantiation) { 10824 // A redeclaration in function prototype scope in C isn't 10825 // visible elsewhere, so merely issue a warning. 10826 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10827 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10828 else 10829 Diag(NameLoc, diag::err_redefinition) << Name; 10830 Diag(Def->getLocation(), diag::note_previous_definition); 10831 // If this is a redefinition, recover by making this 10832 // struct be anonymous, which will make any later 10833 // references get the previous definition. 10834 Name = 0; 10835 Previous.clear(); 10836 Invalid = true; 10837 } 10838 } else { 10839 // If the type is currently being defined, complain 10840 // about a nested redefinition. 10841 const TagType *Tag 10842 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10843 if (Tag->isBeingDefined()) { 10844 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10845 Diag(PrevTagDecl->getLocation(), 10846 diag::note_previous_definition); 10847 Name = 0; 10848 Previous.clear(); 10849 Invalid = true; 10850 } 10851 } 10852 10853 // Okay, this is definition of a previously declared or referenced 10854 // tag PrevDecl. We're going to create a new Decl for it. 10855 } 10856 } 10857 // If we get here we have (another) forward declaration or we 10858 // have a definition. Just create a new decl. 10859 10860 } else { 10861 // If we get here, this is a definition of a new tag type in a nested 10862 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 10863 // new decl/type. We set PrevDecl to NULL so that the entities 10864 // have distinct types. 10865 Previous.clear(); 10866 } 10867 // If we get here, we're going to create a new Decl. If PrevDecl 10868 // is non-NULL, it's a definition of the tag declared by 10869 // PrevDecl. If it's NULL, we have a new definition. 10870 10871 10872 // Otherwise, PrevDecl is not a tag, but was found with tag 10873 // lookup. This is only actually possible in C++, where a few 10874 // things like templates still live in the tag namespace. 10875 } else { 10876 // Use a better diagnostic if an elaborated-type-specifier 10877 // found the wrong kind of type on the first 10878 // (non-redeclaration) lookup. 10879 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 10880 !Previous.isForRedeclaration()) { 10881 unsigned Kind = 0; 10882 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10883 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10884 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10885 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 10886 Diag(PrevDecl->getLocation(), diag::note_declared_at); 10887 Invalid = true; 10888 10889 // Otherwise, only diagnose if the declaration is in scope. 10890 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 10891 SS.isNotEmpty() || isExplicitSpecialization)) { 10892 // do nothing 10893 10894 // Diagnose implicit declarations introduced by elaborated types. 10895 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 10896 unsigned Kind = 0; 10897 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10898 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10899 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10900 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 10901 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10902 Invalid = true; 10903 10904 // Otherwise it's a declaration. Call out a particularly common 10905 // case here. 10906 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10907 unsigned Kind = 0; 10908 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 10909 Diag(NameLoc, diag::err_tag_definition_of_typedef) 10910 << Name << Kind << TND->getUnderlyingType(); 10911 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10912 Invalid = true; 10913 10914 // Otherwise, diagnose. 10915 } else { 10916 // The tag name clashes with something else in the target scope, 10917 // issue an error and recover by making this tag be anonymous. 10918 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 10919 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10920 Name = 0; 10921 Invalid = true; 10922 } 10923 10924 // The existing declaration isn't relevant to us; we're in a 10925 // new scope, so clear out the previous declaration. 10926 Previous.clear(); 10927 } 10928 } 10929 10930 CreateNewDecl: 10931 10932 TagDecl *PrevDecl = 0; 10933 if (Previous.isSingleResult()) 10934 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 10935 10936 // If there is an identifier, use the location of the identifier as the 10937 // location of the decl, otherwise use the location of the struct/union 10938 // keyword. 10939 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 10940 10941 // Otherwise, create a new declaration. If there is a previous 10942 // declaration of the same entity, the two will be linked via 10943 // PrevDecl. 10944 TagDecl *New; 10945 10946 bool IsForwardReference = false; 10947 if (Kind == TTK_Enum) { 10948 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10949 // enum X { A, B, C } D; D should chain to X. 10950 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 10951 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 10952 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 10953 // If this is an undefined enum, warn. 10954 if (TUK != TUK_Definition && !Invalid) { 10955 TagDecl *Def; 10956 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 10957 cast<EnumDecl>(New)->isFixed()) { 10958 // C++0x: 7.2p2: opaque-enum-declaration. 10959 // Conflicts are diagnosed above. Do nothing. 10960 } 10961 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 10962 Diag(Loc, diag::ext_forward_ref_enum_def) 10963 << New; 10964 Diag(Def->getLocation(), diag::note_previous_definition); 10965 } else { 10966 unsigned DiagID = diag::ext_forward_ref_enum; 10967 if (getLangOpts().MSVCCompat) 10968 DiagID = diag::ext_ms_forward_ref_enum; 10969 else if (getLangOpts().CPlusPlus) 10970 DiagID = diag::err_forward_ref_enum; 10971 Diag(Loc, DiagID); 10972 10973 // If this is a forward-declared reference to an enumeration, make a 10974 // note of it; we won't actually be introducing the declaration into 10975 // the declaration context. 10976 if (TUK == TUK_Reference) 10977 IsForwardReference = true; 10978 } 10979 } 10980 10981 if (EnumUnderlying) { 10982 EnumDecl *ED = cast<EnumDecl>(New); 10983 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10984 ED->setIntegerTypeSourceInfo(TI); 10985 else 10986 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 10987 ED->setPromotionType(ED->getIntegerType()); 10988 } 10989 10990 } else { 10991 // struct/union/class 10992 10993 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10994 // struct X { int A; } D; D should chain to X. 10995 if (getLangOpts().CPlusPlus) { 10996 // FIXME: Look for a way to use RecordDecl for simple structs. 10997 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10998 cast_or_null<CXXRecordDecl>(PrevDecl)); 10999 11000 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11001 StdBadAlloc = cast<CXXRecordDecl>(New); 11002 } else 11003 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11004 cast_or_null<RecordDecl>(PrevDecl)); 11005 } 11006 11007 // C++11 [dcl.type]p3: 11008 // A type-specifier-seq shall not define a class or enumeration [...]. 11009 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11010 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11011 << Context.getTagDeclType(New); 11012 Invalid = true; 11013 } 11014 11015 // Maybe add qualifier info. 11016 if (SS.isNotEmpty()) { 11017 if (SS.isSet()) { 11018 // If this is either a declaration or a definition, check the 11019 // nested-name-specifier against the current context. We don't do this 11020 // for explicit specializations, because they have similar checking 11021 // (with more specific diagnostics) in the call to 11022 // CheckMemberSpecialization, below. 11023 if (!isExplicitSpecialization && 11024 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11025 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11026 Invalid = true; 11027 11028 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11029 if (TemplateParameterLists.size() > 0) { 11030 New->setTemplateParameterListsInfo(Context, 11031 TemplateParameterLists.size(), 11032 TemplateParameterLists.data()); 11033 } 11034 } 11035 else 11036 Invalid = true; 11037 } 11038 11039 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11040 // Add alignment attributes if necessary; these attributes are checked when 11041 // the ASTContext lays out the structure. 11042 // 11043 // It is important for implementing the correct semantics that this 11044 // happen here (in act on tag decl). The #pragma pack stack is 11045 // maintained as a result of parser callbacks which can occur at 11046 // many points during the parsing of a struct declaration (because 11047 // the #pragma tokens are effectively skipped over during the 11048 // parsing of the struct). 11049 if (TUK == TUK_Definition) { 11050 AddAlignmentAttributesForRecord(RD); 11051 AddMsStructLayoutForRecord(RD); 11052 } 11053 } 11054 11055 if (ModulePrivateLoc.isValid()) { 11056 if (isExplicitSpecialization) 11057 Diag(New->getLocation(), diag::err_module_private_specialization) 11058 << 2 11059 << FixItHint::CreateRemoval(ModulePrivateLoc); 11060 // __module_private__ does not apply to local classes. However, we only 11061 // diagnose this as an error when the declaration specifiers are 11062 // freestanding. Here, we just ignore the __module_private__. 11063 else if (!SearchDC->isFunctionOrMethod()) 11064 New->setModulePrivate(); 11065 } 11066 11067 // If this is a specialization of a member class (of a class template), 11068 // check the specialization. 11069 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11070 Invalid = true; 11071 11072 if (Invalid) 11073 New->setInvalidDecl(); 11074 11075 if (Attr) 11076 ProcessDeclAttributeList(S, New, Attr); 11077 11078 // If we're declaring or defining a tag in function prototype scope 11079 // in C, note that this type can only be used within the function. 11080 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 11081 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11082 11083 // Set the lexical context. If the tag has a C++ scope specifier, the 11084 // lexical context will be different from the semantic context. 11085 New->setLexicalDeclContext(CurContext); 11086 11087 // Mark this as a friend decl if applicable. 11088 // In Microsoft mode, a friend declaration also acts as a forward 11089 // declaration so we always pass true to setObjectOfFriendDecl to make 11090 // the tag name visible. 11091 if (TUK == TUK_Friend) 11092 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11093 getLangOpts().MicrosoftExt); 11094 11095 // Set the access specifier. 11096 if (!Invalid && SearchDC->isRecord()) 11097 SetMemberAccessSpecifier(New, PrevDecl, AS); 11098 11099 if (TUK == TUK_Definition) 11100 New->startDefinition(); 11101 11102 // If this has an identifier, add it to the scope stack. 11103 if (TUK == TUK_Friend) { 11104 // We might be replacing an existing declaration in the lookup tables; 11105 // if so, borrow its access specifier. 11106 if (PrevDecl) 11107 New->setAccess(PrevDecl->getAccess()); 11108 11109 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11110 DC->makeDeclVisibleInContext(New); 11111 if (Name) // can be null along some error paths 11112 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11113 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11114 } else if (Name) { 11115 S = getNonFieldDeclScope(S); 11116 PushOnScopeChains(New, S, !IsForwardReference); 11117 if (IsForwardReference) 11118 SearchDC->makeDeclVisibleInContext(New); 11119 11120 } else { 11121 CurContext->addDecl(New); 11122 } 11123 11124 // If this is the C FILE type, notify the AST context. 11125 if (IdentifierInfo *II = New->getIdentifier()) 11126 if (!New->isInvalidDecl() && 11127 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11128 II->isStr("FILE")) 11129 Context.setFILEDecl(New); 11130 11131 // If we were in function prototype scope (and not in C++ mode), add this 11132 // tag to the list of decls to inject into the function definition scope. 11133 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 11134 InFunctionDeclarator && Name) 11135 DeclsInPrototypeScope.push_back(New); 11136 11137 if (PrevDecl) 11138 mergeDeclAttributes(New, PrevDecl); 11139 11140 // If there's a #pragma GCC visibility in scope, set the visibility of this 11141 // record. 11142 AddPushedVisibilityAttribute(New); 11143 11144 OwnedDecl = true; 11145 // In C++, don't return an invalid declaration. We can't recover well from 11146 // the cases where we make the type anonymous. 11147 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11148 } 11149 11150 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11151 AdjustDeclIfTemplate(TagD); 11152 TagDecl *Tag = cast<TagDecl>(TagD); 11153 11154 // Enter the tag context. 11155 PushDeclContext(S, Tag); 11156 11157 ActOnDocumentableDecl(TagD); 11158 11159 // If there's a #pragma GCC visibility in scope, set the visibility of this 11160 // record. 11161 AddPushedVisibilityAttribute(Tag); 11162 } 11163 11164 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11165 assert(isa<ObjCContainerDecl>(IDecl) && 11166 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11167 DeclContext *OCD = cast<DeclContext>(IDecl); 11168 assert(getContainingDC(OCD) == CurContext && 11169 "The next DeclContext should be lexically contained in the current one."); 11170 CurContext = OCD; 11171 return IDecl; 11172 } 11173 11174 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11175 SourceLocation FinalLoc, 11176 bool IsFinalSpelledSealed, 11177 SourceLocation LBraceLoc) { 11178 AdjustDeclIfTemplate(TagD); 11179 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11180 11181 FieldCollector->StartClass(); 11182 11183 if (!Record->getIdentifier()) 11184 return; 11185 11186 if (FinalLoc.isValid()) 11187 Record->addAttr(new (Context) 11188 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11189 11190 // C++ [class]p2: 11191 // [...] The class-name is also inserted into the scope of the 11192 // class itself; this is known as the injected-class-name. For 11193 // purposes of access checking, the injected-class-name is treated 11194 // as if it were a public member name. 11195 CXXRecordDecl *InjectedClassName 11196 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11197 Record->getLocStart(), Record->getLocation(), 11198 Record->getIdentifier(), 11199 /*PrevDecl=*/0, 11200 /*DelayTypeCreation=*/true); 11201 Context.getTypeDeclType(InjectedClassName, Record); 11202 InjectedClassName->setImplicit(); 11203 InjectedClassName->setAccess(AS_public); 11204 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11205 InjectedClassName->setDescribedClassTemplate(Template); 11206 PushOnScopeChains(InjectedClassName, S); 11207 assert(InjectedClassName->isInjectedClassName() && 11208 "Broken injected-class-name"); 11209 } 11210 11211 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11212 SourceLocation RBraceLoc) { 11213 AdjustDeclIfTemplate(TagD); 11214 TagDecl *Tag = cast<TagDecl>(TagD); 11215 Tag->setRBraceLoc(RBraceLoc); 11216 11217 // Make sure we "complete" the definition even it is invalid. 11218 if (Tag->isBeingDefined()) { 11219 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11220 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11221 RD->completeDefinition(); 11222 } 11223 11224 if (isa<CXXRecordDecl>(Tag)) 11225 FieldCollector->FinishClass(); 11226 11227 // Exit this scope of this tag's definition. 11228 PopDeclContext(); 11229 11230 if (getCurLexicalContext()->isObjCContainer() && 11231 Tag->getDeclContext()->isFileContext()) 11232 Tag->setTopLevelDeclInObjCContainer(); 11233 11234 // Notify the consumer that we've defined a tag. 11235 if (!Tag->isInvalidDecl()) 11236 Consumer.HandleTagDeclDefinition(Tag); 11237 } 11238 11239 void Sema::ActOnObjCContainerFinishDefinition() { 11240 // Exit this scope of this interface definition. 11241 PopDeclContext(); 11242 } 11243 11244 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11245 assert(DC == CurContext && "Mismatch of container contexts"); 11246 OriginalLexicalContext = DC; 11247 ActOnObjCContainerFinishDefinition(); 11248 } 11249 11250 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11251 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11252 OriginalLexicalContext = 0; 11253 } 11254 11255 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11256 AdjustDeclIfTemplate(TagD); 11257 TagDecl *Tag = cast<TagDecl>(TagD); 11258 Tag->setInvalidDecl(); 11259 11260 // Make sure we "complete" the definition even it is invalid. 11261 if (Tag->isBeingDefined()) { 11262 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11263 RD->completeDefinition(); 11264 } 11265 11266 // We're undoing ActOnTagStartDefinition here, not 11267 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11268 // the FieldCollector. 11269 11270 PopDeclContext(); 11271 } 11272 11273 // Note that FieldName may be null for anonymous bitfields. 11274 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11275 IdentifierInfo *FieldName, 11276 QualType FieldTy, bool IsMsStruct, 11277 Expr *BitWidth, bool *ZeroWidth) { 11278 // Default to true; that shouldn't confuse checks for emptiness 11279 if (ZeroWidth) 11280 *ZeroWidth = true; 11281 11282 // C99 6.7.2.1p4 - verify the field type. 11283 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11284 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11285 // Handle incomplete types with specific error. 11286 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11287 return ExprError(); 11288 if (FieldName) 11289 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11290 << FieldName << FieldTy << BitWidth->getSourceRange(); 11291 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11292 << FieldTy << BitWidth->getSourceRange(); 11293 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11294 UPPC_BitFieldWidth)) 11295 return ExprError(); 11296 11297 // If the bit-width is type- or value-dependent, don't try to check 11298 // it now. 11299 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11300 return Owned(BitWidth); 11301 11302 llvm::APSInt Value; 11303 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11304 if (ICE.isInvalid()) 11305 return ICE; 11306 BitWidth = ICE.take(); 11307 11308 if (Value != 0 && ZeroWidth) 11309 *ZeroWidth = false; 11310 11311 // Zero-width bitfield is ok for anonymous field. 11312 if (Value == 0 && FieldName) 11313 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11314 11315 if (Value.isSigned() && Value.isNegative()) { 11316 if (FieldName) 11317 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11318 << FieldName << Value.toString(10); 11319 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11320 << Value.toString(10); 11321 } 11322 11323 if (!FieldTy->isDependentType()) { 11324 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11325 if (Value.getZExtValue() > TypeSize) { 11326 if (!getLangOpts().CPlusPlus || IsMsStruct || 11327 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11328 if (FieldName) 11329 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11330 << FieldName << (unsigned)Value.getZExtValue() 11331 << (unsigned)TypeSize; 11332 11333 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11334 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11335 } 11336 11337 if (FieldName) 11338 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11339 << FieldName << (unsigned)Value.getZExtValue() 11340 << (unsigned)TypeSize; 11341 else 11342 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11343 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11344 } 11345 } 11346 11347 return Owned(BitWidth); 11348 } 11349 11350 /// ActOnField - Each field of a C struct/union is passed into this in order 11351 /// to create a FieldDecl object for it. 11352 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11353 Declarator &D, Expr *BitfieldWidth) { 11354 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11355 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11356 /*InitStyle=*/ICIS_NoInit, AS_public); 11357 return Res; 11358 } 11359 11360 /// HandleField - Analyze a field of a C struct or a C++ data member. 11361 /// 11362 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11363 SourceLocation DeclStart, 11364 Declarator &D, Expr *BitWidth, 11365 InClassInitStyle InitStyle, 11366 AccessSpecifier AS) { 11367 IdentifierInfo *II = D.getIdentifier(); 11368 SourceLocation Loc = DeclStart; 11369 if (II) Loc = D.getIdentifierLoc(); 11370 11371 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11372 QualType T = TInfo->getType(); 11373 if (getLangOpts().CPlusPlus) { 11374 CheckExtraCXXDefaultArguments(D); 11375 11376 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11377 UPPC_DataMemberType)) { 11378 D.setInvalidType(); 11379 T = Context.IntTy; 11380 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11381 } 11382 } 11383 11384 // TR 18037 does not allow fields to be declared with address spaces. 11385 if (T.getQualifiers().hasAddressSpace()) { 11386 Diag(Loc, diag::err_field_with_address_space); 11387 D.setInvalidType(); 11388 } 11389 11390 // OpenCL 1.2 spec, s6.9 r: 11391 // The event type cannot be used to declare a structure or union field. 11392 if (LangOpts.OpenCL && T->isEventT()) { 11393 Diag(Loc, diag::err_event_t_struct_field); 11394 D.setInvalidType(); 11395 } 11396 11397 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11398 11399 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11400 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11401 diag::err_invalid_thread) 11402 << DeclSpec::getSpecifierName(TSCS); 11403 11404 // Check to see if this name was declared as a member previously 11405 NamedDecl *PrevDecl = 0; 11406 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11407 LookupName(Previous, S); 11408 switch (Previous.getResultKind()) { 11409 case LookupResult::Found: 11410 case LookupResult::FoundUnresolvedValue: 11411 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11412 break; 11413 11414 case LookupResult::FoundOverloaded: 11415 PrevDecl = Previous.getRepresentativeDecl(); 11416 break; 11417 11418 case LookupResult::NotFound: 11419 case LookupResult::NotFoundInCurrentInstantiation: 11420 case LookupResult::Ambiguous: 11421 break; 11422 } 11423 Previous.suppressDiagnostics(); 11424 11425 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11426 // Maybe we will complain about the shadowed template parameter. 11427 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11428 // Just pretend that we didn't see the previous declaration. 11429 PrevDecl = 0; 11430 } 11431 11432 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11433 PrevDecl = 0; 11434 11435 bool Mutable 11436 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11437 SourceLocation TSSL = D.getLocStart(); 11438 FieldDecl *NewFD 11439 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11440 TSSL, AS, PrevDecl, &D); 11441 11442 if (NewFD->isInvalidDecl()) 11443 Record->setInvalidDecl(); 11444 11445 if (D.getDeclSpec().isModulePrivateSpecified()) 11446 NewFD->setModulePrivate(); 11447 11448 if (NewFD->isInvalidDecl() && PrevDecl) { 11449 // Don't introduce NewFD into scope; there's already something 11450 // with the same name in the same scope. 11451 } else if (II) { 11452 PushOnScopeChains(NewFD, S); 11453 } else 11454 Record->addDecl(NewFD); 11455 11456 return NewFD; 11457 } 11458 11459 /// \brief Build a new FieldDecl and check its well-formedness. 11460 /// 11461 /// This routine builds a new FieldDecl given the fields name, type, 11462 /// record, etc. \p PrevDecl should refer to any previous declaration 11463 /// with the same name and in the same scope as the field to be 11464 /// created. 11465 /// 11466 /// \returns a new FieldDecl. 11467 /// 11468 /// \todo The Declarator argument is a hack. It will be removed once 11469 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11470 TypeSourceInfo *TInfo, 11471 RecordDecl *Record, SourceLocation Loc, 11472 bool Mutable, Expr *BitWidth, 11473 InClassInitStyle InitStyle, 11474 SourceLocation TSSL, 11475 AccessSpecifier AS, NamedDecl *PrevDecl, 11476 Declarator *D) { 11477 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11478 bool InvalidDecl = false; 11479 if (D) InvalidDecl = D->isInvalidType(); 11480 11481 // If we receive a broken type, recover by assuming 'int' and 11482 // marking this declaration as invalid. 11483 if (T.isNull()) { 11484 InvalidDecl = true; 11485 T = Context.IntTy; 11486 } 11487 11488 QualType EltTy = Context.getBaseElementType(T); 11489 if (!EltTy->isDependentType()) { 11490 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11491 // Fields of incomplete type force their record to be invalid. 11492 Record->setInvalidDecl(); 11493 InvalidDecl = true; 11494 } else { 11495 NamedDecl *Def; 11496 EltTy->isIncompleteType(&Def); 11497 if (Def && Def->isInvalidDecl()) { 11498 Record->setInvalidDecl(); 11499 InvalidDecl = true; 11500 } 11501 } 11502 } 11503 11504 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11505 if (BitWidth && getLangOpts().OpenCL) { 11506 Diag(Loc, diag::err_opencl_bitfields); 11507 InvalidDecl = true; 11508 } 11509 11510 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11511 // than a variably modified type. 11512 if (!InvalidDecl && T->isVariablyModifiedType()) { 11513 bool SizeIsNegative; 11514 llvm::APSInt Oversized; 11515 11516 TypeSourceInfo *FixedTInfo = 11517 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11518 SizeIsNegative, 11519 Oversized); 11520 if (FixedTInfo) { 11521 Diag(Loc, diag::warn_illegal_constant_array_size); 11522 TInfo = FixedTInfo; 11523 T = FixedTInfo->getType(); 11524 } else { 11525 if (SizeIsNegative) 11526 Diag(Loc, diag::err_typecheck_negative_array_size); 11527 else if (Oversized.getBoolValue()) 11528 Diag(Loc, diag::err_array_too_large) 11529 << Oversized.toString(10); 11530 else 11531 Diag(Loc, diag::err_typecheck_field_variable_size); 11532 InvalidDecl = true; 11533 } 11534 } 11535 11536 // Fields can not have abstract class types 11537 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11538 diag::err_abstract_type_in_decl, 11539 AbstractFieldType)) 11540 InvalidDecl = true; 11541 11542 bool ZeroWidth = false; 11543 // If this is declared as a bit-field, check the bit-field. 11544 if (!InvalidDecl && BitWidth) { 11545 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11546 &ZeroWidth).take(); 11547 if (!BitWidth) { 11548 InvalidDecl = true; 11549 BitWidth = 0; 11550 ZeroWidth = false; 11551 } 11552 } 11553 11554 // Check that 'mutable' is consistent with the type of the declaration. 11555 if (!InvalidDecl && Mutable) { 11556 unsigned DiagID = 0; 11557 if (T->isReferenceType()) 11558 DiagID = diag::err_mutable_reference; 11559 else if (T.isConstQualified()) 11560 DiagID = diag::err_mutable_const; 11561 11562 if (DiagID) { 11563 SourceLocation ErrLoc = Loc; 11564 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11565 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11566 Diag(ErrLoc, DiagID); 11567 Mutable = false; 11568 InvalidDecl = true; 11569 } 11570 } 11571 11572 // C++11 [class.union]p8 (DR1460): 11573 // At most one variant member of a union may have a 11574 // brace-or-equal-initializer. 11575 if (InitStyle != ICIS_NoInit) 11576 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11577 11578 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11579 BitWidth, Mutable, InitStyle); 11580 if (InvalidDecl) 11581 NewFD->setInvalidDecl(); 11582 11583 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11584 Diag(Loc, diag::err_duplicate_member) << II; 11585 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11586 NewFD->setInvalidDecl(); 11587 } 11588 11589 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11590 if (Record->isUnion()) { 11591 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11592 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11593 if (RDecl->getDefinition()) { 11594 // C++ [class.union]p1: An object of a class with a non-trivial 11595 // constructor, a non-trivial copy constructor, a non-trivial 11596 // destructor, or a non-trivial copy assignment operator 11597 // cannot be a member of a union, nor can an array of such 11598 // objects. 11599 if (CheckNontrivialField(NewFD)) 11600 NewFD->setInvalidDecl(); 11601 } 11602 } 11603 11604 // C++ [class.union]p1: If a union contains a member of reference type, 11605 // the program is ill-formed, except when compiling with MSVC extensions 11606 // enabled. 11607 if (EltTy->isReferenceType()) { 11608 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11609 diag::ext_union_member_of_reference_type : 11610 diag::err_union_member_of_reference_type) 11611 << NewFD->getDeclName() << EltTy; 11612 if (!getLangOpts().MicrosoftExt) 11613 NewFD->setInvalidDecl(); 11614 } 11615 } 11616 } 11617 11618 // FIXME: We need to pass in the attributes given an AST 11619 // representation, not a parser representation. 11620 if (D) { 11621 // FIXME: The current scope is almost... but not entirely... correct here. 11622 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11623 11624 if (NewFD->hasAttrs()) 11625 CheckAlignasUnderalignment(NewFD); 11626 } 11627 11628 // In auto-retain/release, infer strong retension for fields of 11629 // retainable type. 11630 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11631 NewFD->setInvalidDecl(); 11632 11633 if (T.isObjCGCWeak()) 11634 Diag(Loc, diag::warn_attribute_weak_on_field); 11635 11636 NewFD->setAccess(AS); 11637 return NewFD; 11638 } 11639 11640 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11641 assert(FD); 11642 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11643 11644 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11645 return false; 11646 11647 QualType EltTy = Context.getBaseElementType(FD->getType()); 11648 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11649 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11650 if (RDecl->getDefinition()) { 11651 // We check for copy constructors before constructors 11652 // because otherwise we'll never get complaints about 11653 // copy constructors. 11654 11655 CXXSpecialMember member = CXXInvalid; 11656 // We're required to check for any non-trivial constructors. Since the 11657 // implicit default constructor is suppressed if there are any 11658 // user-declared constructors, we just need to check that there is a 11659 // trivial default constructor and a trivial copy constructor. (We don't 11660 // worry about move constructors here, since this is a C++98 check.) 11661 if (RDecl->hasNonTrivialCopyConstructor()) 11662 member = CXXCopyConstructor; 11663 else if (!RDecl->hasTrivialDefaultConstructor()) 11664 member = CXXDefaultConstructor; 11665 else if (RDecl->hasNonTrivialCopyAssignment()) 11666 member = CXXCopyAssignment; 11667 else if (RDecl->hasNonTrivialDestructor()) 11668 member = CXXDestructor; 11669 11670 if (member != CXXInvalid) { 11671 if (!getLangOpts().CPlusPlus11 && 11672 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11673 // Objective-C++ ARC: it is an error to have a non-trivial field of 11674 // a union. However, system headers in Objective-C programs 11675 // occasionally have Objective-C lifetime objects within unions, 11676 // and rather than cause the program to fail, we make those 11677 // members unavailable. 11678 SourceLocation Loc = FD->getLocation(); 11679 if (getSourceManager().isInSystemHeader(Loc)) { 11680 if (!FD->hasAttr<UnavailableAttr>()) 11681 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11682 "this system field has retaining ownership", 11683 Loc)); 11684 return false; 11685 } 11686 } 11687 11688 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11689 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11690 diag::err_illegal_union_or_anon_struct_member) 11691 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11692 DiagnoseNontrivial(RDecl, member); 11693 return !getLangOpts().CPlusPlus11; 11694 } 11695 } 11696 } 11697 11698 return false; 11699 } 11700 11701 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11702 /// AST enum value. 11703 static ObjCIvarDecl::AccessControl 11704 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11705 switch (ivarVisibility) { 11706 default: llvm_unreachable("Unknown visitibility kind"); 11707 case tok::objc_private: return ObjCIvarDecl::Private; 11708 case tok::objc_public: return ObjCIvarDecl::Public; 11709 case tok::objc_protected: return ObjCIvarDecl::Protected; 11710 case tok::objc_package: return ObjCIvarDecl::Package; 11711 } 11712 } 11713 11714 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11715 /// in order to create an IvarDecl object for it. 11716 Decl *Sema::ActOnIvar(Scope *S, 11717 SourceLocation DeclStart, 11718 Declarator &D, Expr *BitfieldWidth, 11719 tok::ObjCKeywordKind Visibility) { 11720 11721 IdentifierInfo *II = D.getIdentifier(); 11722 Expr *BitWidth = (Expr*)BitfieldWidth; 11723 SourceLocation Loc = DeclStart; 11724 if (II) Loc = D.getIdentifierLoc(); 11725 11726 // FIXME: Unnamed fields can be handled in various different ways, for 11727 // example, unnamed unions inject all members into the struct namespace! 11728 11729 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11730 QualType T = TInfo->getType(); 11731 11732 if (BitWidth) { 11733 // 6.7.2.1p3, 6.7.2.1p4 11734 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11735 if (!BitWidth) 11736 D.setInvalidType(); 11737 } else { 11738 // Not a bitfield. 11739 11740 // validate II. 11741 11742 } 11743 if (T->isReferenceType()) { 11744 Diag(Loc, diag::err_ivar_reference_type); 11745 D.setInvalidType(); 11746 } 11747 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11748 // than a variably modified type. 11749 else if (T->isVariablyModifiedType()) { 11750 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11751 D.setInvalidType(); 11752 } 11753 11754 // Get the visibility (access control) for this ivar. 11755 ObjCIvarDecl::AccessControl ac = 11756 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11757 : ObjCIvarDecl::None; 11758 // Must set ivar's DeclContext to its enclosing interface. 11759 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11760 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11761 return 0; 11762 ObjCContainerDecl *EnclosingContext; 11763 if (ObjCImplementationDecl *IMPDecl = 11764 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11765 if (LangOpts.ObjCRuntime.isFragile()) { 11766 // Case of ivar declared in an implementation. Context is that of its class. 11767 EnclosingContext = IMPDecl->getClassInterface(); 11768 assert(EnclosingContext && "Implementation has no class interface!"); 11769 } 11770 else 11771 EnclosingContext = EnclosingDecl; 11772 } else { 11773 if (ObjCCategoryDecl *CDecl = 11774 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11775 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11776 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11777 return 0; 11778 } 11779 } 11780 EnclosingContext = EnclosingDecl; 11781 } 11782 11783 // Construct the decl. 11784 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11785 DeclStart, Loc, II, T, 11786 TInfo, ac, (Expr *)BitfieldWidth); 11787 11788 if (II) { 11789 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11790 ForRedeclaration); 11791 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11792 && !isa<TagDecl>(PrevDecl)) { 11793 Diag(Loc, diag::err_duplicate_member) << II; 11794 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11795 NewID->setInvalidDecl(); 11796 } 11797 } 11798 11799 // Process attributes attached to the ivar. 11800 ProcessDeclAttributes(S, NewID, D); 11801 11802 if (D.isInvalidType()) 11803 NewID->setInvalidDecl(); 11804 11805 // In ARC, infer 'retaining' for ivars of retainable type. 11806 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11807 NewID->setInvalidDecl(); 11808 11809 if (D.getDeclSpec().isModulePrivateSpecified()) 11810 NewID->setModulePrivate(); 11811 11812 if (II) { 11813 // FIXME: When interfaces are DeclContexts, we'll need to add 11814 // these to the interface. 11815 S->AddDecl(NewID); 11816 IdResolver.AddDecl(NewID); 11817 } 11818 11819 if (LangOpts.ObjCRuntime.isNonFragile() && 11820 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11821 Diag(Loc, diag::warn_ivars_in_interface); 11822 11823 return NewID; 11824 } 11825 11826 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11827 /// class and class extensions. For every class \@interface and class 11828 /// extension \@interface, if the last ivar is a bitfield of any type, 11829 /// then add an implicit `char :0` ivar to the end of that interface. 11830 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11831 SmallVectorImpl<Decl *> &AllIvarDecls) { 11832 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11833 return; 11834 11835 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11836 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11837 11838 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11839 return; 11840 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11841 if (!ID) { 11842 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11843 if (!CD->IsClassExtension()) 11844 return; 11845 } 11846 // No need to add this to end of @implementation. 11847 else 11848 return; 11849 } 11850 // All conditions are met. Add a new bitfield to the tail end of ivars. 11851 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11852 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11853 11854 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11855 DeclLoc, DeclLoc, 0, 11856 Context.CharTy, 11857 Context.getTrivialTypeSourceInfo(Context.CharTy, 11858 DeclLoc), 11859 ObjCIvarDecl::Private, BW, 11860 true); 11861 AllIvarDecls.push_back(Ivar); 11862 } 11863 11864 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 11865 ArrayRef<Decl *> Fields, SourceLocation LBrac, 11866 SourceLocation RBrac, AttributeList *Attr) { 11867 assert(EnclosingDecl && "missing record or interface decl"); 11868 11869 // If this is an Objective-C @implementation or category and we have 11870 // new fields here we should reset the layout of the interface since 11871 // it will now change. 11872 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 11873 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 11874 switch (DC->getKind()) { 11875 default: break; 11876 case Decl::ObjCCategory: 11877 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 11878 break; 11879 case Decl::ObjCImplementation: 11880 Context. 11881 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 11882 break; 11883 } 11884 } 11885 11886 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 11887 11888 // Start counting up the number of named members; make sure to include 11889 // members of anonymous structs and unions in the total. 11890 unsigned NumNamedMembers = 0; 11891 if (Record) { 11892 for (RecordDecl::decl_iterator i = Record->decls_begin(), 11893 e = Record->decls_end(); i != e; i++) { 11894 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 11895 if (IFD->getDeclName()) 11896 ++NumNamedMembers; 11897 } 11898 } 11899 11900 // Verify that all the fields are okay. 11901 SmallVector<FieldDecl*, 32> RecFields; 11902 11903 bool ARCErrReported = false; 11904 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 11905 i != end; ++i) { 11906 FieldDecl *FD = cast<FieldDecl>(*i); 11907 11908 // Get the type for the field. 11909 const Type *FDTy = FD->getType().getTypePtr(); 11910 11911 if (!FD->isAnonymousStructOrUnion()) { 11912 // Remember all fields written by the user. 11913 RecFields.push_back(FD); 11914 } 11915 11916 // If the field is already invalid for some reason, don't emit more 11917 // diagnostics about it. 11918 if (FD->isInvalidDecl()) { 11919 EnclosingDecl->setInvalidDecl(); 11920 continue; 11921 } 11922 11923 // C99 6.7.2.1p2: 11924 // A structure or union shall not contain a member with 11925 // incomplete or function type (hence, a structure shall not 11926 // contain an instance of itself, but may contain a pointer to 11927 // an instance of itself), except that the last member of a 11928 // structure with more than one named member may have incomplete 11929 // array type; such a structure (and any union containing, 11930 // possibly recursively, a member that is such a structure) 11931 // shall not be a member of a structure or an element of an 11932 // array. 11933 if (FDTy->isFunctionType()) { 11934 // Field declared as a function. 11935 Diag(FD->getLocation(), diag::err_field_declared_as_function) 11936 << FD->getDeclName(); 11937 FD->setInvalidDecl(); 11938 EnclosingDecl->setInvalidDecl(); 11939 continue; 11940 } else if (FDTy->isIncompleteArrayType() && Record && 11941 ((i + 1 == Fields.end() && !Record->isUnion()) || 11942 ((getLangOpts().MicrosoftExt || 11943 getLangOpts().CPlusPlus) && 11944 (i + 1 == Fields.end() || Record->isUnion())))) { 11945 // Flexible array member. 11946 // Microsoft and g++ is more permissive regarding flexible array. 11947 // It will accept flexible array in union and also 11948 // as the sole element of a struct/class. 11949 unsigned DiagID = 0; 11950 if (Record->isUnion()) 11951 DiagID = getLangOpts().MicrosoftExt 11952 ? diag::ext_flexible_array_union_ms 11953 : getLangOpts().CPlusPlus 11954 ? diag::ext_flexible_array_union_gnu 11955 : diag::err_flexible_array_union; 11956 else if (Fields.size() == 1) 11957 DiagID = getLangOpts().MicrosoftExt 11958 ? diag::ext_flexible_array_empty_aggregate_ms 11959 : getLangOpts().CPlusPlus 11960 ? diag::ext_flexible_array_empty_aggregate_gnu 11961 : NumNamedMembers < 1 11962 ? diag::err_flexible_array_empty_aggregate 11963 : 0; 11964 11965 if (DiagID) 11966 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 11967 << Record->getTagKind(); 11968 // While the layout of types that contain virtual bases is not specified 11969 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 11970 // virtual bases after the derived members. This would make a flexible 11971 // array member declared at the end of an object not adjacent to the end 11972 // of the type. 11973 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 11974 if (RD->getNumVBases() != 0) 11975 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 11976 << FD->getDeclName() << Record->getTagKind(); 11977 if (!getLangOpts().C99) 11978 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11979 << FD->getDeclName() << Record->getTagKind(); 11980 11981 // If the element type has a non-trivial destructor, we would not 11982 // implicitly destroy the elements, so disallow it for now. 11983 // 11984 // FIXME: GCC allows this. We should probably either implicitly delete 11985 // the destructor of the containing class, or just allow this. 11986 QualType BaseElem = Context.getBaseElementType(FD->getType()); 11987 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 11988 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 11989 << FD->getDeclName() << FD->getType(); 11990 FD->setInvalidDecl(); 11991 EnclosingDecl->setInvalidDecl(); 11992 continue; 11993 } 11994 // Okay, we have a legal flexible array member at the end of the struct. 11995 if (Record) 11996 Record->setHasFlexibleArrayMember(true); 11997 } else if (!FDTy->isDependentType() && 11998 RequireCompleteType(FD->getLocation(), FD->getType(), 11999 diag::err_field_incomplete)) { 12000 // Incomplete type 12001 FD->setInvalidDecl(); 12002 EnclosingDecl->setInvalidDecl(); 12003 continue; 12004 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12005 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 12006 // If this is a member of a union, then entire union becomes "flexible". 12007 if (Record && Record->isUnion()) { 12008 Record->setHasFlexibleArrayMember(true); 12009 } else { 12010 // If this is a struct/class and this is not the last element, reject 12011 // it. Note that GCC supports variable sized arrays in the middle of 12012 // structures. 12013 if (i + 1 != Fields.end()) 12014 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12015 << FD->getDeclName() << FD->getType(); 12016 else { 12017 // We support flexible arrays at the end of structs in 12018 // other structs as an extension. 12019 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12020 << FD->getDeclName(); 12021 if (Record) 12022 Record->setHasFlexibleArrayMember(true); 12023 } 12024 } 12025 } 12026 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12027 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12028 diag::err_abstract_type_in_decl, 12029 AbstractIvarType)) { 12030 // Ivars can not have abstract class types 12031 FD->setInvalidDecl(); 12032 } 12033 if (Record && FDTTy->getDecl()->hasObjectMember()) 12034 Record->setHasObjectMember(true); 12035 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12036 Record->setHasVolatileMember(true); 12037 } else if (FDTy->isObjCObjectType()) { 12038 /// A field cannot be an Objective-c object 12039 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12040 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12041 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12042 FD->setType(T); 12043 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12044 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12045 // It's an error in ARC if a field has lifetime. 12046 // We don't want to report this in a system header, though, 12047 // so we just make the field unavailable. 12048 // FIXME: that's really not sufficient; we need to make the type 12049 // itself invalid to, say, initialize or copy. 12050 QualType T = FD->getType(); 12051 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12052 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12053 SourceLocation loc = FD->getLocation(); 12054 if (getSourceManager().isInSystemHeader(loc)) { 12055 if (!FD->hasAttr<UnavailableAttr>()) { 12056 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12057 "this system field has retaining ownership", 12058 loc)); 12059 } 12060 } else { 12061 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12062 << T->isBlockPointerType() << Record->getTagKind(); 12063 } 12064 ARCErrReported = true; 12065 } 12066 } else if (getLangOpts().ObjC1 && 12067 getLangOpts().getGC() != LangOptions::NonGC && 12068 Record && !Record->hasObjectMember()) { 12069 if (FD->getType()->isObjCObjectPointerType() || 12070 FD->getType().isObjCGCStrong()) 12071 Record->setHasObjectMember(true); 12072 else if (Context.getAsArrayType(FD->getType())) { 12073 QualType BaseType = Context.getBaseElementType(FD->getType()); 12074 if (BaseType->isRecordType() && 12075 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12076 Record->setHasObjectMember(true); 12077 else if (BaseType->isObjCObjectPointerType() || 12078 BaseType.isObjCGCStrong()) 12079 Record->setHasObjectMember(true); 12080 } 12081 } 12082 if (Record && FD->getType().isVolatileQualified()) 12083 Record->setHasVolatileMember(true); 12084 // Keep track of the number of named members. 12085 if (FD->getIdentifier()) 12086 ++NumNamedMembers; 12087 } 12088 12089 // Okay, we successfully defined 'Record'. 12090 if (Record) { 12091 bool Completed = false; 12092 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12093 if (!CXXRecord->isInvalidDecl()) { 12094 // Set access bits correctly on the directly-declared conversions. 12095 for (CXXRecordDecl::conversion_iterator 12096 I = CXXRecord->conversion_begin(), 12097 E = CXXRecord->conversion_end(); I != E; ++I) 12098 I.setAccess((*I)->getAccess()); 12099 12100 if (!CXXRecord->isDependentType()) { 12101 if (CXXRecord->hasUserDeclaredDestructor()) { 12102 // Adjust user-defined destructor exception spec. 12103 if (getLangOpts().CPlusPlus11) 12104 AdjustDestructorExceptionSpec(CXXRecord, 12105 CXXRecord->getDestructor()); 12106 } 12107 12108 // Add any implicitly-declared members to this class. 12109 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12110 12111 // If we have virtual base classes, we may end up finding multiple 12112 // final overriders for a given virtual function. Check for this 12113 // problem now. 12114 if (CXXRecord->getNumVBases()) { 12115 CXXFinalOverriderMap FinalOverriders; 12116 CXXRecord->getFinalOverriders(FinalOverriders); 12117 12118 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12119 MEnd = FinalOverriders.end(); 12120 M != MEnd; ++M) { 12121 for (OverridingMethods::iterator SO = M->second.begin(), 12122 SOEnd = M->second.end(); 12123 SO != SOEnd; ++SO) { 12124 assert(SO->second.size() > 0 && 12125 "Virtual function without overridding functions?"); 12126 if (SO->second.size() == 1) 12127 continue; 12128 12129 // C++ [class.virtual]p2: 12130 // In a derived class, if a virtual member function of a base 12131 // class subobject has more than one final overrider the 12132 // program is ill-formed. 12133 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12134 << (const NamedDecl *)M->first << Record; 12135 Diag(M->first->getLocation(), 12136 diag::note_overridden_virtual_function); 12137 for (OverridingMethods::overriding_iterator 12138 OM = SO->second.begin(), 12139 OMEnd = SO->second.end(); 12140 OM != OMEnd; ++OM) 12141 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12142 << (const NamedDecl *)M->first << OM->Method->getParent(); 12143 12144 Record->setInvalidDecl(); 12145 } 12146 } 12147 CXXRecord->completeDefinition(&FinalOverriders); 12148 Completed = true; 12149 } 12150 } 12151 } 12152 } 12153 12154 if (!Completed) 12155 Record->completeDefinition(); 12156 12157 if (Record->hasAttrs()) { 12158 CheckAlignasUnderalignment(Record); 12159 12160 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12161 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12162 IA->getRange(), IA->getBestCase(), 12163 IA->getSemanticSpelling()); 12164 } 12165 12166 // Check if the structure/union declaration is a type that can have zero 12167 // size in C. For C this is a language extension, for C++ it may cause 12168 // compatibility problems. 12169 bool CheckForZeroSize; 12170 if (!getLangOpts().CPlusPlus) { 12171 CheckForZeroSize = true; 12172 } else { 12173 // For C++ filter out types that cannot be referenced in C code. 12174 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12175 CheckForZeroSize = 12176 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12177 !CXXRecord->isDependentType() && 12178 CXXRecord->isCLike(); 12179 } 12180 if (CheckForZeroSize) { 12181 bool ZeroSize = true; 12182 bool IsEmpty = true; 12183 unsigned NonBitFields = 0; 12184 for (RecordDecl::field_iterator I = Record->field_begin(), 12185 E = Record->field_end(); 12186 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12187 IsEmpty = false; 12188 if (I->isUnnamedBitfield()) { 12189 if (I->getBitWidthValue(Context) > 0) 12190 ZeroSize = false; 12191 } else { 12192 ++NonBitFields; 12193 QualType FieldType = I->getType(); 12194 if (FieldType->isIncompleteType() || 12195 !Context.getTypeSizeInChars(FieldType).isZero()) 12196 ZeroSize = false; 12197 } 12198 } 12199 12200 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12201 // allowed in C++, but warn if its declaration is inside 12202 // extern "C" block. 12203 if (ZeroSize) { 12204 Diag(RecLoc, getLangOpts().CPlusPlus ? 12205 diag::warn_zero_size_struct_union_in_extern_c : 12206 diag::warn_zero_size_struct_union_compat) 12207 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12208 } 12209 12210 // Structs without named members are extension in C (C99 6.7.2.1p7), 12211 // but are accepted by GCC. 12212 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12213 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12214 diag::ext_no_named_members_in_struct_union) 12215 << Record->isUnion(); 12216 } 12217 } 12218 } else { 12219 ObjCIvarDecl **ClsFields = 12220 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12221 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12222 ID->setEndOfDefinitionLoc(RBrac); 12223 // Add ivar's to class's DeclContext. 12224 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12225 ClsFields[i]->setLexicalDeclContext(ID); 12226 ID->addDecl(ClsFields[i]); 12227 } 12228 // Must enforce the rule that ivars in the base classes may not be 12229 // duplicates. 12230 if (ID->getSuperClass()) 12231 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12232 } else if (ObjCImplementationDecl *IMPDecl = 12233 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12234 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12235 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12236 // Ivar declared in @implementation never belongs to the implementation. 12237 // Only it is in implementation's lexical context. 12238 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12239 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12240 IMPDecl->setIvarLBraceLoc(LBrac); 12241 IMPDecl->setIvarRBraceLoc(RBrac); 12242 } else if (ObjCCategoryDecl *CDecl = 12243 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12244 // case of ivars in class extension; all other cases have been 12245 // reported as errors elsewhere. 12246 // FIXME. Class extension does not have a LocEnd field. 12247 // CDecl->setLocEnd(RBrac); 12248 // Add ivar's to class extension's DeclContext. 12249 // Diagnose redeclaration of private ivars. 12250 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12251 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12252 if (IDecl) { 12253 if (const ObjCIvarDecl *ClsIvar = 12254 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12255 Diag(ClsFields[i]->getLocation(), 12256 diag::err_duplicate_ivar_declaration); 12257 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12258 continue; 12259 } 12260 for (ObjCInterfaceDecl::known_extensions_iterator 12261 Ext = IDecl->known_extensions_begin(), 12262 ExtEnd = IDecl->known_extensions_end(); 12263 Ext != ExtEnd; ++Ext) { 12264 if (const ObjCIvarDecl *ClsExtIvar 12265 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12266 Diag(ClsFields[i]->getLocation(), 12267 diag::err_duplicate_ivar_declaration); 12268 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12269 continue; 12270 } 12271 } 12272 } 12273 ClsFields[i]->setLexicalDeclContext(CDecl); 12274 CDecl->addDecl(ClsFields[i]); 12275 } 12276 CDecl->setIvarLBraceLoc(LBrac); 12277 CDecl->setIvarRBraceLoc(RBrac); 12278 } 12279 } 12280 12281 if (Attr) 12282 ProcessDeclAttributeList(S, Record, Attr); 12283 } 12284 12285 /// \brief Determine whether the given integral value is representable within 12286 /// the given type T. 12287 static bool isRepresentableIntegerValue(ASTContext &Context, 12288 llvm::APSInt &Value, 12289 QualType T) { 12290 assert(T->isIntegralType(Context) && "Integral type required!"); 12291 unsigned BitWidth = Context.getIntWidth(T); 12292 12293 if (Value.isUnsigned() || Value.isNonNegative()) { 12294 if (T->isSignedIntegerOrEnumerationType()) 12295 --BitWidth; 12296 return Value.getActiveBits() <= BitWidth; 12297 } 12298 return Value.getMinSignedBits() <= BitWidth; 12299 } 12300 12301 // \brief Given an integral type, return the next larger integral type 12302 // (or a NULL type of no such type exists). 12303 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12304 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12305 // enum checking below. 12306 assert(T->isIntegralType(Context) && "Integral type required!"); 12307 const unsigned NumTypes = 4; 12308 QualType SignedIntegralTypes[NumTypes] = { 12309 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12310 }; 12311 QualType UnsignedIntegralTypes[NumTypes] = { 12312 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12313 Context.UnsignedLongLongTy 12314 }; 12315 12316 unsigned BitWidth = Context.getTypeSize(T); 12317 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12318 : UnsignedIntegralTypes; 12319 for (unsigned I = 0; I != NumTypes; ++I) 12320 if (Context.getTypeSize(Types[I]) > BitWidth) 12321 return Types[I]; 12322 12323 return QualType(); 12324 } 12325 12326 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12327 EnumConstantDecl *LastEnumConst, 12328 SourceLocation IdLoc, 12329 IdentifierInfo *Id, 12330 Expr *Val) { 12331 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12332 llvm::APSInt EnumVal(IntWidth); 12333 QualType EltTy; 12334 12335 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12336 Val = 0; 12337 12338 if (Val) 12339 Val = DefaultLvalueConversion(Val).take(); 12340 12341 if (Val) { 12342 if (Enum->isDependentType() || Val->isTypeDependent()) 12343 EltTy = Context.DependentTy; 12344 else { 12345 SourceLocation ExpLoc; 12346 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12347 !getLangOpts().MSVCCompat) { 12348 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12349 // constant-expression in the enumerator-definition shall be a converted 12350 // constant expression of the underlying type. 12351 EltTy = Enum->getIntegerType(); 12352 ExprResult Converted = 12353 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12354 CCEK_Enumerator); 12355 if (Converted.isInvalid()) 12356 Val = 0; 12357 else 12358 Val = Converted.take(); 12359 } else if (!Val->isValueDependent() && 12360 !(Val = VerifyIntegerConstantExpression(Val, 12361 &EnumVal).take())) { 12362 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12363 } else { 12364 if (Enum->isFixed()) { 12365 EltTy = Enum->getIntegerType(); 12366 12367 // In Obj-C and Microsoft mode, require the enumeration value to be 12368 // representable in the underlying type of the enumeration. In C++11, 12369 // we perform a non-narrowing conversion as part of converted constant 12370 // expression checking. 12371 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12372 if (getLangOpts().MSVCCompat) { 12373 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12374 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12375 } else 12376 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12377 } else 12378 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12379 } else if (getLangOpts().CPlusPlus) { 12380 // C++11 [dcl.enum]p5: 12381 // If the underlying type is not fixed, the type of each enumerator 12382 // is the type of its initializing value: 12383 // - If an initializer is specified for an enumerator, the 12384 // initializing value has the same type as the expression. 12385 EltTy = Val->getType(); 12386 } else { 12387 // C99 6.7.2.2p2: 12388 // The expression that defines the value of an enumeration constant 12389 // shall be an integer constant expression that has a value 12390 // representable as an int. 12391 12392 // Complain if the value is not representable in an int. 12393 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12394 Diag(IdLoc, diag::ext_enum_value_not_int) 12395 << EnumVal.toString(10) << Val->getSourceRange() 12396 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12397 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12398 // Force the type of the expression to 'int'. 12399 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12400 } 12401 EltTy = Val->getType(); 12402 } 12403 } 12404 } 12405 } 12406 12407 if (!Val) { 12408 if (Enum->isDependentType()) 12409 EltTy = Context.DependentTy; 12410 else if (!LastEnumConst) { 12411 // C++0x [dcl.enum]p5: 12412 // If the underlying type is not fixed, the type of each enumerator 12413 // is the type of its initializing value: 12414 // - If no initializer is specified for the first enumerator, the 12415 // initializing value has an unspecified integral type. 12416 // 12417 // GCC uses 'int' for its unspecified integral type, as does 12418 // C99 6.7.2.2p3. 12419 if (Enum->isFixed()) { 12420 EltTy = Enum->getIntegerType(); 12421 } 12422 else { 12423 EltTy = Context.IntTy; 12424 } 12425 } else { 12426 // Assign the last value + 1. 12427 EnumVal = LastEnumConst->getInitVal(); 12428 ++EnumVal; 12429 EltTy = LastEnumConst->getType(); 12430 12431 // Check for overflow on increment. 12432 if (EnumVal < LastEnumConst->getInitVal()) { 12433 // C++0x [dcl.enum]p5: 12434 // If the underlying type is not fixed, the type of each enumerator 12435 // is the type of its initializing value: 12436 // 12437 // - Otherwise the type of the initializing value is the same as 12438 // the type of the initializing value of the preceding enumerator 12439 // unless the incremented value is not representable in that type, 12440 // in which case the type is an unspecified integral type 12441 // sufficient to contain the incremented value. If no such type 12442 // exists, the program is ill-formed. 12443 QualType T = getNextLargerIntegralType(Context, EltTy); 12444 if (T.isNull() || Enum->isFixed()) { 12445 // There is no integral type larger enough to represent this 12446 // value. Complain, then allow the value to wrap around. 12447 EnumVal = LastEnumConst->getInitVal(); 12448 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12449 ++EnumVal; 12450 if (Enum->isFixed()) 12451 // When the underlying type is fixed, this is ill-formed. 12452 Diag(IdLoc, diag::err_enumerator_wrapped) 12453 << EnumVal.toString(10) 12454 << EltTy; 12455 else 12456 Diag(IdLoc, diag::warn_enumerator_too_large) 12457 << EnumVal.toString(10); 12458 } else { 12459 EltTy = T; 12460 } 12461 12462 // Retrieve the last enumerator's value, extent that type to the 12463 // type that is supposed to be large enough to represent the incremented 12464 // value, then increment. 12465 EnumVal = LastEnumConst->getInitVal(); 12466 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12467 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12468 ++EnumVal; 12469 12470 // If we're not in C++, diagnose the overflow of enumerator values, 12471 // which in C99 means that the enumerator value is not representable in 12472 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12473 // permits enumerator values that are representable in some larger 12474 // integral type. 12475 if (!getLangOpts().CPlusPlus && !T.isNull()) 12476 Diag(IdLoc, diag::warn_enum_value_overflow); 12477 } else if (!getLangOpts().CPlusPlus && 12478 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12479 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12480 Diag(IdLoc, diag::ext_enum_value_not_int) 12481 << EnumVal.toString(10) << 1; 12482 } 12483 } 12484 } 12485 12486 if (!EltTy->isDependentType()) { 12487 // Make the enumerator value match the signedness and size of the 12488 // enumerator's type. 12489 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12490 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12491 } 12492 12493 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12494 Val, EnumVal); 12495 } 12496 12497 12498 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12499 SourceLocation IdLoc, IdentifierInfo *Id, 12500 AttributeList *Attr, 12501 SourceLocation EqualLoc, Expr *Val) { 12502 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12503 EnumConstantDecl *LastEnumConst = 12504 cast_or_null<EnumConstantDecl>(lastEnumConst); 12505 12506 // The scope passed in may not be a decl scope. Zip up the scope tree until 12507 // we find one that is. 12508 S = getNonFieldDeclScope(S); 12509 12510 // Verify that there isn't already something declared with this name in this 12511 // scope. 12512 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12513 ForRedeclaration); 12514 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12515 // Maybe we will complain about the shadowed template parameter. 12516 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12517 // Just pretend that we didn't see the previous declaration. 12518 PrevDecl = 0; 12519 } 12520 12521 if (PrevDecl) { 12522 // When in C++, we may get a TagDecl with the same name; in this case the 12523 // enum constant will 'hide' the tag. 12524 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12525 "Received TagDecl when not in C++!"); 12526 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12527 if (isa<EnumConstantDecl>(PrevDecl)) 12528 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12529 else 12530 Diag(IdLoc, diag::err_redefinition) << Id; 12531 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12532 return 0; 12533 } 12534 } 12535 12536 // C++ [class.mem]p15: 12537 // If T is the name of a class, then each of the following shall have a name 12538 // different from T: 12539 // - every enumerator of every member of class T that is an unscoped 12540 // enumerated type 12541 if (CXXRecordDecl *Record 12542 = dyn_cast<CXXRecordDecl>( 12543 TheEnumDecl->getDeclContext()->getRedeclContext())) 12544 if (!TheEnumDecl->isScoped() && 12545 Record->getIdentifier() && Record->getIdentifier() == Id) 12546 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12547 12548 EnumConstantDecl *New = 12549 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12550 12551 if (New) { 12552 // Process attributes. 12553 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12554 12555 // Register this decl in the current scope stack. 12556 New->setAccess(TheEnumDecl->getAccess()); 12557 PushOnScopeChains(New, S); 12558 } 12559 12560 ActOnDocumentableDecl(New); 12561 12562 return New; 12563 } 12564 12565 // Returns true when the enum initial expression does not trigger the 12566 // duplicate enum warning. A few common cases are exempted as follows: 12567 // Element2 = Element1 12568 // Element2 = Element1 + 1 12569 // Element2 = Element1 - 1 12570 // Where Element2 and Element1 are from the same enum. 12571 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12572 Expr *InitExpr = ECD->getInitExpr(); 12573 if (!InitExpr) 12574 return true; 12575 InitExpr = InitExpr->IgnoreImpCasts(); 12576 12577 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12578 if (!BO->isAdditiveOp()) 12579 return true; 12580 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12581 if (!IL) 12582 return true; 12583 if (IL->getValue() != 1) 12584 return true; 12585 12586 InitExpr = BO->getLHS(); 12587 } 12588 12589 // This checks if the elements are from the same enum. 12590 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12591 if (!DRE) 12592 return true; 12593 12594 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12595 if (!EnumConstant) 12596 return true; 12597 12598 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12599 Enum) 12600 return true; 12601 12602 return false; 12603 } 12604 12605 struct DupKey { 12606 int64_t val; 12607 bool isTombstoneOrEmptyKey; 12608 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12609 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12610 }; 12611 12612 static DupKey GetDupKey(const llvm::APSInt& Val) { 12613 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12614 false); 12615 } 12616 12617 struct DenseMapInfoDupKey { 12618 static DupKey getEmptyKey() { return DupKey(0, true); } 12619 static DupKey getTombstoneKey() { return DupKey(1, true); } 12620 static unsigned getHashValue(const DupKey Key) { 12621 return (unsigned)(Key.val * 37); 12622 } 12623 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12624 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12625 LHS.val == RHS.val; 12626 } 12627 }; 12628 12629 // Emits a warning when an element is implicitly set a value that 12630 // a previous element has already been set to. 12631 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12632 EnumDecl *Enum, 12633 QualType EnumType) { 12634 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12635 Enum->getLocation()) == 12636 DiagnosticsEngine::Ignored) 12637 return; 12638 // Avoid anonymous enums 12639 if (!Enum->getIdentifier()) 12640 return; 12641 12642 // Only check for small enums. 12643 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12644 return; 12645 12646 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12647 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12648 12649 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12650 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12651 ValueToVectorMap; 12652 12653 DuplicatesVector DupVector; 12654 ValueToVectorMap EnumMap; 12655 12656 // Populate the EnumMap with all values represented by enum constants without 12657 // an initialier. 12658 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12659 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12660 12661 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12662 // this constant. Skip this enum since it may be ill-formed. 12663 if (!ECD) { 12664 return; 12665 } 12666 12667 if (ECD->getInitExpr()) 12668 continue; 12669 12670 DupKey Key = GetDupKey(ECD->getInitVal()); 12671 DeclOrVector &Entry = EnumMap[Key]; 12672 12673 // First time encountering this value. 12674 if (Entry.isNull()) 12675 Entry = ECD; 12676 } 12677 12678 // Create vectors for any values that has duplicates. 12679 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12680 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12681 if (!ValidDuplicateEnum(ECD, Enum)) 12682 continue; 12683 12684 DupKey Key = GetDupKey(ECD->getInitVal()); 12685 12686 DeclOrVector& Entry = EnumMap[Key]; 12687 if (Entry.isNull()) 12688 continue; 12689 12690 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12691 // Ensure constants are different. 12692 if (D == ECD) 12693 continue; 12694 12695 // Create new vector and push values onto it. 12696 ECDVector *Vec = new ECDVector(); 12697 Vec->push_back(D); 12698 Vec->push_back(ECD); 12699 12700 // Update entry to point to the duplicates vector. 12701 Entry = Vec; 12702 12703 // Store the vector somewhere we can consult later for quick emission of 12704 // diagnostics. 12705 DupVector.push_back(Vec); 12706 continue; 12707 } 12708 12709 ECDVector *Vec = Entry.get<ECDVector*>(); 12710 // Make sure constants are not added more than once. 12711 if (*Vec->begin() == ECD) 12712 continue; 12713 12714 Vec->push_back(ECD); 12715 } 12716 12717 // Emit diagnostics. 12718 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12719 DupVectorEnd = DupVector.end(); 12720 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12721 ECDVector *Vec = *DupVectorIter; 12722 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12723 12724 // Emit warning for one enum constant. 12725 ECDVector::iterator I = Vec->begin(); 12726 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12727 << (*I)->getName() << (*I)->getInitVal().toString(10) 12728 << (*I)->getSourceRange(); 12729 ++I; 12730 12731 // Emit one note for each of the remaining enum constants with 12732 // the same value. 12733 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12734 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12735 << (*I)->getName() << (*I)->getInitVal().toString(10) 12736 << (*I)->getSourceRange(); 12737 delete Vec; 12738 } 12739 } 12740 12741 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12742 SourceLocation RBraceLoc, Decl *EnumDeclX, 12743 ArrayRef<Decl *> Elements, 12744 Scope *S, AttributeList *Attr) { 12745 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12746 QualType EnumType = Context.getTypeDeclType(Enum); 12747 12748 if (Attr) 12749 ProcessDeclAttributeList(S, Enum, Attr); 12750 12751 if (Enum->isDependentType()) { 12752 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12753 EnumConstantDecl *ECD = 12754 cast_or_null<EnumConstantDecl>(Elements[i]); 12755 if (!ECD) continue; 12756 12757 ECD->setType(EnumType); 12758 } 12759 12760 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12761 return; 12762 } 12763 12764 // TODO: If the result value doesn't fit in an int, it must be a long or long 12765 // long value. ISO C does not support this, but GCC does as an extension, 12766 // emit a warning. 12767 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12768 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12769 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12770 12771 // Verify that all the values are okay, compute the size of the values, and 12772 // reverse the list. 12773 unsigned NumNegativeBits = 0; 12774 unsigned NumPositiveBits = 0; 12775 12776 // Keep track of whether all elements have type int. 12777 bool AllElementsInt = true; 12778 12779 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12780 EnumConstantDecl *ECD = 12781 cast_or_null<EnumConstantDecl>(Elements[i]); 12782 if (!ECD) continue; // Already issued a diagnostic. 12783 12784 const llvm::APSInt &InitVal = ECD->getInitVal(); 12785 12786 // Keep track of the size of positive and negative values. 12787 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12788 NumPositiveBits = std::max(NumPositiveBits, 12789 (unsigned)InitVal.getActiveBits()); 12790 else 12791 NumNegativeBits = std::max(NumNegativeBits, 12792 (unsigned)InitVal.getMinSignedBits()); 12793 12794 // Keep track of whether every enum element has type int (very commmon). 12795 if (AllElementsInt) 12796 AllElementsInt = ECD->getType() == Context.IntTy; 12797 } 12798 12799 // Figure out the type that should be used for this enum. 12800 QualType BestType; 12801 unsigned BestWidth; 12802 12803 // C++0x N3000 [conv.prom]p3: 12804 // An rvalue of an unscoped enumeration type whose underlying 12805 // type is not fixed can be converted to an rvalue of the first 12806 // of the following types that can represent all the values of 12807 // the enumeration: int, unsigned int, long int, unsigned long 12808 // int, long long int, or unsigned long long int. 12809 // C99 6.4.4.3p2: 12810 // An identifier declared as an enumeration constant has type int. 12811 // The C99 rule is modified by a gcc extension 12812 QualType BestPromotionType; 12813 12814 bool Packed = Enum->hasAttr<PackedAttr>(); 12815 // -fshort-enums is the equivalent to specifying the packed attribute on all 12816 // enum definitions. 12817 if (LangOpts.ShortEnums) 12818 Packed = true; 12819 12820 if (Enum->isFixed()) { 12821 BestType = Enum->getIntegerType(); 12822 if (BestType->isPromotableIntegerType()) 12823 BestPromotionType = Context.getPromotedIntegerType(BestType); 12824 else 12825 BestPromotionType = BestType; 12826 // We don't need to set BestWidth, because BestType is going to be the type 12827 // of the enumerators, but we do anyway because otherwise some compilers 12828 // warn that it might be used uninitialized. 12829 BestWidth = CharWidth; 12830 } 12831 else if (NumNegativeBits) { 12832 // If there is a negative value, figure out the smallest integer type (of 12833 // int/long/longlong) that fits. 12834 // If it's packed, check also if it fits a char or a short. 12835 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12836 BestType = Context.SignedCharTy; 12837 BestWidth = CharWidth; 12838 } else if (Packed && NumNegativeBits <= ShortWidth && 12839 NumPositiveBits < ShortWidth) { 12840 BestType = Context.ShortTy; 12841 BestWidth = ShortWidth; 12842 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12843 BestType = Context.IntTy; 12844 BestWidth = IntWidth; 12845 } else { 12846 BestWidth = Context.getTargetInfo().getLongWidth(); 12847 12848 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12849 BestType = Context.LongTy; 12850 } else { 12851 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12852 12853 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12854 Diag(Enum->getLocation(), diag::warn_enum_too_large); 12855 BestType = Context.LongLongTy; 12856 } 12857 } 12858 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12859 } else { 12860 // If there is no negative value, figure out the smallest type that fits 12861 // all of the enumerator values. 12862 // If it's packed, check also if it fits a char or a short. 12863 if (Packed && NumPositiveBits <= CharWidth) { 12864 BestType = Context.UnsignedCharTy; 12865 BestPromotionType = Context.IntTy; 12866 BestWidth = CharWidth; 12867 } else if (Packed && NumPositiveBits <= ShortWidth) { 12868 BestType = Context.UnsignedShortTy; 12869 BestPromotionType = Context.IntTy; 12870 BestWidth = ShortWidth; 12871 } else if (NumPositiveBits <= IntWidth) { 12872 BestType = Context.UnsignedIntTy; 12873 BestWidth = IntWidth; 12874 BestPromotionType 12875 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12876 ? Context.UnsignedIntTy : Context.IntTy; 12877 } else if (NumPositiveBits <= 12878 (BestWidth = Context.getTargetInfo().getLongWidth())) { 12879 BestType = Context.UnsignedLongTy; 12880 BestPromotionType 12881 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12882 ? Context.UnsignedLongTy : Context.LongTy; 12883 } else { 12884 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12885 assert(NumPositiveBits <= BestWidth && 12886 "How could an initializer get larger than ULL?"); 12887 BestType = Context.UnsignedLongLongTy; 12888 BestPromotionType 12889 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12890 ? Context.UnsignedLongLongTy : Context.LongLongTy; 12891 } 12892 } 12893 12894 // Loop over all of the enumerator constants, changing their types to match 12895 // the type of the enum if needed. 12896 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12897 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12898 if (!ECD) continue; // Already issued a diagnostic. 12899 12900 // Standard C says the enumerators have int type, but we allow, as an 12901 // extension, the enumerators to be larger than int size. If each 12902 // enumerator value fits in an int, type it as an int, otherwise type it the 12903 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 12904 // that X has type 'int', not 'unsigned'. 12905 12906 // Determine whether the value fits into an int. 12907 llvm::APSInt InitVal = ECD->getInitVal(); 12908 12909 // If it fits into an integer type, force it. Otherwise force it to match 12910 // the enum decl type. 12911 QualType NewTy; 12912 unsigned NewWidth; 12913 bool NewSign; 12914 if (!getLangOpts().CPlusPlus && 12915 !Enum->isFixed() && 12916 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 12917 NewTy = Context.IntTy; 12918 NewWidth = IntWidth; 12919 NewSign = true; 12920 } else if (ECD->getType() == BestType) { 12921 // Already the right type! 12922 if (getLangOpts().CPlusPlus) 12923 // C++ [dcl.enum]p4: Following the closing brace of an 12924 // enum-specifier, each enumerator has the type of its 12925 // enumeration. 12926 ECD->setType(EnumType); 12927 continue; 12928 } else { 12929 NewTy = BestType; 12930 NewWidth = BestWidth; 12931 NewSign = BestType->isSignedIntegerOrEnumerationType(); 12932 } 12933 12934 // Adjust the APSInt value. 12935 InitVal = InitVal.extOrTrunc(NewWidth); 12936 InitVal.setIsSigned(NewSign); 12937 ECD->setInitVal(InitVal); 12938 12939 // Adjust the Expr initializer and type. 12940 if (ECD->getInitExpr() && 12941 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 12942 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 12943 CK_IntegralCast, 12944 ECD->getInitExpr(), 12945 /*base paths*/ 0, 12946 VK_RValue)); 12947 if (getLangOpts().CPlusPlus) 12948 // C++ [dcl.enum]p4: Following the closing brace of an 12949 // enum-specifier, each enumerator has the type of its 12950 // enumeration. 12951 ECD->setType(EnumType); 12952 else 12953 ECD->setType(NewTy); 12954 } 12955 12956 Enum->completeDefinition(BestType, BestPromotionType, 12957 NumPositiveBits, NumNegativeBits); 12958 12959 // If we're declaring a function, ensure this decl isn't forgotten about - 12960 // it needs to go into the function scope. 12961 if (InFunctionDeclarator) 12962 DeclsInPrototypeScope.push_back(Enum); 12963 12964 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 12965 12966 // Now that the enum type is defined, ensure it's not been underaligned. 12967 if (Enum->hasAttrs()) 12968 CheckAlignasUnderalignment(Enum); 12969 } 12970 12971 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 12972 SourceLocation StartLoc, 12973 SourceLocation EndLoc) { 12974 StringLiteral *AsmString = cast<StringLiteral>(expr); 12975 12976 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 12977 AsmString, StartLoc, 12978 EndLoc); 12979 CurContext->addDecl(New); 12980 return New; 12981 } 12982 12983 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 12984 SourceLocation ImportLoc, 12985 ModuleIdPath Path) { 12986 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 12987 Module::AllVisible, 12988 /*IsIncludeDirective=*/false); 12989 if (!Mod) 12990 return true; 12991 12992 SmallVector<SourceLocation, 2> IdentifierLocs; 12993 Module *ModCheck = Mod; 12994 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 12995 // If we've run out of module parents, just drop the remaining identifiers. 12996 // We need the length to be consistent. 12997 if (!ModCheck) 12998 break; 12999 ModCheck = ModCheck->Parent; 13000 13001 IdentifierLocs.push_back(Path[I].second); 13002 } 13003 13004 ImportDecl *Import = ImportDecl::Create(Context, 13005 Context.getTranslationUnitDecl(), 13006 AtLoc.isValid()? AtLoc : ImportLoc, 13007 Mod, IdentifierLocs); 13008 Context.getTranslationUnitDecl()->addDecl(Import); 13009 return Import; 13010 } 13011 13012 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13013 // FIXME: Should we synthesize an ImportDecl here? 13014 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13015 /*Complain=*/true); 13016 } 13017 13018 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 13019 // Create the implicit import declaration. 13020 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13021 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13022 Loc, Mod, Loc); 13023 TU->addDecl(ImportD); 13024 Consumer.HandleImplicitImportDecl(ImportD); 13025 13026 // Make the module visible. 13027 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13028 /*Complain=*/false); 13029 } 13030 13031 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13032 IdentifierInfo* AliasName, 13033 SourceLocation PragmaLoc, 13034 SourceLocation NameLoc, 13035 SourceLocation AliasNameLoc) { 13036 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13037 LookupOrdinaryName); 13038 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13039 AliasName->getName(), 0); 13040 13041 if (PrevDecl) 13042 PrevDecl->addAttr(Attr); 13043 else 13044 (void)ExtnameUndeclaredIdentifiers.insert( 13045 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13046 } 13047 13048 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13049 SourceLocation PragmaLoc, 13050 SourceLocation NameLoc) { 13051 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13052 13053 if (PrevDecl) { 13054 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13055 } else { 13056 (void)WeakUndeclaredIdentifiers.insert( 13057 std::pair<IdentifierInfo*,WeakInfo> 13058 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 13059 } 13060 } 13061 13062 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13063 IdentifierInfo* AliasName, 13064 SourceLocation PragmaLoc, 13065 SourceLocation NameLoc, 13066 SourceLocation AliasNameLoc) { 13067 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13068 LookupOrdinaryName); 13069 WeakInfo W = WeakInfo(Name, NameLoc); 13070 13071 if (PrevDecl) { 13072 if (!PrevDecl->hasAttr<AliasAttr>()) 13073 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13074 DeclApplyPragmaWeak(TUScope, ND, W); 13075 } else { 13076 (void)WeakUndeclaredIdentifiers.insert( 13077 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13078 } 13079 } 13080 13081 Decl *Sema::getObjCDeclContext() const { 13082 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13083 } 13084 13085 AvailabilityResult Sema::getCurContextAvailability() const { 13086 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13087 // If we are within an Objective-C method, we should consult 13088 // both the availability of the method as well as the 13089 // enclosing class. If the class is (say) deprecated, 13090 // the entire method is considered deprecated from the 13091 // purpose of checking if the current context is deprecated. 13092 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13093 AvailabilityResult R = MD->getAvailability(); 13094 if (R != AR_Available) 13095 return R; 13096 D = MD->getClassInterface(); 13097 } 13098 // If we are within an Objective-c @implementation, it 13099 // gets the same availability context as the @interface. 13100 else if (const ObjCImplementationDecl *ID = 13101 dyn_cast<ObjCImplementationDecl>(D)) { 13102 D = ID->getClassInterface(); 13103 } 13104 return D->getAvailability(); 13105 } 13106