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 "clang/Sema/Initialization.h" 16 #include "clang/Sema/Lookup.h" 17 #include "clang/Sema/CXXFieldCollector.h" 18 #include "clang/Sema/Scope.h" 19 #include "clang/Sema/ScopeInfo.h" 20 #include "TypeLocBuilder.h" 21 #include "clang/AST/ASTConsumer.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/CXXInheritance.h" 24 #include "clang/AST/CommentDiagnostic.h" 25 #include "clang/AST/DeclCXX.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/AST/DeclTemplate.h" 28 #include "clang/AST/EvaluatedExprVisitor.h" 29 #include "clang/AST/ExprCXX.h" 30 #include "clang/AST/StmtCXX.h" 31 #include "clang/AST/CharUnits.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/ParsedTemplate.h" 34 #include "clang/Parse/ParseDiagnostic.h" 35 #include "clang/Basic/PartialDiagnostic.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Basic/SourceManager.h" 38 #include "clang/Basic/TargetInfo.h" 39 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 40 #include "clang/Lex/Preprocessor.h" 41 #include "clang/Lex/HeaderSearch.h" 42 #include "clang/Lex/ModuleLoader.h" 43 #include "llvm/ADT/SmallString.h" 44 #include "llvm/ADT/Triple.h" 45 #include <algorithm> 46 #include <cstring> 47 #include <functional> 48 using namespace clang; 49 using namespace sema; 50 51 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 52 if (OwnedType) { 53 Decl *Group[2] = { OwnedType, Ptr }; 54 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 55 } 56 57 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 58 } 59 60 namespace { 61 62 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 63 public: 64 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false) 65 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) { 66 WantExpressionKeywords = false; 67 WantCXXNamedCasts = false; 68 WantRemainingKeywords = false; 69 } 70 71 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 72 if (NamedDecl *ND = candidate.getCorrectionDecl()) 73 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 74 (AllowInvalidDecl || !ND->isInvalidDecl()); 75 else 76 return !WantClassName && candidate.isKeyword(); 77 } 78 79 private: 80 bool AllowInvalidDecl; 81 bool WantClassName; 82 }; 83 84 } 85 86 /// \brief Determine whether the token kind starts a simple-type-specifier. 87 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 88 switch (Kind) { 89 // FIXME: Take into account the current language when deciding whether a 90 // token kind is a valid type specifier 91 case tok::kw_short: 92 case tok::kw_long: 93 case tok::kw___int64: 94 case tok::kw___int128: 95 case tok::kw_signed: 96 case tok::kw_unsigned: 97 case tok::kw_void: 98 case tok::kw_char: 99 case tok::kw_int: 100 case tok::kw_half: 101 case tok::kw_float: 102 case tok::kw_double: 103 case tok::kw_wchar_t: 104 case tok::kw_bool: 105 case tok::kw___underlying_type: 106 return true; 107 108 case tok::annot_typename: 109 case tok::kw_char16_t: 110 case tok::kw_char32_t: 111 case tok::kw_typeof: 112 case tok::kw_decltype: 113 return getLangOpts().CPlusPlus; 114 115 default: 116 break; 117 } 118 119 return false; 120 } 121 122 /// \brief If the identifier refers to a type name within this scope, 123 /// return the declaration of that type. 124 /// 125 /// This routine performs ordinary name lookup of the identifier II 126 /// within the given scope, with optional C++ scope specifier SS, to 127 /// determine whether the name refers to a type. If so, returns an 128 /// opaque pointer (actually a QualType) corresponding to that 129 /// type. Otherwise, returns NULL. 130 /// 131 /// If name lookup results in an ambiguity, this routine will complain 132 /// and then return NULL. 133 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 134 Scope *S, CXXScopeSpec *SS, 135 bool isClassName, bool HasTrailingDot, 136 ParsedType ObjectTypePtr, 137 bool IsCtorOrDtorName, 138 bool WantNontrivialTypeSourceInfo, 139 IdentifierInfo **CorrectedII) { 140 // Determine where we will perform name lookup. 141 DeclContext *LookupCtx = 0; 142 if (ObjectTypePtr) { 143 QualType ObjectType = ObjectTypePtr.get(); 144 if (ObjectType->isRecordType()) 145 LookupCtx = computeDeclContext(ObjectType); 146 } else if (SS && SS->isNotEmpty()) { 147 LookupCtx = computeDeclContext(*SS, false); 148 149 if (!LookupCtx) { 150 if (isDependentScopeSpecifier(*SS)) { 151 // C++ [temp.res]p3: 152 // A qualified-id that refers to a type and in which the 153 // nested-name-specifier depends on a template-parameter (14.6.2) 154 // shall be prefixed by the keyword typename to indicate that the 155 // qualified-id denotes a type, forming an 156 // elaborated-type-specifier (7.1.5.3). 157 // 158 // We therefore do not perform any name lookup if the result would 159 // refer to a member of an unknown specialization. 160 if (!isClassName && !IsCtorOrDtorName) 161 return ParsedType(); 162 163 // We know from the grammar that this name refers to a type, 164 // so build a dependent node to describe the type. 165 if (WantNontrivialTypeSourceInfo) 166 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 167 168 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 169 QualType T = 170 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 171 II, NameLoc); 172 173 return ParsedType::make(T); 174 } 175 176 return ParsedType(); 177 } 178 179 if (!LookupCtx->isDependentContext() && 180 RequireCompleteDeclContext(*SS, LookupCtx)) 181 return ParsedType(); 182 } 183 184 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 185 // lookup for class-names. 186 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 187 LookupOrdinaryName; 188 LookupResult Result(*this, &II, NameLoc, Kind); 189 if (LookupCtx) { 190 // Perform "qualified" name lookup into the declaration context we 191 // computed, which is either the type of the base of a member access 192 // expression or the declaration context associated with a prior 193 // nested-name-specifier. 194 LookupQualifiedName(Result, LookupCtx); 195 196 if (ObjectTypePtr && Result.empty()) { 197 // C++ [basic.lookup.classref]p3: 198 // If the unqualified-id is ~type-name, the type-name is looked up 199 // in the context of the entire postfix-expression. If the type T of 200 // the object expression is of a class type C, the type-name is also 201 // looked up in the scope of class C. At least one of the lookups shall 202 // find a name that refers to (possibly cv-qualified) T. 203 LookupName(Result, S); 204 } 205 } else { 206 // Perform unqualified name lookup. 207 LookupName(Result, S); 208 } 209 210 NamedDecl *IIDecl = 0; 211 switch (Result.getResultKind()) { 212 case LookupResult::NotFound: 213 case LookupResult::NotFoundInCurrentInstantiation: 214 if (CorrectedII) { 215 TypeNameValidatorCCC Validator(true, isClassName); 216 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 217 Kind, S, SS, Validator); 218 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 219 TemplateTy Template; 220 bool MemberOfUnknownSpecialization; 221 UnqualifiedId TemplateName; 222 TemplateName.setIdentifier(NewII, NameLoc); 223 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 224 CXXScopeSpec NewSS, *NewSSPtr = SS; 225 if (SS && NNS) { 226 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 227 NewSSPtr = &NewSS; 228 } 229 if (Correction && (NNS || NewII != &II) && 230 // Ignore a correction to a template type as the to-be-corrected 231 // identifier is not a template (typo correction for template names 232 // is handled elsewhere). 233 !(getLangOpts().CPlusPlus && NewSSPtr && 234 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 235 false, Template, MemberOfUnknownSpecialization))) { 236 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 237 isClassName, HasTrailingDot, ObjectTypePtr, 238 IsCtorOrDtorName, 239 WantNontrivialTypeSourceInfo); 240 if (Ty) { 241 std::string CorrectedStr(Correction.getAsString(getLangOpts())); 242 std::string CorrectedQuotedStr( 243 Correction.getQuoted(getLangOpts())); 244 Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest) 245 << Result.getLookupName() << CorrectedQuotedStr << isClassName 246 << FixItHint::CreateReplacement(SourceRange(NameLoc), 247 CorrectedStr); 248 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl()) 249 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 250 << CorrectedQuotedStr; 251 252 if (SS && NNS) 253 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 254 *CorrectedII = NewII; 255 return Ty; 256 } 257 } 258 } 259 // If typo correction failed or was not performed, fall through 260 case LookupResult::FoundOverloaded: 261 case LookupResult::FoundUnresolvedValue: 262 Result.suppressDiagnostics(); 263 return ParsedType(); 264 265 case LookupResult::Ambiguous: 266 // Recover from type-hiding ambiguities by hiding the type. We'll 267 // do the lookup again when looking for an object, and we can 268 // diagnose the error then. If we don't do this, then the error 269 // about hiding the type will be immediately followed by an error 270 // that only makes sense if the identifier was treated like a type. 271 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 272 Result.suppressDiagnostics(); 273 return ParsedType(); 274 } 275 276 // Look to see if we have a type anywhere in the list of results. 277 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 278 Res != ResEnd; ++Res) { 279 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 280 if (!IIDecl || 281 (*Res)->getLocation().getRawEncoding() < 282 IIDecl->getLocation().getRawEncoding()) 283 IIDecl = *Res; 284 } 285 } 286 287 if (!IIDecl) { 288 // None of the entities we found is a type, so there is no way 289 // to even assume that the result is a type. In this case, don't 290 // complain about the ambiguity. The parser will either try to 291 // perform this lookup again (e.g., as an object name), which 292 // will produce the ambiguity, or will complain that it expected 293 // a type name. 294 Result.suppressDiagnostics(); 295 return ParsedType(); 296 } 297 298 // We found a type within the ambiguous lookup; diagnose the 299 // ambiguity and then return that type. This might be the right 300 // answer, or it might not be, but it suppresses any attempt to 301 // perform the name lookup again. 302 break; 303 304 case LookupResult::Found: 305 IIDecl = Result.getFoundDecl(); 306 break; 307 } 308 309 assert(IIDecl && "Didn't find decl"); 310 311 QualType T; 312 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 313 DiagnoseUseOfDecl(IIDecl, NameLoc); 314 315 if (T.isNull()) 316 T = Context.getTypeDeclType(TD); 317 318 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 319 // constructor or destructor name (in such a case, the scope specifier 320 // will be attached to the enclosing Expr or Decl node). 321 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 322 if (WantNontrivialTypeSourceInfo) { 323 // Construct a type with type-source information. 324 TypeLocBuilder Builder; 325 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 326 327 T = getElaboratedType(ETK_None, *SS, T); 328 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 329 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 330 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 331 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 332 } else { 333 T = getElaboratedType(ETK_None, *SS, T); 334 } 335 } 336 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 337 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 338 if (!HasTrailingDot) 339 T = Context.getObjCInterfaceType(IDecl); 340 } 341 342 if (T.isNull()) { 343 // If it's not plausibly a type, suppress diagnostics. 344 Result.suppressDiagnostics(); 345 return ParsedType(); 346 } 347 return ParsedType::make(T); 348 } 349 350 /// isTagName() - This method is called *for error recovery purposes only* 351 /// to determine if the specified name is a valid tag name ("struct foo"). If 352 /// so, this returns the TST for the tag corresponding to it (TST_enum, 353 /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 354 /// where the user forgot to specify the tag. 355 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 356 // Do a tag name lookup in this scope. 357 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 358 LookupName(R, S, false); 359 R.suppressDiagnostics(); 360 if (R.getResultKind() == LookupResult::Found) 361 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 362 switch (TD->getTagKind()) { 363 case TTK_Struct: return DeclSpec::TST_struct; 364 case TTK_Union: return DeclSpec::TST_union; 365 case TTK_Class: return DeclSpec::TST_class; 366 case TTK_Enum: return DeclSpec::TST_enum; 367 } 368 } 369 370 return DeclSpec::TST_unspecified; 371 } 372 373 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 374 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 375 /// then downgrade the missing typename error to a warning. 376 /// This is needed for MSVC compatibility; Example: 377 /// @code 378 /// template<class T> class A { 379 /// public: 380 /// typedef int TYPE; 381 /// }; 382 /// template<class T> class B : public A<T> { 383 /// public: 384 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 385 /// }; 386 /// @endcode 387 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 388 if (CurContext->isRecord()) { 389 const Type *Ty = SS->getScopeRep()->getAsType(); 390 391 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 392 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 393 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 394 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 395 return true; 396 return S->isFunctionPrototypeScope(); 397 } 398 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 399 } 400 401 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 402 SourceLocation IILoc, 403 Scope *S, 404 CXXScopeSpec *SS, 405 ParsedType &SuggestedType) { 406 // We don't have anything to suggest (yet). 407 SuggestedType = ParsedType(); 408 409 // There may have been a typo in the name of the type. Look up typo 410 // results, in case we have something that we can suggest. 411 TypeNameValidatorCCC Validator(false); 412 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 413 LookupOrdinaryName, S, SS, 414 Validator)) { 415 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 416 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 417 418 if (Corrected.isKeyword()) { 419 // We corrected to a keyword. 420 IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo(); 421 if (!isSimpleTypeSpecifier(NewII->getTokenID())) 422 CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr; 423 Diag(IILoc, diag::err_unknown_typename_suggest) 424 << II << CorrectedQuotedStr 425 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 426 II = NewII; 427 } else { 428 NamedDecl *Result = Corrected.getCorrectionDecl(); 429 // We found a similarly-named type or interface; suggest that. 430 if (!SS || !SS->isSet()) 431 Diag(IILoc, diag::err_unknown_typename_suggest) 432 << II << CorrectedQuotedStr 433 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 434 else if (DeclContext *DC = computeDeclContext(*SS, false)) 435 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 436 << II << DC << CorrectedQuotedStr << SS->getRange() 437 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 438 else 439 llvm_unreachable("could not have corrected a typo here"); 440 441 Diag(Result->getLocation(), diag::note_previous_decl) 442 << CorrectedQuotedStr; 443 444 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 445 false, false, ParsedType(), 446 /*IsCtorOrDtorName=*/false, 447 /*NonTrivialTypeSourceInfo=*/true); 448 } 449 return true; 450 } 451 452 if (getLangOpts().CPlusPlus) { 453 // See if II is a class template that the user forgot to pass arguments to. 454 UnqualifiedId Name; 455 Name.setIdentifier(II, IILoc); 456 CXXScopeSpec EmptySS; 457 TemplateTy TemplateResult; 458 bool MemberOfUnknownSpecialization; 459 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 460 Name, ParsedType(), true, TemplateResult, 461 MemberOfUnknownSpecialization) == TNK_Type_template) { 462 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 463 Diag(IILoc, diag::err_template_missing_args) << TplName; 464 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 465 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 466 << TplDecl->getTemplateParameters()->getSourceRange(); 467 } 468 return true; 469 } 470 } 471 472 // FIXME: Should we move the logic that tries to recover from a missing tag 473 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 474 475 if (!SS || (!SS->isSet() && !SS->isInvalid())) 476 Diag(IILoc, diag::err_unknown_typename) << II; 477 else if (DeclContext *DC = computeDeclContext(*SS, false)) 478 Diag(IILoc, diag::err_typename_nested_not_found) 479 << II << DC << SS->getRange(); 480 else if (isDependentScopeSpecifier(*SS)) { 481 unsigned DiagID = diag::err_typename_missing; 482 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 483 DiagID = diag::warn_typename_missing; 484 485 Diag(SS->getRange().getBegin(), DiagID) 486 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName() 487 << SourceRange(SS->getRange().getBegin(), IILoc) 488 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 489 SuggestedType = ActOnTypenameType(S, SourceLocation(), 490 *SS, *II, IILoc).get(); 491 } else { 492 assert(SS && SS->isInvalid() && 493 "Invalid scope specifier has already been diagnosed"); 494 } 495 496 return true; 497 } 498 499 /// \brief Determine whether the given result set contains either a type name 500 /// or 501 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 502 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 503 NextToken.is(tok::less); 504 505 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 506 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 507 return true; 508 509 if (CheckTemplate && isa<TemplateDecl>(*I)) 510 return true; 511 } 512 513 return false; 514 } 515 516 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 517 Scope *S, CXXScopeSpec &SS, 518 IdentifierInfo *&Name, 519 SourceLocation NameLoc) { 520 Result.clear(Sema::LookupTagName); 521 SemaRef.LookupParsedName(Result, S, &SS); 522 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) { 523 const char *TagName = 0; 524 const char *FixItTagName = 0; 525 switch (Tag->getTagKind()) { 526 case TTK_Class: 527 TagName = "class"; 528 FixItTagName = "class "; 529 break; 530 531 case TTK_Enum: 532 TagName = "enum"; 533 FixItTagName = "enum "; 534 break; 535 536 case TTK_Struct: 537 TagName = "struct"; 538 FixItTagName = "struct "; 539 break; 540 541 case TTK_Union: 542 TagName = "union"; 543 FixItTagName = "union "; 544 break; 545 } 546 547 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 548 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 549 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 550 551 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupOrdinaryName); 552 if (SemaRef.LookupParsedName(R, S, &SS)) { 553 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); 554 I != IEnd; ++I) 555 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 556 << Name << TagName; 557 } 558 return true; 559 } 560 561 Result.clear(Sema::LookupOrdinaryName); 562 return false; 563 } 564 565 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 566 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 567 QualType T, SourceLocation NameLoc) { 568 ASTContext &Context = S.Context; 569 570 TypeLocBuilder Builder; 571 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 572 573 T = S.getElaboratedType(ETK_None, SS, T); 574 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 575 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 576 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 577 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 578 } 579 580 Sema::NameClassification Sema::ClassifyName(Scope *S, 581 CXXScopeSpec &SS, 582 IdentifierInfo *&Name, 583 SourceLocation NameLoc, 584 const Token &NextToken, 585 bool IsAddressOfOperand, 586 CorrectionCandidateCallback *CCC) { 587 DeclarationNameInfo NameInfo(Name, NameLoc); 588 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 589 590 if (NextToken.is(tok::coloncolon)) { 591 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 592 QualType(), false, SS, 0, false); 593 594 } 595 596 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 597 LookupParsedName(Result, S, &SS, !CurMethod); 598 599 // Perform lookup for Objective-C instance variables (including automatically 600 // synthesized instance variables), if we're in an Objective-C method. 601 // FIXME: This lookup really, really needs to be folded in to the normal 602 // unqualified lookup mechanism. 603 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 604 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 605 if (E.get() || E.isInvalid()) 606 return E; 607 } 608 609 bool SecondTry = false; 610 bool IsFilteredTemplateName = false; 611 612 Corrected: 613 switch (Result.getResultKind()) { 614 case LookupResult::NotFound: 615 // If an unqualified-id is followed by a '(', then we have a function 616 // call. 617 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 618 // In C++, this is an ADL-only call. 619 // FIXME: Reference? 620 if (getLangOpts().CPlusPlus) 621 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 622 623 // C90 6.3.2.2: 624 // If the expression that precedes the parenthesized argument list in a 625 // function call consists solely of an identifier, and if no 626 // declaration is visible for this identifier, the identifier is 627 // implicitly declared exactly as if, in the innermost block containing 628 // the function call, the declaration 629 // 630 // extern int identifier (); 631 // 632 // appeared. 633 // 634 // We also allow this in C99 as an extension. 635 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 636 Result.addDecl(D); 637 Result.resolveKind(); 638 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 639 } 640 } 641 642 // In C, we first see whether there is a tag type by the same name, in 643 // which case it's likely that the user just forget to write "enum", 644 // "struct", or "union". 645 if (!getLangOpts().CPlusPlus && !SecondTry && 646 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 647 break; 648 } 649 650 // Perform typo correction to determine if there is another name that is 651 // close to this name. 652 if (!SecondTry && CCC) { 653 SecondTry = true; 654 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 655 Result.getLookupKind(), S, 656 &SS, *CCC)) { 657 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 658 unsigned QualifiedDiag = diag::err_no_member_suggest; 659 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 660 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 661 662 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 663 NamedDecl *UnderlyingFirstDecl 664 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 665 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 666 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 667 UnqualifiedDiag = diag::err_no_template_suggest; 668 QualifiedDiag = diag::err_no_member_template_suggest; 669 } else if (UnderlyingFirstDecl && 670 (isa<TypeDecl>(UnderlyingFirstDecl) || 671 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 672 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 673 UnqualifiedDiag = diag::err_unknown_typename_suggest; 674 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 675 } 676 677 if (SS.isEmpty()) 678 Diag(NameLoc, UnqualifiedDiag) 679 << Name << CorrectedQuotedStr 680 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 681 else 682 Diag(NameLoc, QualifiedDiag) 683 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 684 << SS.getRange() 685 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 686 687 // Update the name, so that the caller has the new name. 688 Name = Corrected.getCorrectionAsIdentifierInfo(); 689 690 // Typo correction corrected to a keyword. 691 if (Corrected.isKeyword()) 692 return Corrected.getCorrectionAsIdentifierInfo(); 693 694 // Also update the LookupResult... 695 // FIXME: This should probably go away at some point 696 Result.clear(); 697 Result.setLookupName(Corrected.getCorrection()); 698 if (FirstDecl) { 699 Result.addDecl(FirstDecl); 700 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 701 << CorrectedQuotedStr; 702 } 703 704 // If we found an Objective-C instance variable, let 705 // LookupInObjCMethod build the appropriate expression to 706 // reference the ivar. 707 // FIXME: This is a gross hack. 708 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 709 Result.clear(); 710 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 711 return move(E); 712 } 713 714 goto Corrected; 715 } 716 } 717 718 // We failed to correct; just fall through and let the parser deal with it. 719 Result.suppressDiagnostics(); 720 return NameClassification::Unknown(); 721 722 case LookupResult::NotFoundInCurrentInstantiation: { 723 // We performed name lookup into the current instantiation, and there were 724 // dependent bases, so we treat this result the same way as any other 725 // dependent nested-name-specifier. 726 727 // C++ [temp.res]p2: 728 // A name used in a template declaration or definition and that is 729 // dependent on a template-parameter is assumed not to name a type 730 // unless the applicable name lookup finds a type name or the name is 731 // qualified by the keyword typename. 732 // 733 // FIXME: If the next token is '<', we might want to ask the parser to 734 // perform some heroics to see if we actually have a 735 // template-argument-list, which would indicate a missing 'template' 736 // keyword here. 737 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 738 NameInfo, IsAddressOfOperand, 739 /*TemplateArgs=*/0); 740 } 741 742 case LookupResult::Found: 743 case LookupResult::FoundOverloaded: 744 case LookupResult::FoundUnresolvedValue: 745 break; 746 747 case LookupResult::Ambiguous: 748 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 749 hasAnyAcceptableTemplateNames(Result)) { 750 // C++ [temp.local]p3: 751 // A lookup that finds an injected-class-name (10.2) can result in an 752 // ambiguity in certain cases (for example, if it is found in more than 753 // one base class). If all of the injected-class-names that are found 754 // refer to specializations of the same class template, and if the name 755 // is followed by a template-argument-list, the reference refers to the 756 // class template itself and not a specialization thereof, and is not 757 // ambiguous. 758 // 759 // This filtering can make an ambiguous result into an unambiguous one, 760 // so try again after filtering out template names. 761 FilterAcceptableTemplateNames(Result); 762 if (!Result.isAmbiguous()) { 763 IsFilteredTemplateName = true; 764 break; 765 } 766 } 767 768 // Diagnose the ambiguity and return an error. 769 return NameClassification::Error(); 770 } 771 772 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 773 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 774 // C++ [temp.names]p3: 775 // After name lookup (3.4) finds that a name is a template-name or that 776 // an operator-function-id or a literal- operator-id refers to a set of 777 // overloaded functions any member of which is a function template if 778 // this is followed by a <, the < is always taken as the delimiter of a 779 // template-argument-list and never as the less-than operator. 780 if (!IsFilteredTemplateName) 781 FilterAcceptableTemplateNames(Result); 782 783 if (!Result.empty()) { 784 bool IsFunctionTemplate; 785 TemplateName Template; 786 if (Result.end() - Result.begin() > 1) { 787 IsFunctionTemplate = true; 788 Template = Context.getOverloadedTemplateName(Result.begin(), 789 Result.end()); 790 } else { 791 TemplateDecl *TD 792 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 793 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 794 795 if (SS.isSet() && !SS.isInvalid()) 796 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 797 /*TemplateKeyword=*/false, 798 TD); 799 else 800 Template = TemplateName(TD); 801 } 802 803 if (IsFunctionTemplate) { 804 // Function templates always go through overload resolution, at which 805 // point we'll perform the various checks (e.g., accessibility) we need 806 // to based on which function we selected. 807 Result.suppressDiagnostics(); 808 809 return NameClassification::FunctionTemplate(Template); 810 } 811 812 return NameClassification::TypeTemplate(Template); 813 } 814 } 815 816 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 817 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 818 DiagnoseUseOfDecl(Type, NameLoc); 819 QualType T = Context.getTypeDeclType(Type); 820 if (SS.isNotEmpty()) 821 return buildNestedType(*this, SS, T, NameLoc); 822 return ParsedType::make(T); 823 } 824 825 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 826 if (!Class) { 827 // FIXME: It's unfortunate that we don't have a Type node for handling this. 828 if (ObjCCompatibleAliasDecl *Alias 829 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 830 Class = Alias->getClassInterface(); 831 } 832 833 if (Class) { 834 DiagnoseUseOfDecl(Class, NameLoc); 835 836 if (NextToken.is(tok::period)) { 837 // Interface. <something> is parsed as a property reference expression. 838 // Just return "unknown" as a fall-through for now. 839 Result.suppressDiagnostics(); 840 return NameClassification::Unknown(); 841 } 842 843 QualType T = Context.getObjCInterfaceType(Class); 844 return ParsedType::make(T); 845 } 846 847 // We can have a type template here if we're classifying a template argument. 848 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 849 return NameClassification::TypeTemplate( 850 TemplateName(cast<TemplateDecl>(FirstDecl))); 851 852 // Check for a tag type hidden by a non-type decl in a few cases where it 853 // seems likely a type is wanted instead of the non-type that was found. 854 if (!getLangOpts().ObjC1) { 855 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 856 if ((NextToken.is(tok::identifier) || 857 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 858 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 859 FirstDecl = (*Result.begin())->getUnderlyingDecl(); 860 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 861 DiagnoseUseOfDecl(Type, NameLoc); 862 QualType T = Context.getTypeDeclType(Type); 863 if (SS.isNotEmpty()) 864 return buildNestedType(*this, SS, T, NameLoc); 865 return ParsedType::make(T); 866 } 867 } 868 } 869 870 if (FirstDecl->isCXXClassMember()) 871 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 872 873 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 874 return BuildDeclarationNameExpr(SS, Result, ADL); 875 } 876 877 // Determines the context to return to after temporarily entering a 878 // context. This depends in an unnecessarily complicated way on the 879 // exact ordering of callbacks from the parser. 880 DeclContext *Sema::getContainingDC(DeclContext *DC) { 881 882 // Functions defined inline within classes aren't parsed until we've 883 // finished parsing the top-level class, so the top-level class is 884 // the context we'll need to return to. 885 if (isa<FunctionDecl>(DC)) { 886 DC = DC->getLexicalParent(); 887 888 // A function not defined within a class will always return to its 889 // lexical context. 890 if (!isa<CXXRecordDecl>(DC)) 891 return DC; 892 893 // A C++ inline method/friend is parsed *after* the topmost class 894 // it was declared in is fully parsed ("complete"); the topmost 895 // class is the context we need to return to. 896 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 897 DC = RD; 898 899 // Return the declaration context of the topmost class the inline method is 900 // declared in. 901 return DC; 902 } 903 904 return DC->getLexicalParent(); 905 } 906 907 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 908 assert(getContainingDC(DC) == CurContext && 909 "The next DeclContext should be lexically contained in the current one."); 910 CurContext = DC; 911 S->setEntity(DC); 912 } 913 914 void Sema::PopDeclContext() { 915 assert(CurContext && "DeclContext imbalance!"); 916 917 CurContext = getContainingDC(CurContext); 918 assert(CurContext && "Popped translation unit!"); 919 } 920 921 /// EnterDeclaratorContext - Used when we must lookup names in the context 922 /// of a declarator's nested name specifier. 923 /// 924 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 925 // C++0x [basic.lookup.unqual]p13: 926 // A name used in the definition of a static data member of class 927 // X (after the qualified-id of the static member) is looked up as 928 // if the name was used in a member function of X. 929 // C++0x [basic.lookup.unqual]p14: 930 // If a variable member of a namespace is defined outside of the 931 // scope of its namespace then any name used in the definition of 932 // the variable member (after the declarator-id) is looked up as 933 // if the definition of the variable member occurred in its 934 // namespace. 935 // Both of these imply that we should push a scope whose context 936 // is the semantic context of the declaration. We can't use 937 // PushDeclContext here because that context is not necessarily 938 // lexically contained in the current context. Fortunately, 939 // the containing scope should have the appropriate information. 940 941 assert(!S->getEntity() && "scope already has entity"); 942 943 #ifndef NDEBUG 944 Scope *Ancestor = S->getParent(); 945 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 946 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 947 #endif 948 949 CurContext = DC; 950 S->setEntity(DC); 951 } 952 953 void Sema::ExitDeclaratorContext(Scope *S) { 954 assert(S->getEntity() == CurContext && "Context imbalance!"); 955 956 // Switch back to the lexical context. The safety of this is 957 // enforced by an assert in EnterDeclaratorContext. 958 Scope *Ancestor = S->getParent(); 959 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 960 CurContext = (DeclContext*) Ancestor->getEntity(); 961 962 // We don't need to do anything with the scope, which is going to 963 // disappear. 964 } 965 966 967 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 968 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 969 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 970 // We assume that the caller has already called 971 // ActOnReenterTemplateScope 972 FD = TFD->getTemplatedDecl(); 973 } 974 if (!FD) 975 return; 976 977 // Same implementation as PushDeclContext, but enters the context 978 // from the lexical parent, rather than the top-level class. 979 assert(CurContext == FD->getLexicalParent() && 980 "The next DeclContext should be lexically contained in the current one."); 981 CurContext = FD; 982 S->setEntity(CurContext); 983 984 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 985 ParmVarDecl *Param = FD->getParamDecl(P); 986 // If the parameter has an identifier, then add it to the scope 987 if (Param->getIdentifier()) { 988 S->AddDecl(Param); 989 IdResolver.AddDecl(Param); 990 } 991 } 992 } 993 994 995 void Sema::ActOnExitFunctionContext() { 996 // Same implementation as PopDeclContext, but returns to the lexical parent, 997 // rather than the top-level class. 998 assert(CurContext && "DeclContext imbalance!"); 999 CurContext = CurContext->getLexicalParent(); 1000 assert(CurContext && "Popped translation unit!"); 1001 } 1002 1003 1004 /// \brief Determine whether we allow overloading of the function 1005 /// PrevDecl with another declaration. 1006 /// 1007 /// This routine determines whether overloading is possible, not 1008 /// whether some new function is actually an overload. It will return 1009 /// true in C++ (where we can always provide overloads) or, as an 1010 /// extension, in C when the previous function is already an 1011 /// overloaded function declaration or has the "overloadable" 1012 /// attribute. 1013 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1014 ASTContext &Context) { 1015 if (Context.getLangOpts().CPlusPlus) 1016 return true; 1017 1018 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1019 return true; 1020 1021 return (Previous.getResultKind() == LookupResult::Found 1022 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1023 } 1024 1025 /// Add this decl to the scope shadowed decl chains. 1026 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1027 // Move up the scope chain until we find the nearest enclosing 1028 // non-transparent context. The declaration will be introduced into this 1029 // scope. 1030 while (S->getEntity() && 1031 ((DeclContext *)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++. 1041 // Out-of-line variable and function definitions shouldn't even in C. 1042 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 1043 D->isOutOfLine() && 1044 !D->getDeclContext()->getRedeclContext()->Equals( 1045 D->getLexicalDeclContext()->getRedeclContext())) 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 ExplicitInstantiationOrSpecialization) { 1094 return IdResolver.isDeclInScope(D, Ctx, Context, S, 1095 ExplicitInstantiationOrSpecialization); 1096 } 1097 1098 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1099 DeclContext *TargetDC = DC->getPrimaryContext(); 1100 do { 1101 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 1102 if (ScopeDC->getPrimaryContext() == TargetDC) 1103 return S; 1104 } while ((S = S->getParent())); 1105 1106 return 0; 1107 } 1108 1109 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1110 DeclContext*, 1111 ASTContext&); 1112 1113 /// Filters out lookup results that don't fall within the given scope 1114 /// as determined by isDeclInScope. 1115 void Sema::FilterLookupForScope(LookupResult &R, 1116 DeclContext *Ctx, Scope *S, 1117 bool ConsiderLinkage, 1118 bool ExplicitInstantiationOrSpecialization) { 1119 LookupResult::Filter F = R.makeFilter(); 1120 while (F.hasNext()) { 1121 NamedDecl *D = F.next(); 1122 1123 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 1124 continue; 1125 1126 if (ConsiderLinkage && 1127 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1128 continue; 1129 1130 F.erase(); 1131 } 1132 1133 F.done(); 1134 } 1135 1136 static bool isUsingDecl(NamedDecl *D) { 1137 return isa<UsingShadowDecl>(D) || 1138 isa<UnresolvedUsingTypenameDecl>(D) || 1139 isa<UnresolvedUsingValueDecl>(D); 1140 } 1141 1142 /// Removes using shadow declarations from the lookup results. 1143 static void RemoveUsingDecls(LookupResult &R) { 1144 LookupResult::Filter F = R.makeFilter(); 1145 while (F.hasNext()) 1146 if (isUsingDecl(F.next())) 1147 F.erase(); 1148 1149 F.done(); 1150 } 1151 1152 /// \brief Check for this common pattern: 1153 /// @code 1154 /// class S { 1155 /// S(const S&); // DO NOT IMPLEMENT 1156 /// void operator=(const S&); // DO NOT IMPLEMENT 1157 /// }; 1158 /// @endcode 1159 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1160 // FIXME: Should check for private access too but access is set after we get 1161 // the decl here. 1162 if (D->doesThisDeclarationHaveABody()) 1163 return false; 1164 1165 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1166 return CD->isCopyConstructor(); 1167 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1168 return Method->isCopyAssignmentOperator(); 1169 return false; 1170 } 1171 1172 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1173 assert(D); 1174 1175 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1176 return false; 1177 1178 // Ignore class templates. 1179 if (D->getDeclContext()->isDependentContext() || 1180 D->getLexicalDeclContext()->isDependentContext()) 1181 return false; 1182 1183 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1184 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1185 return false; 1186 1187 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1188 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1189 return false; 1190 } else { 1191 // 'static inline' functions are used in headers; don't warn. 1192 if (FD->getStorageClass() == SC_Static && 1193 FD->isInlineSpecified()) 1194 return false; 1195 } 1196 1197 if (FD->doesThisDeclarationHaveABody() && 1198 Context.DeclMustBeEmitted(FD)) 1199 return false; 1200 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1201 if (!VD->isFileVarDecl() || 1202 VD->getType().isConstant(Context) || 1203 Context.DeclMustBeEmitted(VD)) 1204 return false; 1205 1206 if (VD->isStaticDataMember() && 1207 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1208 return false; 1209 1210 } else { 1211 return false; 1212 } 1213 1214 // Only warn for unused decls internal to the translation unit. 1215 if (D->getLinkage() == ExternalLinkage) 1216 return false; 1217 1218 return true; 1219 } 1220 1221 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1222 if (!D) 1223 return; 1224 1225 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1226 const FunctionDecl *First = FD->getFirstDeclaration(); 1227 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1228 return; // First should already be in the vector. 1229 } 1230 1231 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1232 const VarDecl *First = VD->getFirstDeclaration(); 1233 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1234 return; // First should already be in the vector. 1235 } 1236 1237 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1238 UnusedFileScopedDecls.push_back(D); 1239 } 1240 1241 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1242 if (D->isInvalidDecl()) 1243 return false; 1244 1245 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1246 return false; 1247 1248 if (isa<LabelDecl>(D)) 1249 return true; 1250 1251 // White-list anything that isn't a local variable. 1252 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1253 !D->getDeclContext()->isFunctionOrMethod()) 1254 return false; 1255 1256 // Types of valid local variables should be complete, so this should succeed. 1257 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1258 1259 // White-list anything with an __attribute__((unused)) type. 1260 QualType Ty = VD->getType(); 1261 1262 // Only look at the outermost level of typedef. 1263 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 1264 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1265 return false; 1266 } 1267 1268 // If we failed to complete the type for some reason, or if the type is 1269 // dependent, don't diagnose the variable. 1270 if (Ty->isIncompleteType() || Ty->isDependentType()) 1271 return false; 1272 1273 if (const TagType *TT = Ty->getAs<TagType>()) { 1274 const TagDecl *Tag = TT->getDecl(); 1275 if (Tag->hasAttr<UnusedAttr>()) 1276 return false; 1277 1278 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1279 if (!RD->hasTrivialDestructor()) 1280 return false; 1281 1282 if (const Expr *Init = VD->getInit()) { 1283 const CXXConstructExpr *Construct = 1284 dyn_cast<CXXConstructExpr>(Init); 1285 if (Construct && !Construct->isElidable()) { 1286 CXXConstructorDecl *CD = Construct->getConstructor(); 1287 if (!CD->isTrivial()) 1288 return false; 1289 } 1290 } 1291 } 1292 } 1293 1294 // TODO: __attribute__((unused)) templates? 1295 } 1296 1297 return true; 1298 } 1299 1300 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1301 FixItHint &Hint) { 1302 if (isa<LabelDecl>(D)) { 1303 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1304 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1305 if (AfterColon.isInvalid()) 1306 return; 1307 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1308 getCharRange(D->getLocStart(), AfterColon)); 1309 } 1310 return; 1311 } 1312 1313 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1314 /// unless they are marked attr(unused). 1315 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1316 FixItHint Hint; 1317 if (!ShouldDiagnoseUnusedDecl(D)) 1318 return; 1319 1320 GenerateFixForUnusedDecl(D, Context, Hint); 1321 1322 unsigned DiagID; 1323 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1324 DiagID = diag::warn_unused_exception_param; 1325 else if (isa<LabelDecl>(D)) 1326 DiagID = diag::warn_unused_label; 1327 else 1328 DiagID = diag::warn_unused_variable; 1329 1330 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1331 } 1332 1333 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1334 // Verify that we have no forward references left. If so, there was a goto 1335 // or address of a label taken, but no definition of it. Label fwd 1336 // definitions are indicated with a null substmt. 1337 if (L->getStmt() == 0) 1338 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1339 } 1340 1341 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1342 if (S->decl_empty()) return; 1343 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1344 "Scope shouldn't contain decls!"); 1345 1346 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1347 I != E; ++I) { 1348 Decl *TmpD = (*I); 1349 assert(TmpD && "This decl didn't get pushed??"); 1350 1351 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1352 NamedDecl *D = cast<NamedDecl>(TmpD); 1353 1354 if (!D->getDeclName()) continue; 1355 1356 // Diagnose unused variables in this scope. 1357 if (!S->hasErrorOccurred()) 1358 DiagnoseUnusedDecl(D); 1359 1360 // If this was a forward reference to a label, verify it was defined. 1361 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1362 CheckPoppedLabel(LD, *this); 1363 1364 // Remove this name from our lexical scope. 1365 IdResolver.RemoveDecl(D); 1366 } 1367 } 1368 1369 void Sema::ActOnStartFunctionDeclarator() { 1370 ++InFunctionDeclarator; 1371 } 1372 1373 void Sema::ActOnEndFunctionDeclarator() { 1374 assert(InFunctionDeclarator); 1375 --InFunctionDeclarator; 1376 } 1377 1378 /// \brief Look for an Objective-C class in the translation unit. 1379 /// 1380 /// \param Id The name of the Objective-C class we're looking for. If 1381 /// typo-correction fixes this name, the Id will be updated 1382 /// to the fixed name. 1383 /// 1384 /// \param IdLoc The location of the name in the translation unit. 1385 /// 1386 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1387 /// if there is no class with the given name. 1388 /// 1389 /// \returns The declaration of the named Objective-C class, or NULL if the 1390 /// class could not be found. 1391 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1392 SourceLocation IdLoc, 1393 bool DoTypoCorrection) { 1394 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1395 // creation from this context. 1396 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1397 1398 if (!IDecl && DoTypoCorrection) { 1399 // Perform typo correction at the given location, but only if we 1400 // find an Objective-C class name. 1401 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1402 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1403 LookupOrdinaryName, TUScope, NULL, 1404 Validator)) { 1405 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1406 Diag(IdLoc, diag::err_undef_interface_suggest) 1407 << Id << IDecl->getDeclName() 1408 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1409 Diag(IDecl->getLocation(), diag::note_previous_decl) 1410 << IDecl->getDeclName(); 1411 1412 Id = IDecl->getIdentifier(); 1413 } 1414 } 1415 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1416 // This routine must always return a class definition, if any. 1417 if (Def && Def->getDefinition()) 1418 Def = Def->getDefinition(); 1419 return Def; 1420 } 1421 1422 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1423 /// from S, where a non-field would be declared. This routine copes 1424 /// with the difference between C and C++ scoping rules in structs and 1425 /// unions. For example, the following code is well-formed in C but 1426 /// ill-formed in C++: 1427 /// @code 1428 /// struct S6 { 1429 /// enum { BAR } e; 1430 /// }; 1431 /// 1432 /// void test_S6() { 1433 /// struct S6 a; 1434 /// a.e = BAR; 1435 /// } 1436 /// @endcode 1437 /// For the declaration of BAR, this routine will return a different 1438 /// scope. The scope S will be the scope of the unnamed enumeration 1439 /// within S6. In C++, this routine will return the scope associated 1440 /// with S6, because the enumeration's scope is a transparent 1441 /// context but structures can contain non-field names. In C, this 1442 /// routine will return the translation unit scope, since the 1443 /// enumeration's scope is a transparent context and structures cannot 1444 /// contain non-field names. 1445 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1446 while (((S->getFlags() & Scope::DeclScope) == 0) || 1447 (S->getEntity() && 1448 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1449 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1450 S = S->getParent(); 1451 return S; 1452 } 1453 1454 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1455 /// file scope. lazily create a decl for it. ForRedeclaration is true 1456 /// if we're creating this built-in in anticipation of redeclaring the 1457 /// built-in. 1458 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1459 Scope *S, bool ForRedeclaration, 1460 SourceLocation Loc) { 1461 Builtin::ID BID = (Builtin::ID)bid; 1462 1463 ASTContext::GetBuiltinTypeError Error; 1464 QualType R = Context.GetBuiltinType(BID, Error); 1465 switch (Error) { 1466 case ASTContext::GE_None: 1467 // Okay 1468 break; 1469 1470 case ASTContext::GE_Missing_stdio: 1471 if (ForRedeclaration) 1472 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1473 << Context.BuiltinInfo.GetName(BID); 1474 return 0; 1475 1476 case ASTContext::GE_Missing_setjmp: 1477 if (ForRedeclaration) 1478 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1479 << Context.BuiltinInfo.GetName(BID); 1480 return 0; 1481 1482 case ASTContext::GE_Missing_ucontext: 1483 if (ForRedeclaration) 1484 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1485 << Context.BuiltinInfo.GetName(BID); 1486 return 0; 1487 } 1488 1489 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1490 Diag(Loc, diag::ext_implicit_lib_function_decl) 1491 << Context.BuiltinInfo.GetName(BID) 1492 << R; 1493 if (Context.BuiltinInfo.getHeaderName(BID) && 1494 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1495 != DiagnosticsEngine::Ignored) 1496 Diag(Loc, diag::note_please_include_header) 1497 << Context.BuiltinInfo.getHeaderName(BID) 1498 << Context.BuiltinInfo.GetName(BID); 1499 } 1500 1501 FunctionDecl *New = FunctionDecl::Create(Context, 1502 Context.getTranslationUnitDecl(), 1503 Loc, Loc, II, R, /*TInfo=*/0, 1504 SC_Extern, 1505 SC_None, false, 1506 /*hasPrototype=*/true); 1507 New->setImplicit(); 1508 1509 // Create Decl objects for each parameter, adding them to the 1510 // FunctionDecl. 1511 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1512 SmallVector<ParmVarDecl*, 16> Params; 1513 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1514 ParmVarDecl *parm = 1515 ParmVarDecl::Create(Context, New, SourceLocation(), 1516 SourceLocation(), 0, 1517 FT->getArgType(i), /*TInfo=*/0, 1518 SC_None, SC_None, 0); 1519 parm->setScopeInfo(0, i); 1520 Params.push_back(parm); 1521 } 1522 New->setParams(Params); 1523 } 1524 1525 AddKnownFunctionAttributes(New); 1526 1527 // TUScope is the translation-unit scope to insert this function into. 1528 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1529 // relate Scopes to DeclContexts, and probably eliminate CurContext 1530 // entirely, but we're not there yet. 1531 DeclContext *SavedContext = CurContext; 1532 CurContext = Context.getTranslationUnitDecl(); 1533 PushOnScopeChains(New, TUScope); 1534 CurContext = SavedContext; 1535 return New; 1536 } 1537 1538 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1539 QualType OldType; 1540 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1541 OldType = OldTypedef->getUnderlyingType(); 1542 else 1543 OldType = Context.getTypeDeclType(Old); 1544 QualType NewType = New->getUnderlyingType(); 1545 1546 if (NewType->isVariablyModifiedType()) { 1547 // Must not redefine a typedef with a variably-modified type. 1548 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1549 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1550 << Kind << NewType; 1551 if (Old->getLocation().isValid()) 1552 Diag(Old->getLocation(), diag::note_previous_definition); 1553 New->setInvalidDecl(); 1554 return true; 1555 } 1556 1557 if (OldType != NewType && 1558 !OldType->isDependentType() && 1559 !NewType->isDependentType() && 1560 !Context.hasSameType(OldType, NewType)) { 1561 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1562 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1563 << Kind << NewType << OldType; 1564 if (Old->getLocation().isValid()) 1565 Diag(Old->getLocation(), diag::note_previous_definition); 1566 New->setInvalidDecl(); 1567 return true; 1568 } 1569 return false; 1570 } 1571 1572 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1573 /// same name and scope as a previous declaration 'Old'. Figure out 1574 /// how to resolve this situation, merging decls or emitting 1575 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1576 /// 1577 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1578 // If the new decl is known invalid already, don't bother doing any 1579 // merging checks. 1580 if (New->isInvalidDecl()) return; 1581 1582 // Allow multiple definitions for ObjC built-in typedefs. 1583 // FIXME: Verify the underlying types are equivalent! 1584 if (getLangOpts().ObjC1) { 1585 const IdentifierInfo *TypeID = New->getIdentifier(); 1586 switch (TypeID->getLength()) { 1587 default: break; 1588 case 2: 1589 { 1590 if (!TypeID->isStr("id")) 1591 break; 1592 QualType T = New->getUnderlyingType(); 1593 if (!T->isPointerType()) 1594 break; 1595 if (!T->isVoidPointerType()) { 1596 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1597 if (!PT->isStructureType()) 1598 break; 1599 } 1600 Context.setObjCIdRedefinitionType(T); 1601 // Install the built-in type for 'id', ignoring the current definition. 1602 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1603 return; 1604 } 1605 case 5: 1606 if (!TypeID->isStr("Class")) 1607 break; 1608 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1609 // Install the built-in type for 'Class', ignoring the current definition. 1610 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1611 return; 1612 case 3: 1613 if (!TypeID->isStr("SEL")) 1614 break; 1615 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1616 // Install the built-in type for 'SEL', ignoring the current definition. 1617 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1618 return; 1619 } 1620 // Fall through - the typedef name was not a builtin type. 1621 } 1622 1623 // Verify the old decl was also a type. 1624 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1625 if (!Old) { 1626 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1627 << New->getDeclName(); 1628 1629 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1630 if (OldD->getLocation().isValid()) 1631 Diag(OldD->getLocation(), diag::note_previous_definition); 1632 1633 return New->setInvalidDecl(); 1634 } 1635 1636 // If the old declaration is invalid, just give up here. 1637 if (Old->isInvalidDecl()) 1638 return New->setInvalidDecl(); 1639 1640 // If the typedef types are not identical, reject them in all languages and 1641 // with any extensions enabled. 1642 if (isIncompatibleTypedef(Old, New)) 1643 return; 1644 1645 // The types match. Link up the redeclaration chain if the old 1646 // declaration was a typedef. 1647 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1648 New->setPreviousDeclaration(Typedef); 1649 1650 if (getLangOpts().MicrosoftExt) 1651 return; 1652 1653 if (getLangOpts().CPlusPlus) { 1654 // C++ [dcl.typedef]p2: 1655 // In a given non-class scope, a typedef specifier can be used to 1656 // redefine the name of any type declared in that scope to refer 1657 // to the type to which it already refers. 1658 if (!isa<CXXRecordDecl>(CurContext)) 1659 return; 1660 1661 // C++0x [dcl.typedef]p4: 1662 // In a given class scope, a typedef specifier can be used to redefine 1663 // any class-name declared in that scope that is not also a typedef-name 1664 // to refer to the type to which it already refers. 1665 // 1666 // This wording came in via DR424, which was a correction to the 1667 // wording in DR56, which accidentally banned code like: 1668 // 1669 // struct S { 1670 // typedef struct A { } A; 1671 // }; 1672 // 1673 // in the C++03 standard. We implement the C++0x semantics, which 1674 // allow the above but disallow 1675 // 1676 // struct S { 1677 // typedef int I; 1678 // typedef int I; 1679 // }; 1680 // 1681 // since that was the intent of DR56. 1682 if (!isa<TypedefNameDecl>(Old)) 1683 return; 1684 1685 Diag(New->getLocation(), diag::err_redefinition) 1686 << New->getDeclName(); 1687 Diag(Old->getLocation(), diag::note_previous_definition); 1688 return New->setInvalidDecl(); 1689 } 1690 1691 // Modules always permit redefinition of typedefs, as does C11. 1692 if (getLangOpts().Modules || getLangOpts().C11) 1693 return; 1694 1695 // If we have a redefinition of a typedef in C, emit a warning. This warning 1696 // is normally mapped to an error, but can be controlled with 1697 // -Wtypedef-redefinition. If either the original or the redefinition is 1698 // in a system header, don't emit this for compatibility with GCC. 1699 if (getDiagnostics().getSuppressSystemWarnings() && 1700 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1701 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1702 return; 1703 1704 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1705 << New->getDeclName(); 1706 Diag(Old->getLocation(), diag::note_previous_definition); 1707 return; 1708 } 1709 1710 /// DeclhasAttr - returns true if decl Declaration already has the target 1711 /// attribute. 1712 static bool 1713 DeclHasAttr(const Decl *D, const Attr *A) { 1714 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1715 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1716 // responsible for making sure they are consistent. 1717 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1718 if (AA) 1719 return false; 1720 1721 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1722 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1723 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1724 if ((*i)->getKind() == A->getKind()) { 1725 if (Ann) { 1726 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1727 return true; 1728 continue; 1729 } 1730 // FIXME: Don't hardcode this check 1731 if (OA && isa<OwnershipAttr>(*i)) 1732 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1733 return true; 1734 } 1735 1736 return false; 1737 } 1738 1739 bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) { 1740 InheritableAttr *NewAttr = NULL; 1741 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1742 NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1743 AA->getIntroduced(), AA->getDeprecated(), 1744 AA->getObsoleted(), AA->getUnavailable(), 1745 AA->getMessage()); 1746 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1747 NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility()); 1748 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1749 NewAttr = mergeDLLImportAttr(D, ImportA->getRange()); 1750 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1751 NewAttr = mergeDLLExportAttr(D, ExportA->getRange()); 1752 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1753 NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(), 1754 FA->getFormatIdx(), FA->getFirstArg()); 1755 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1756 NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName()); 1757 else if (!DeclHasAttr(D, Attr)) 1758 NewAttr = cast<InheritableAttr>(Attr->clone(Context)); 1759 1760 if (NewAttr) { 1761 NewAttr->setInherited(true); 1762 D->addAttr(NewAttr); 1763 return true; 1764 } 1765 1766 return false; 1767 } 1768 1769 static const Decl *getDefinition(const Decl *D) { 1770 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1771 return TD->getDefinition(); 1772 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1773 return VD->getDefinition(); 1774 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1775 const FunctionDecl* Def; 1776 if (FD->hasBody(Def)) 1777 return Def; 1778 } 1779 return NULL; 1780 } 1781 1782 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 1783 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 1784 I != E; ++I) { 1785 Attr *Attribute = *I; 1786 if (Attribute->getKind() == Kind) 1787 return true; 1788 } 1789 return false; 1790 } 1791 1792 /// checkNewAttributesAfterDef - If we already have a definition, check that 1793 /// there are no new attributes in this declaration. 1794 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 1795 if (!New->hasAttrs()) 1796 return; 1797 1798 const Decl *Def = getDefinition(Old); 1799 if (!Def || Def == New) 1800 return; 1801 1802 AttrVec &NewAttributes = New->getAttrs(); 1803 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 1804 const Attr *NewAttribute = NewAttributes[I]; 1805 if (hasAttribute(Def, NewAttribute->getKind())) { 1806 ++I; 1807 continue; // regular attr merging will take care of validating this. 1808 } 1809 S.Diag(NewAttribute->getLocation(), 1810 diag::warn_attribute_precede_definition); 1811 S.Diag(Def->getLocation(), diag::note_previous_definition); 1812 NewAttributes.erase(NewAttributes.begin() + I); 1813 --E; 1814 } 1815 } 1816 1817 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 1818 void Sema::mergeDeclAttributes(Decl *New, Decl *Old, 1819 bool MergeDeprecation) { 1820 // attributes declared post-definition are currently ignored 1821 checkNewAttributesAfterDef(*this, New, Old); 1822 1823 if (!Old->hasAttrs()) 1824 return; 1825 1826 bool foundAny = New->hasAttrs(); 1827 1828 // Ensure that any moving of objects within the allocated map is done before 1829 // we process them. 1830 if (!foundAny) New->setAttrs(AttrVec()); 1831 1832 for (specific_attr_iterator<InheritableAttr> 1833 i = Old->specific_attr_begin<InheritableAttr>(), 1834 e = Old->specific_attr_end<InheritableAttr>(); 1835 i != e; ++i) { 1836 // Ignore deprecated/unavailable/availability attributes if requested. 1837 if (!MergeDeprecation && 1838 (isa<DeprecatedAttr>(*i) || 1839 isa<UnavailableAttr>(*i) || 1840 isa<AvailabilityAttr>(*i))) 1841 continue; 1842 1843 if (mergeDeclAttribute(New, *i)) 1844 foundAny = true; 1845 } 1846 1847 if (!foundAny) New->dropAttrs(); 1848 } 1849 1850 /// mergeParamDeclAttributes - Copy attributes from the old parameter 1851 /// to the new one. 1852 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 1853 const ParmVarDecl *oldDecl, 1854 ASTContext &C) { 1855 if (!oldDecl->hasAttrs()) 1856 return; 1857 1858 bool foundAny = newDecl->hasAttrs(); 1859 1860 // Ensure that any moving of objects within the allocated map is 1861 // done before we process them. 1862 if (!foundAny) newDecl->setAttrs(AttrVec()); 1863 1864 for (specific_attr_iterator<InheritableParamAttr> 1865 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 1866 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 1867 if (!DeclHasAttr(newDecl, *i)) { 1868 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 1869 newAttr->setInherited(true); 1870 newDecl->addAttr(newAttr); 1871 foundAny = true; 1872 } 1873 } 1874 1875 if (!foundAny) newDecl->dropAttrs(); 1876 } 1877 1878 namespace { 1879 1880 /// Used in MergeFunctionDecl to keep track of function parameters in 1881 /// C. 1882 struct GNUCompatibleParamWarning { 1883 ParmVarDecl *OldParm; 1884 ParmVarDecl *NewParm; 1885 QualType PromotedType; 1886 }; 1887 1888 } 1889 1890 /// getSpecialMember - get the special member enum for a method. 1891 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1892 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1893 if (Ctor->isDefaultConstructor()) 1894 return Sema::CXXDefaultConstructor; 1895 1896 if (Ctor->isCopyConstructor()) 1897 return Sema::CXXCopyConstructor; 1898 1899 if (Ctor->isMoveConstructor()) 1900 return Sema::CXXMoveConstructor; 1901 } else if (isa<CXXDestructorDecl>(MD)) { 1902 return Sema::CXXDestructor; 1903 } else if (MD->isCopyAssignmentOperator()) { 1904 return Sema::CXXCopyAssignment; 1905 } else if (MD->isMoveAssignmentOperator()) { 1906 return Sema::CXXMoveAssignment; 1907 } 1908 1909 return Sema::CXXInvalid; 1910 } 1911 1912 /// canRedefineFunction - checks if a function can be redefined. Currently, 1913 /// only extern inline functions can be redefined, and even then only in 1914 /// GNU89 mode. 1915 static bool canRedefineFunction(const FunctionDecl *FD, 1916 const LangOptions& LangOpts) { 1917 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 1918 !LangOpts.CPlusPlus && 1919 FD->isInlineSpecified() && 1920 FD->getStorageClass() == SC_Extern); 1921 } 1922 1923 /// MergeFunctionDecl - We just parsed a function 'New' from 1924 /// declarator D which has the same name and scope as a previous 1925 /// declaration 'Old'. Figure out how to resolve this situation, 1926 /// merging decls or emitting diagnostics as appropriate. 1927 /// 1928 /// In C++, New and Old must be declarations that are not 1929 /// overloaded. Use IsOverload to determine whether New and Old are 1930 /// overloaded, and to select the Old declaration that New should be 1931 /// merged with. 1932 /// 1933 /// Returns true if there was an error, false otherwise. 1934 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) { 1935 // Verify the old decl was also a function. 1936 FunctionDecl *Old = 0; 1937 if (FunctionTemplateDecl *OldFunctionTemplate 1938 = dyn_cast<FunctionTemplateDecl>(OldD)) 1939 Old = OldFunctionTemplate->getTemplatedDecl(); 1940 else 1941 Old = dyn_cast<FunctionDecl>(OldD); 1942 if (!Old) { 1943 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 1944 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 1945 Diag(Shadow->getTargetDecl()->getLocation(), 1946 diag::note_using_decl_target); 1947 Diag(Shadow->getUsingDecl()->getLocation(), 1948 diag::note_using_decl) << 0; 1949 return true; 1950 } 1951 1952 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1953 << New->getDeclName(); 1954 Diag(OldD->getLocation(), diag::note_previous_definition); 1955 return true; 1956 } 1957 1958 // Determine whether the previous declaration was a definition, 1959 // implicit declaration, or a declaration. 1960 diag::kind PrevDiag; 1961 if (Old->isThisDeclarationADefinition()) 1962 PrevDiag = diag::note_previous_definition; 1963 else if (Old->isImplicit()) 1964 PrevDiag = diag::note_previous_implicit_declaration; 1965 else 1966 PrevDiag = diag::note_previous_declaration; 1967 1968 QualType OldQType = Context.getCanonicalType(Old->getType()); 1969 QualType NewQType = Context.getCanonicalType(New->getType()); 1970 1971 // Don't complain about this if we're in GNU89 mode and the old function 1972 // is an extern inline function. 1973 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 1974 New->getStorageClass() == SC_Static && 1975 Old->getStorageClass() != SC_Static && 1976 !canRedefineFunction(Old, getLangOpts())) { 1977 if (getLangOpts().MicrosoftExt) { 1978 Diag(New->getLocation(), diag::warn_static_non_static) << New; 1979 Diag(Old->getLocation(), PrevDiag); 1980 } else { 1981 Diag(New->getLocation(), diag::err_static_non_static) << New; 1982 Diag(Old->getLocation(), PrevDiag); 1983 return true; 1984 } 1985 } 1986 1987 // If a function is first declared with a calling convention, but is 1988 // later declared or defined without one, the second decl assumes the 1989 // calling convention of the first. 1990 // 1991 // For the new decl, we have to look at the NON-canonical type to tell the 1992 // difference between a function that really doesn't have a calling 1993 // convention and one that is declared cdecl. That's because in 1994 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 1995 // because it is the default calling convention. 1996 // 1997 // Note also that we DO NOT return at this point, because we still have 1998 // other tests to run. 1999 const FunctionType *OldType = cast<FunctionType>(OldQType); 2000 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 2001 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2002 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2003 bool RequiresAdjustment = false; 2004 if (OldTypeInfo.getCC() != CC_Default && 2005 NewTypeInfo.getCC() == CC_Default) { 2006 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2007 RequiresAdjustment = true; 2008 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 2009 NewTypeInfo.getCC())) { 2010 // Calling conventions really aren't compatible, so complain. 2011 Diag(New->getLocation(), diag::err_cconv_change) 2012 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2013 << (OldTypeInfo.getCC() == CC_Default) 2014 << (OldTypeInfo.getCC() == CC_Default ? "" : 2015 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 2016 Diag(Old->getLocation(), diag::note_previous_declaration); 2017 return true; 2018 } 2019 2020 // FIXME: diagnose the other way around? 2021 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2022 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2023 RequiresAdjustment = true; 2024 } 2025 2026 // Merge regparm attribute. 2027 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2028 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2029 if (NewTypeInfo.getHasRegParm()) { 2030 Diag(New->getLocation(), diag::err_regparm_mismatch) 2031 << NewType->getRegParmType() 2032 << OldType->getRegParmType(); 2033 Diag(Old->getLocation(), diag::note_previous_declaration); 2034 return true; 2035 } 2036 2037 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2038 RequiresAdjustment = true; 2039 } 2040 2041 // Merge ns_returns_retained attribute. 2042 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2043 if (NewTypeInfo.getProducesResult()) { 2044 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2045 Diag(Old->getLocation(), diag::note_previous_declaration); 2046 return true; 2047 } 2048 2049 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2050 RequiresAdjustment = true; 2051 } 2052 2053 if (RequiresAdjustment) { 2054 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 2055 New->setType(QualType(NewType, 0)); 2056 NewQType = Context.getCanonicalType(New->getType()); 2057 } 2058 2059 if (getLangOpts().CPlusPlus) { 2060 // (C++98 13.1p2): 2061 // Certain function declarations cannot be overloaded: 2062 // -- Function declarations that differ only in the return type 2063 // cannot be overloaded. 2064 QualType OldReturnType = OldType->getResultType(); 2065 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2066 QualType ResQT; 2067 if (OldReturnType != NewReturnType) { 2068 if (NewReturnType->isObjCObjectPointerType() 2069 && OldReturnType->isObjCObjectPointerType()) 2070 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2071 if (ResQT.isNull()) { 2072 if (New->isCXXClassMember() && New->isOutOfLine()) 2073 Diag(New->getLocation(), 2074 diag::err_member_def_does_not_match_ret_type) << New; 2075 else 2076 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2077 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2078 return true; 2079 } 2080 else 2081 NewQType = ResQT; 2082 } 2083 2084 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 2085 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 2086 if (OldMethod && NewMethod) { 2087 // Preserve triviality. 2088 NewMethod->setTrivial(OldMethod->isTrivial()); 2089 2090 // MSVC allows explicit template specialization at class scope: 2091 // 2 CXMethodDecls referring to the same function will be injected. 2092 // We don't want a redeclartion error. 2093 bool IsClassScopeExplicitSpecialization = 2094 OldMethod->isFunctionTemplateSpecialization() && 2095 NewMethod->isFunctionTemplateSpecialization(); 2096 bool isFriend = NewMethod->getFriendObjectKind(); 2097 2098 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2099 !IsClassScopeExplicitSpecialization) { 2100 // -- Member function declarations with the same name and the 2101 // same parameter types cannot be overloaded if any of them 2102 // is a static member function declaration. 2103 if (OldMethod->isStatic() || NewMethod->isStatic()) { 2104 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2105 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2106 return true; 2107 } 2108 2109 // C++ [class.mem]p1: 2110 // [...] A member shall not be declared twice in the 2111 // member-specification, except that a nested class or member 2112 // class template can be declared and then later defined. 2113 if (ActiveTemplateInstantiations.empty()) { 2114 unsigned NewDiag; 2115 if (isa<CXXConstructorDecl>(OldMethod)) 2116 NewDiag = diag::err_constructor_redeclared; 2117 else if (isa<CXXDestructorDecl>(NewMethod)) 2118 NewDiag = diag::err_destructor_redeclared; 2119 else if (isa<CXXConversionDecl>(NewMethod)) 2120 NewDiag = diag::err_conv_function_redeclared; 2121 else 2122 NewDiag = diag::err_member_redeclared; 2123 2124 Diag(New->getLocation(), NewDiag); 2125 } else { 2126 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2127 << New << New->getType(); 2128 } 2129 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2130 2131 // Complain if this is an explicit declaration of a special 2132 // member that was initially declared implicitly. 2133 // 2134 // As an exception, it's okay to befriend such methods in order 2135 // to permit the implicit constructor/destructor/operator calls. 2136 } else if (OldMethod->isImplicit()) { 2137 if (isFriend) { 2138 NewMethod->setImplicit(); 2139 } else { 2140 Diag(NewMethod->getLocation(), 2141 diag::err_definition_of_implicitly_declared_member) 2142 << New << getSpecialMember(OldMethod); 2143 return true; 2144 } 2145 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2146 Diag(NewMethod->getLocation(), 2147 diag::err_definition_of_explicitly_defaulted_member) 2148 << getSpecialMember(OldMethod); 2149 return true; 2150 } 2151 } 2152 2153 // (C++98 8.3.5p3): 2154 // All declarations for a function shall agree exactly in both the 2155 // return type and the parameter-type-list. 2156 // We also want to respect all the extended bits except noreturn. 2157 2158 // noreturn should now match unless the old type info didn't have it. 2159 QualType OldQTypeForComparison = OldQType; 2160 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2161 assert(OldQType == QualType(OldType, 0)); 2162 const FunctionType *OldTypeForComparison 2163 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2164 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2165 assert(OldQTypeForComparison.isCanonical()); 2166 } 2167 2168 if (OldQTypeForComparison == NewQType) 2169 return MergeCompatibleFunctionDecls(New, Old, S); 2170 2171 // Fall through for conflicting redeclarations and redefinitions. 2172 } 2173 2174 // C: Function types need to be compatible, not identical. This handles 2175 // duplicate function decls like "void f(int); void f(enum X);" properly. 2176 if (!getLangOpts().CPlusPlus && 2177 Context.typesAreCompatible(OldQType, NewQType)) { 2178 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2179 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2180 const FunctionProtoType *OldProto = 0; 2181 if (isa<FunctionNoProtoType>(NewFuncType) && 2182 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2183 // The old declaration provided a function prototype, but the 2184 // new declaration does not. Merge in the prototype. 2185 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2186 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2187 OldProto->arg_type_end()); 2188 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2189 ParamTypes.data(), ParamTypes.size(), 2190 OldProto->getExtProtoInfo()); 2191 New->setType(NewQType); 2192 New->setHasInheritedPrototype(); 2193 2194 // Synthesize a parameter for each argument type. 2195 SmallVector<ParmVarDecl*, 16> Params; 2196 for (FunctionProtoType::arg_type_iterator 2197 ParamType = OldProto->arg_type_begin(), 2198 ParamEnd = OldProto->arg_type_end(); 2199 ParamType != ParamEnd; ++ParamType) { 2200 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2201 SourceLocation(), 2202 SourceLocation(), 0, 2203 *ParamType, /*TInfo=*/0, 2204 SC_None, SC_None, 2205 0); 2206 Param->setScopeInfo(0, Params.size()); 2207 Param->setImplicit(); 2208 Params.push_back(Param); 2209 } 2210 2211 New->setParams(Params); 2212 } 2213 2214 return MergeCompatibleFunctionDecls(New, Old, S); 2215 } 2216 2217 // GNU C permits a K&R definition to follow a prototype declaration 2218 // if the declared types of the parameters in the K&R definition 2219 // match the types in the prototype declaration, even when the 2220 // promoted types of the parameters from the K&R definition differ 2221 // from the types in the prototype. GCC then keeps the types from 2222 // the prototype. 2223 // 2224 // If a variadic prototype is followed by a non-variadic K&R definition, 2225 // the K&R definition becomes variadic. This is sort of an edge case, but 2226 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2227 // C99 6.9.1p8. 2228 if (!getLangOpts().CPlusPlus && 2229 Old->hasPrototype() && !New->hasPrototype() && 2230 New->getType()->getAs<FunctionProtoType>() && 2231 Old->getNumParams() == New->getNumParams()) { 2232 SmallVector<QualType, 16> ArgTypes; 2233 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2234 const FunctionProtoType *OldProto 2235 = Old->getType()->getAs<FunctionProtoType>(); 2236 const FunctionProtoType *NewProto 2237 = New->getType()->getAs<FunctionProtoType>(); 2238 2239 // Determine whether this is the GNU C extension. 2240 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2241 NewProto->getResultType()); 2242 bool LooseCompatible = !MergedReturn.isNull(); 2243 for (unsigned Idx = 0, End = Old->getNumParams(); 2244 LooseCompatible && Idx != End; ++Idx) { 2245 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2246 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2247 if (Context.typesAreCompatible(OldParm->getType(), 2248 NewProto->getArgType(Idx))) { 2249 ArgTypes.push_back(NewParm->getType()); 2250 } else if (Context.typesAreCompatible(OldParm->getType(), 2251 NewParm->getType(), 2252 /*CompareUnqualified=*/true)) { 2253 GNUCompatibleParamWarning Warn 2254 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2255 Warnings.push_back(Warn); 2256 ArgTypes.push_back(NewParm->getType()); 2257 } else 2258 LooseCompatible = false; 2259 } 2260 2261 if (LooseCompatible) { 2262 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2263 Diag(Warnings[Warn].NewParm->getLocation(), 2264 diag::ext_param_promoted_not_compatible_with_prototype) 2265 << Warnings[Warn].PromotedType 2266 << Warnings[Warn].OldParm->getType(); 2267 if (Warnings[Warn].OldParm->getLocation().isValid()) 2268 Diag(Warnings[Warn].OldParm->getLocation(), 2269 diag::note_previous_declaration); 2270 } 2271 2272 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 2273 ArgTypes.size(), 2274 OldProto->getExtProtoInfo())); 2275 return MergeCompatibleFunctionDecls(New, Old, S); 2276 } 2277 2278 // Fall through to diagnose conflicting types. 2279 } 2280 2281 // A function that has already been declared has been redeclared or defined 2282 // with a different type- show appropriate diagnostic 2283 if (unsigned BuiltinID = Old->getBuiltinID()) { 2284 // The user has declared a builtin function with an incompatible 2285 // signature. 2286 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2287 // The function the user is redeclaring is a library-defined 2288 // function like 'malloc' or 'printf'. Warn about the 2289 // redeclaration, then pretend that we don't know about this 2290 // library built-in. 2291 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2292 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2293 << Old << Old->getType(); 2294 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2295 Old->setInvalidDecl(); 2296 return false; 2297 } 2298 2299 PrevDiag = diag::note_previous_builtin_declaration; 2300 } 2301 2302 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2303 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2304 return true; 2305 } 2306 2307 /// \brief Completes the merge of two function declarations that are 2308 /// known to be compatible. 2309 /// 2310 /// This routine handles the merging of attributes and other 2311 /// properties of function declarations form the old declaration to 2312 /// the new declaration, once we know that New is in fact a 2313 /// redeclaration of Old. 2314 /// 2315 /// \returns false 2316 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2317 Scope *S) { 2318 // Merge the attributes 2319 mergeDeclAttributes(New, Old); 2320 2321 // Merge the storage class. 2322 if (Old->getStorageClass() != SC_Extern && 2323 Old->getStorageClass() != SC_None) 2324 New->setStorageClass(Old->getStorageClass()); 2325 2326 // Merge "pure" flag. 2327 if (Old->isPure()) 2328 New->setPure(); 2329 2330 // Merge attributes from the parameters. These can mismatch with K&R 2331 // declarations. 2332 if (New->getNumParams() == Old->getNumParams()) 2333 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2334 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2335 Context); 2336 2337 if (getLangOpts().CPlusPlus) 2338 return MergeCXXFunctionDecl(New, Old, S); 2339 2340 return false; 2341 } 2342 2343 2344 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2345 ObjCMethodDecl *oldMethod) { 2346 2347 // Merge the attributes, including deprecated/unavailable 2348 mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true); 2349 2350 // Merge attributes from the parameters. 2351 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2352 oe = oldMethod->param_end(); 2353 for (ObjCMethodDecl::param_iterator 2354 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2355 ni != ne && oi != oe; ++ni, ++oi) 2356 mergeParamDeclAttributes(*ni, *oi, Context); 2357 2358 CheckObjCMethodOverride(newMethod, oldMethod, true); 2359 } 2360 2361 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2362 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2363 /// emitting diagnostics as appropriate. 2364 /// 2365 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2366 /// to here in AddInitializerToDecl. We can't check them before the initializer 2367 /// is attached. 2368 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 2369 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2370 return; 2371 2372 QualType MergedT; 2373 if (getLangOpts().CPlusPlus) { 2374 AutoType *AT = New->getType()->getContainedAutoType(); 2375 if (AT && !AT->isDeduced()) { 2376 // We don't know what the new type is until the initializer is attached. 2377 return; 2378 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2379 // These could still be something that needs exception specs checked. 2380 return MergeVarDeclExceptionSpecs(New, Old); 2381 } 2382 // C++ [basic.link]p10: 2383 // [...] the types specified by all declarations referring to a given 2384 // object or function shall be identical, except that declarations for an 2385 // array object can specify array types that differ by the presence or 2386 // absence of a major array bound (8.3.4). 2387 else if (Old->getType()->isIncompleteArrayType() && 2388 New->getType()->isArrayType()) { 2389 CanQual<ArrayType> OldArray 2390 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2391 CanQual<ArrayType> NewArray 2392 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2393 if (OldArray->getElementType() == NewArray->getElementType()) 2394 MergedT = New->getType(); 2395 } else if (Old->getType()->isArrayType() && 2396 New->getType()->isIncompleteArrayType()) { 2397 CanQual<ArrayType> OldArray 2398 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2399 CanQual<ArrayType> NewArray 2400 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2401 if (OldArray->getElementType() == NewArray->getElementType()) 2402 MergedT = Old->getType(); 2403 } else if (New->getType()->isObjCObjectPointerType() 2404 && Old->getType()->isObjCObjectPointerType()) { 2405 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2406 Old->getType()); 2407 } 2408 } else { 2409 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2410 } 2411 if (MergedT.isNull()) { 2412 Diag(New->getLocation(), diag::err_redefinition_different_type) 2413 << New->getDeclName(); 2414 Diag(Old->getLocation(), diag::note_previous_definition); 2415 return New->setInvalidDecl(); 2416 } 2417 New->setType(MergedT); 2418 } 2419 2420 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2421 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2422 /// situation, merging decls or emitting diagnostics as appropriate. 2423 /// 2424 /// Tentative definition rules (C99 6.9.2p2) are checked by 2425 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2426 /// definitions here, since the initializer hasn't been attached. 2427 /// 2428 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2429 // If the new decl is already invalid, don't do any other checking. 2430 if (New->isInvalidDecl()) 2431 return; 2432 2433 // Verify the old decl was also a variable. 2434 VarDecl *Old = 0; 2435 if (!Previous.isSingleResult() || 2436 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2437 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2438 << New->getDeclName(); 2439 Diag(Previous.getRepresentativeDecl()->getLocation(), 2440 diag::note_previous_definition); 2441 return New->setInvalidDecl(); 2442 } 2443 2444 // C++ [class.mem]p1: 2445 // A member shall not be declared twice in the member-specification [...] 2446 // 2447 // Here, we need only consider static data members. 2448 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2449 Diag(New->getLocation(), diag::err_duplicate_member) 2450 << New->getIdentifier(); 2451 Diag(Old->getLocation(), diag::note_previous_declaration); 2452 New->setInvalidDecl(); 2453 } 2454 2455 mergeDeclAttributes(New, Old); 2456 // Warn if an already-declared variable is made a weak_import in a subsequent 2457 // declaration 2458 if (New->getAttr<WeakImportAttr>() && 2459 Old->getStorageClass() == SC_None && 2460 !Old->getAttr<WeakImportAttr>()) { 2461 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2462 Diag(Old->getLocation(), diag::note_previous_definition); 2463 // Remove weak_import attribute on new declaration. 2464 New->dropAttr<WeakImportAttr>(); 2465 } 2466 2467 // Merge the types. 2468 MergeVarDeclTypes(New, Old); 2469 if (New->isInvalidDecl()) 2470 return; 2471 2472 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2473 if (New->getStorageClass() == SC_Static && 2474 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2475 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2476 Diag(Old->getLocation(), diag::note_previous_definition); 2477 return New->setInvalidDecl(); 2478 } 2479 // C99 6.2.2p4: 2480 // For an identifier declared with the storage-class specifier 2481 // extern in a scope in which a prior declaration of that 2482 // identifier is visible,23) if the prior declaration specifies 2483 // internal or external linkage, the linkage of the identifier at 2484 // the later declaration is the same as the linkage specified at 2485 // the prior declaration. If no prior declaration is visible, or 2486 // if the prior declaration specifies no linkage, then the 2487 // identifier has external linkage. 2488 if (New->hasExternalStorage() && Old->hasLinkage()) 2489 /* Okay */; 2490 else if (New->getStorageClass() != SC_Static && 2491 Old->getStorageClass() == SC_Static) { 2492 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2493 Diag(Old->getLocation(), diag::note_previous_definition); 2494 return New->setInvalidDecl(); 2495 } 2496 2497 // Check if extern is followed by non-extern and vice-versa. 2498 if (New->hasExternalStorage() && 2499 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2500 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2501 Diag(Old->getLocation(), diag::note_previous_definition); 2502 return New->setInvalidDecl(); 2503 } 2504 if (Old->hasExternalStorage() && 2505 !New->hasLinkage() && New->isLocalVarDecl()) { 2506 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2507 Diag(Old->getLocation(), diag::note_previous_definition); 2508 return New->setInvalidDecl(); 2509 } 2510 2511 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2512 2513 // FIXME: The test for external storage here seems wrong? We still 2514 // need to check for mismatches. 2515 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2516 // Don't complain about out-of-line definitions of static members. 2517 !(Old->getLexicalDeclContext()->isRecord() && 2518 !New->getLexicalDeclContext()->isRecord())) { 2519 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2520 Diag(Old->getLocation(), diag::note_previous_definition); 2521 return New->setInvalidDecl(); 2522 } 2523 2524 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2525 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2526 Diag(Old->getLocation(), diag::note_previous_definition); 2527 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2528 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2529 Diag(Old->getLocation(), diag::note_previous_definition); 2530 } 2531 2532 // C++ doesn't have tentative definitions, so go right ahead and check here. 2533 const VarDecl *Def; 2534 if (getLangOpts().CPlusPlus && 2535 New->isThisDeclarationADefinition() == VarDecl::Definition && 2536 (Def = Old->getDefinition())) { 2537 Diag(New->getLocation(), diag::err_redefinition) 2538 << New->getDeclName(); 2539 Diag(Def->getLocation(), diag::note_previous_definition); 2540 New->setInvalidDecl(); 2541 return; 2542 } 2543 // c99 6.2.2 P4. 2544 // For an identifier declared with the storage-class specifier extern in a 2545 // scope in which a prior declaration of that identifier is visible, if 2546 // the prior declaration specifies internal or external linkage, the linkage 2547 // of the identifier at the later declaration is the same as the linkage 2548 // specified at the prior declaration. 2549 // FIXME. revisit this code. 2550 if (New->hasExternalStorage() && 2551 Old->getLinkage() == InternalLinkage && 2552 New->getDeclContext() == Old->getDeclContext()) 2553 New->setStorageClass(Old->getStorageClass()); 2554 2555 // Keep a chain of previous declarations. 2556 New->setPreviousDeclaration(Old); 2557 2558 // Inherit access appropriately. 2559 New->setAccess(Old->getAccess()); 2560 } 2561 2562 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2563 /// no declarator (e.g. "struct foo;") is parsed. 2564 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2565 DeclSpec &DS) { 2566 return ParsedFreeStandingDeclSpec(S, AS, DS, 2567 MultiTemplateParamsArg(*this, 0, 0)); 2568 } 2569 2570 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2571 /// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2572 /// parameters to cope with template friend declarations. 2573 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2574 DeclSpec &DS, 2575 MultiTemplateParamsArg TemplateParams) { 2576 Decl *TagD = 0; 2577 TagDecl *Tag = 0; 2578 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2579 DS.getTypeSpecType() == DeclSpec::TST_struct || 2580 DS.getTypeSpecType() == DeclSpec::TST_union || 2581 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2582 TagD = DS.getRepAsDecl(); 2583 2584 if (!TagD) // We probably had an error 2585 return 0; 2586 2587 // Note that the above type specs guarantee that the 2588 // type rep is a Decl, whereas in many of the others 2589 // it's a Type. 2590 if (isa<TagDecl>(TagD)) 2591 Tag = cast<TagDecl>(TagD); 2592 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 2593 Tag = CTD->getTemplatedDecl(); 2594 } 2595 2596 if (Tag) { 2597 Tag->setFreeStanding(); 2598 if (Tag->isInvalidDecl()) 2599 return Tag; 2600 } 2601 2602 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 2603 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 2604 // or incomplete types shall not be restrict-qualified." 2605 if (TypeQuals & DeclSpec::TQ_restrict) 2606 Diag(DS.getRestrictSpecLoc(), 2607 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 2608 << DS.getSourceRange(); 2609 } 2610 2611 if (DS.isConstexprSpecified()) { 2612 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 2613 // and definitions of functions and variables. 2614 if (Tag) 2615 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 2616 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 2617 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 2618 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3); 2619 else 2620 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 2621 // Don't emit warnings after this error. 2622 return TagD; 2623 } 2624 2625 if (DS.isFriendSpecified()) { 2626 // If we're dealing with a decl but not a TagDecl, assume that 2627 // whatever routines created it handled the friendship aspect. 2628 if (TagD && !Tag) 2629 return 0; 2630 return ActOnFriendTypeDecl(S, DS, TemplateParams); 2631 } 2632 2633 // Track whether we warned about the fact that there aren't any 2634 // declarators. 2635 bool emittedWarning = false; 2636 2637 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 2638 if (!Record->getDeclName() && Record->isCompleteDefinition() && 2639 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 2640 if (getLangOpts().CPlusPlus || 2641 Record->getDeclContext()->isRecord()) 2642 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 2643 2644 Diag(DS.getLocStart(), diag::ext_no_declarators) 2645 << DS.getSourceRange(); 2646 emittedWarning = true; 2647 } 2648 } 2649 2650 // Check for Microsoft C extension: anonymous struct. 2651 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 2652 CurContext->isRecord() && 2653 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 2654 // Handle 2 kinds of anonymous struct: 2655 // struct STRUCT; 2656 // and 2657 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 2658 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 2659 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 2660 (DS.getTypeSpecType() == DeclSpec::TST_typename && 2661 DS.getRepAsType().get()->isStructureType())) { 2662 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 2663 << DS.getSourceRange(); 2664 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 2665 } 2666 } 2667 2668 if (getLangOpts().CPlusPlus && 2669 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 2670 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 2671 if (Enum->enumerator_begin() == Enum->enumerator_end() && 2672 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 2673 Diag(Enum->getLocation(), diag::ext_no_declarators) 2674 << DS.getSourceRange(); 2675 emittedWarning = true; 2676 } 2677 2678 // Skip all the checks below if we have a type error. 2679 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 2680 2681 if (!DS.isMissingDeclaratorOk()) { 2682 // Warn about typedefs of enums without names, since this is an 2683 // extension in both Microsoft and GNU. 2684 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 2685 Tag && isa<EnumDecl>(Tag)) { 2686 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 2687 << DS.getSourceRange(); 2688 return Tag; 2689 } 2690 2691 Diag(DS.getLocStart(), diag::ext_no_declarators) 2692 << DS.getSourceRange(); 2693 emittedWarning = true; 2694 } 2695 2696 // We're going to complain about a bunch of spurious specifiers; 2697 // only do this if we're declaring a tag, because otherwise we 2698 // should be getting diag::ext_no_declarators. 2699 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 2700 return TagD; 2701 2702 // Note that a linkage-specification sets a storage class, but 2703 // 'extern "C" struct foo;' is actually valid and not theoretically 2704 // useless. 2705 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 2706 if (!DS.isExternInLinkageSpec()) 2707 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 2708 << DeclSpec::getSpecifierName(scs); 2709 2710 if (DS.isThreadSpecified()) 2711 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 2712 if (DS.getTypeQualifiers()) { 2713 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2714 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 2715 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2716 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 2717 // Restrict is covered above. 2718 } 2719 if (DS.isInlineSpecified()) 2720 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 2721 if (DS.isVirtualSpecified()) 2722 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 2723 if (DS.isExplicitSpecified()) 2724 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 2725 2726 if (DS.isModulePrivateSpecified() && 2727 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 2728 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 2729 << Tag->getTagKind() 2730 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 2731 2732 // Warn about ignored type attributes, for example: 2733 // __attribute__((aligned)) struct A; 2734 // Attributes should be placed after tag to apply to type declaration. 2735 if (!DS.getAttributes().empty()) { 2736 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 2737 if (TypeSpecType == DeclSpec::TST_class || 2738 TypeSpecType == DeclSpec::TST_struct || 2739 TypeSpecType == DeclSpec::TST_union || 2740 TypeSpecType == DeclSpec::TST_enum) { 2741 AttributeList* attrs = DS.getAttributes().getList(); 2742 while (attrs) { 2743 Diag(attrs->getScopeLoc(), 2744 diag::warn_declspec_attribute_ignored) 2745 << attrs->getName() 2746 << (TypeSpecType == DeclSpec::TST_class ? 0 : 2747 TypeSpecType == DeclSpec::TST_struct ? 1 : 2748 TypeSpecType == DeclSpec::TST_union ? 2 : 3); 2749 attrs = attrs->getNext(); 2750 } 2751 } 2752 } 2753 2754 ActOnDocumentableDecl(TagD); 2755 2756 return TagD; 2757 } 2758 2759 /// We are trying to inject an anonymous member into the given scope; 2760 /// check if there's an existing declaration that can't be overloaded. 2761 /// 2762 /// \return true if this is a forbidden redeclaration 2763 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 2764 Scope *S, 2765 DeclContext *Owner, 2766 DeclarationName Name, 2767 SourceLocation NameLoc, 2768 unsigned diagnostic) { 2769 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 2770 Sema::ForRedeclaration); 2771 if (!SemaRef.LookupName(R, S)) return false; 2772 2773 if (R.getAsSingle<TagDecl>()) 2774 return false; 2775 2776 // Pick a representative declaration. 2777 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 2778 assert(PrevDecl && "Expected a non-null Decl"); 2779 2780 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 2781 return false; 2782 2783 SemaRef.Diag(NameLoc, diagnostic) << Name; 2784 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 2785 2786 return true; 2787 } 2788 2789 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 2790 /// anonymous struct or union AnonRecord into the owning context Owner 2791 /// and scope S. This routine will be invoked just after we realize 2792 /// that an unnamed union or struct is actually an anonymous union or 2793 /// struct, e.g., 2794 /// 2795 /// @code 2796 /// union { 2797 /// int i; 2798 /// float f; 2799 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 2800 /// // f into the surrounding scope.x 2801 /// @endcode 2802 /// 2803 /// This routine is recursive, injecting the names of nested anonymous 2804 /// structs/unions into the owning context and scope as well. 2805 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 2806 DeclContext *Owner, 2807 RecordDecl *AnonRecord, 2808 AccessSpecifier AS, 2809 SmallVector<NamedDecl*, 2> &Chaining, 2810 bool MSAnonStruct) { 2811 unsigned diagKind 2812 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 2813 : diag::err_anonymous_struct_member_redecl; 2814 2815 bool Invalid = false; 2816 2817 // Look every FieldDecl and IndirectFieldDecl with a name. 2818 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 2819 DEnd = AnonRecord->decls_end(); 2820 D != DEnd; ++D) { 2821 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 2822 cast<NamedDecl>(*D)->getDeclName()) { 2823 ValueDecl *VD = cast<ValueDecl>(*D); 2824 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 2825 VD->getLocation(), diagKind)) { 2826 // C++ [class.union]p2: 2827 // The names of the members of an anonymous union shall be 2828 // distinct from the names of any other entity in the 2829 // scope in which the anonymous union is declared. 2830 Invalid = true; 2831 } else { 2832 // C++ [class.union]p2: 2833 // For the purpose of name lookup, after the anonymous union 2834 // definition, the members of the anonymous union are 2835 // considered to have been defined in the scope in which the 2836 // anonymous union is declared. 2837 unsigned OldChainingSize = Chaining.size(); 2838 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 2839 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 2840 PE = IF->chain_end(); PI != PE; ++PI) 2841 Chaining.push_back(*PI); 2842 else 2843 Chaining.push_back(VD); 2844 2845 assert(Chaining.size() >= 2); 2846 NamedDecl **NamedChain = 2847 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 2848 for (unsigned i = 0; i < Chaining.size(); i++) 2849 NamedChain[i] = Chaining[i]; 2850 2851 IndirectFieldDecl* IndirectField = 2852 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 2853 VD->getIdentifier(), VD->getType(), 2854 NamedChain, Chaining.size()); 2855 2856 IndirectField->setAccess(AS); 2857 IndirectField->setImplicit(); 2858 SemaRef.PushOnScopeChains(IndirectField, S); 2859 2860 // That includes picking up the appropriate access specifier. 2861 if (AS != AS_none) IndirectField->setAccess(AS); 2862 2863 Chaining.resize(OldChainingSize); 2864 } 2865 } 2866 } 2867 2868 return Invalid; 2869 } 2870 2871 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 2872 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 2873 /// illegal input values are mapped to SC_None. 2874 static StorageClass 2875 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2876 switch (StorageClassSpec) { 2877 case DeclSpec::SCS_unspecified: return SC_None; 2878 case DeclSpec::SCS_extern: return SC_Extern; 2879 case DeclSpec::SCS_static: return SC_Static; 2880 case DeclSpec::SCS_auto: return SC_Auto; 2881 case DeclSpec::SCS_register: return SC_Register; 2882 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2883 // Illegal SCSs map to None: error reporting is up to the caller. 2884 case DeclSpec::SCS_mutable: // Fall through. 2885 case DeclSpec::SCS_typedef: return SC_None; 2886 } 2887 llvm_unreachable("unknown storage class specifier"); 2888 } 2889 2890 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 2891 /// a StorageClass. Any error reporting is up to the caller: 2892 /// illegal input values are mapped to SC_None. 2893 static StorageClass 2894 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2895 switch (StorageClassSpec) { 2896 case DeclSpec::SCS_unspecified: return SC_None; 2897 case DeclSpec::SCS_extern: return SC_Extern; 2898 case DeclSpec::SCS_static: return SC_Static; 2899 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2900 // Illegal SCSs map to None: error reporting is up to the caller. 2901 case DeclSpec::SCS_auto: // Fall through. 2902 case DeclSpec::SCS_mutable: // Fall through. 2903 case DeclSpec::SCS_register: // Fall through. 2904 case DeclSpec::SCS_typedef: return SC_None; 2905 } 2906 llvm_unreachable("unknown storage class specifier"); 2907 } 2908 2909 /// BuildAnonymousStructOrUnion - Handle the declaration of an 2910 /// anonymous structure or union. Anonymous unions are a C++ feature 2911 /// (C++ [class.union]) and a C11 feature; anonymous structures 2912 /// are a C11 feature and GNU C++ extension. 2913 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2914 AccessSpecifier AS, 2915 RecordDecl *Record) { 2916 DeclContext *Owner = Record->getDeclContext(); 2917 2918 // Diagnose whether this anonymous struct/union is an extension. 2919 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 2920 Diag(Record->getLocation(), diag::ext_anonymous_union); 2921 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 2922 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 2923 else if (!Record->isUnion() && !getLangOpts().C11) 2924 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 2925 2926 // C and C++ require different kinds of checks for anonymous 2927 // structs/unions. 2928 bool Invalid = false; 2929 if (getLangOpts().CPlusPlus) { 2930 const char* PrevSpec = 0; 2931 unsigned DiagID; 2932 if (Record->isUnion()) { 2933 // C++ [class.union]p6: 2934 // Anonymous unions declared in a named namespace or in the 2935 // global namespace shall be declared static. 2936 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 2937 (isa<TranslationUnitDecl>(Owner) || 2938 (isa<NamespaceDecl>(Owner) && 2939 cast<NamespaceDecl>(Owner)->getDeclName()))) { 2940 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 2941 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 2942 2943 // Recover by adding 'static'. 2944 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 2945 PrevSpec, DiagID); 2946 } 2947 // C++ [class.union]p6: 2948 // A storage class is not allowed in a declaration of an 2949 // anonymous union in a class scope. 2950 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 2951 isa<RecordDecl>(Owner)) { 2952 Diag(DS.getStorageClassSpecLoc(), 2953 diag::err_anonymous_union_with_storage_spec) 2954 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 2955 2956 // Recover by removing the storage specifier. 2957 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 2958 SourceLocation(), 2959 PrevSpec, DiagID); 2960 } 2961 } 2962 2963 // Ignore const/volatile/restrict qualifiers. 2964 if (DS.getTypeQualifiers()) { 2965 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2966 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2967 << Record->isUnion() << 0 2968 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 2969 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2970 Diag(DS.getVolatileSpecLoc(), 2971 diag::ext_anonymous_struct_union_qualified) 2972 << Record->isUnion() << 1 2973 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 2974 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 2975 Diag(DS.getRestrictSpecLoc(), 2976 diag::ext_anonymous_struct_union_qualified) 2977 << Record->isUnion() << 2 2978 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 2979 2980 DS.ClearTypeQualifiers(); 2981 } 2982 2983 // C++ [class.union]p2: 2984 // The member-specification of an anonymous union shall only 2985 // define non-static data members. [Note: nested types and 2986 // functions cannot be declared within an anonymous union. ] 2987 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 2988 MemEnd = Record->decls_end(); 2989 Mem != MemEnd; ++Mem) { 2990 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 2991 // C++ [class.union]p3: 2992 // An anonymous union shall not have private or protected 2993 // members (clause 11). 2994 assert(FD->getAccess() != AS_none); 2995 if (FD->getAccess() != AS_public) { 2996 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 2997 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 2998 Invalid = true; 2999 } 3000 3001 // C++ [class.union]p1 3002 // An object of a class with a non-trivial constructor, a non-trivial 3003 // copy constructor, a non-trivial destructor, or a non-trivial copy 3004 // assignment operator cannot be a member of a union, nor can an 3005 // array of such objects. 3006 if (CheckNontrivialField(FD)) 3007 Invalid = true; 3008 } else if ((*Mem)->isImplicit()) { 3009 // Any implicit members are fine. 3010 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3011 // This is a type that showed up in an 3012 // elaborated-type-specifier inside the anonymous struct or 3013 // union, but which actually declares a type outside of the 3014 // anonymous struct or union. It's okay. 3015 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3016 if (!MemRecord->isAnonymousStructOrUnion() && 3017 MemRecord->getDeclName()) { 3018 // Visual C++ allows type definition in anonymous struct or union. 3019 if (getLangOpts().MicrosoftExt) 3020 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3021 << (int)Record->isUnion(); 3022 else { 3023 // This is a nested type declaration. 3024 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3025 << (int)Record->isUnion(); 3026 Invalid = true; 3027 } 3028 } 3029 } else if (isa<AccessSpecDecl>(*Mem)) { 3030 // Any access specifier is fine. 3031 } else { 3032 // We have something that isn't a non-static data 3033 // member. Complain about it. 3034 unsigned DK = diag::err_anonymous_record_bad_member; 3035 if (isa<TypeDecl>(*Mem)) 3036 DK = diag::err_anonymous_record_with_type; 3037 else if (isa<FunctionDecl>(*Mem)) 3038 DK = diag::err_anonymous_record_with_function; 3039 else if (isa<VarDecl>(*Mem)) 3040 DK = diag::err_anonymous_record_with_static; 3041 3042 // Visual C++ allows type definition in anonymous struct or union. 3043 if (getLangOpts().MicrosoftExt && 3044 DK == diag::err_anonymous_record_with_type) 3045 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3046 << (int)Record->isUnion(); 3047 else { 3048 Diag((*Mem)->getLocation(), DK) 3049 << (int)Record->isUnion(); 3050 Invalid = true; 3051 } 3052 } 3053 } 3054 } 3055 3056 if (!Record->isUnion() && !Owner->isRecord()) { 3057 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3058 << (int)getLangOpts().CPlusPlus; 3059 Invalid = true; 3060 } 3061 3062 // Mock up a declarator. 3063 Declarator Dc(DS, Declarator::MemberContext); 3064 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3065 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3066 3067 // Create a declaration for this anonymous struct/union. 3068 NamedDecl *Anon = 0; 3069 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3070 Anon = FieldDecl::Create(Context, OwningClass, 3071 DS.getLocStart(), 3072 Record->getLocation(), 3073 /*IdentifierInfo=*/0, 3074 Context.getTypeDeclType(Record), 3075 TInfo, 3076 /*BitWidth=*/0, /*Mutable=*/false, 3077 /*InitStyle=*/ICIS_NoInit); 3078 Anon->setAccess(AS); 3079 if (getLangOpts().CPlusPlus) 3080 FieldCollector->Add(cast<FieldDecl>(Anon)); 3081 } else { 3082 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3083 assert(SCSpec != DeclSpec::SCS_typedef && 3084 "Parser allowed 'typedef' as storage class VarDecl."); 3085 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3086 if (SCSpec == DeclSpec::SCS_mutable) { 3087 // mutable can only appear on non-static class members, so it's always 3088 // an error here 3089 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3090 Invalid = true; 3091 SC = SC_None; 3092 } 3093 SCSpec = DS.getStorageClassSpecAsWritten(); 3094 VarDecl::StorageClass SCAsWritten 3095 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3096 3097 Anon = VarDecl::Create(Context, Owner, 3098 DS.getLocStart(), 3099 Record->getLocation(), /*IdentifierInfo=*/0, 3100 Context.getTypeDeclType(Record), 3101 TInfo, SC, SCAsWritten); 3102 3103 // Default-initialize the implicit variable. This initialization will be 3104 // trivial in almost all cases, except if a union member has an in-class 3105 // initializer: 3106 // union { int n = 0; }; 3107 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3108 } 3109 Anon->setImplicit(); 3110 3111 // Add the anonymous struct/union object to the current 3112 // context. We'll be referencing this object when we refer to one of 3113 // its members. 3114 Owner->addDecl(Anon); 3115 3116 // Inject the members of the anonymous struct/union into the owning 3117 // context and into the identifier resolver chain for name lookup 3118 // purposes. 3119 SmallVector<NamedDecl*, 2> Chain; 3120 Chain.push_back(Anon); 3121 3122 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3123 Chain, false)) 3124 Invalid = true; 3125 3126 // Mark this as an anonymous struct/union type. Note that we do not 3127 // do this until after we have already checked and injected the 3128 // members of this anonymous struct/union type, because otherwise 3129 // the members could be injected twice: once by DeclContext when it 3130 // builds its lookup table, and once by 3131 // InjectAnonymousStructOrUnionMembers. 3132 Record->setAnonymousStructOrUnion(true); 3133 3134 if (Invalid) 3135 Anon->setInvalidDecl(); 3136 3137 return Anon; 3138 } 3139 3140 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3141 /// Microsoft C anonymous structure. 3142 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3143 /// Example: 3144 /// 3145 /// struct A { int a; }; 3146 /// struct B { struct A; int b; }; 3147 /// 3148 /// void foo() { 3149 /// B var; 3150 /// var.a = 3; 3151 /// } 3152 /// 3153 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3154 RecordDecl *Record) { 3155 3156 // If there is no Record, get the record via the typedef. 3157 if (!Record) 3158 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3159 3160 // Mock up a declarator. 3161 Declarator Dc(DS, Declarator::TypeNameContext); 3162 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3163 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3164 3165 // Create a declaration for this anonymous struct. 3166 NamedDecl* Anon = FieldDecl::Create(Context, 3167 cast<RecordDecl>(CurContext), 3168 DS.getLocStart(), 3169 DS.getLocStart(), 3170 /*IdentifierInfo=*/0, 3171 Context.getTypeDeclType(Record), 3172 TInfo, 3173 /*BitWidth=*/0, /*Mutable=*/false, 3174 /*InitStyle=*/ICIS_NoInit); 3175 Anon->setImplicit(); 3176 3177 // Add the anonymous struct object to the current context. 3178 CurContext->addDecl(Anon); 3179 3180 // Inject the members of the anonymous struct into the current 3181 // context and into the identifier resolver chain for name lookup 3182 // purposes. 3183 SmallVector<NamedDecl*, 2> Chain; 3184 Chain.push_back(Anon); 3185 3186 RecordDecl *RecordDef = Record->getDefinition(); 3187 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3188 RecordDef, AS_none, 3189 Chain, true)) 3190 Anon->setInvalidDecl(); 3191 3192 return Anon; 3193 } 3194 3195 /// GetNameForDeclarator - Determine the full declaration name for the 3196 /// given Declarator. 3197 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3198 return GetNameFromUnqualifiedId(D.getName()); 3199 } 3200 3201 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3202 DeclarationNameInfo 3203 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3204 DeclarationNameInfo NameInfo; 3205 NameInfo.setLoc(Name.StartLocation); 3206 3207 switch (Name.getKind()) { 3208 3209 case UnqualifiedId::IK_ImplicitSelfParam: 3210 case UnqualifiedId::IK_Identifier: 3211 NameInfo.setName(Name.Identifier); 3212 NameInfo.setLoc(Name.StartLocation); 3213 return NameInfo; 3214 3215 case UnqualifiedId::IK_OperatorFunctionId: 3216 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3217 Name.OperatorFunctionId.Operator)); 3218 NameInfo.setLoc(Name.StartLocation); 3219 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3220 = Name.OperatorFunctionId.SymbolLocations[0]; 3221 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3222 = Name.EndLocation.getRawEncoding(); 3223 return NameInfo; 3224 3225 case UnqualifiedId::IK_LiteralOperatorId: 3226 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3227 Name.Identifier)); 3228 NameInfo.setLoc(Name.StartLocation); 3229 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3230 return NameInfo; 3231 3232 case UnqualifiedId::IK_ConversionFunctionId: { 3233 TypeSourceInfo *TInfo; 3234 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3235 if (Ty.isNull()) 3236 return DeclarationNameInfo(); 3237 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3238 Context.getCanonicalType(Ty))); 3239 NameInfo.setLoc(Name.StartLocation); 3240 NameInfo.setNamedTypeInfo(TInfo); 3241 return NameInfo; 3242 } 3243 3244 case UnqualifiedId::IK_ConstructorName: { 3245 TypeSourceInfo *TInfo; 3246 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3247 if (Ty.isNull()) 3248 return DeclarationNameInfo(); 3249 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3250 Context.getCanonicalType(Ty))); 3251 NameInfo.setLoc(Name.StartLocation); 3252 NameInfo.setNamedTypeInfo(TInfo); 3253 return NameInfo; 3254 } 3255 3256 case UnqualifiedId::IK_ConstructorTemplateId: { 3257 // In well-formed code, we can only have a constructor 3258 // template-id that refers to the current context, so go there 3259 // to find the actual type being constructed. 3260 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3261 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3262 return DeclarationNameInfo(); 3263 3264 // Determine the type of the class being constructed. 3265 QualType CurClassType = Context.getTypeDeclType(CurClass); 3266 3267 // FIXME: Check two things: that the template-id names the same type as 3268 // CurClassType, and that the template-id does not occur when the name 3269 // was qualified. 3270 3271 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3272 Context.getCanonicalType(CurClassType))); 3273 NameInfo.setLoc(Name.StartLocation); 3274 // FIXME: should we retrieve TypeSourceInfo? 3275 NameInfo.setNamedTypeInfo(0); 3276 return NameInfo; 3277 } 3278 3279 case UnqualifiedId::IK_DestructorName: { 3280 TypeSourceInfo *TInfo; 3281 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3282 if (Ty.isNull()) 3283 return DeclarationNameInfo(); 3284 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3285 Context.getCanonicalType(Ty))); 3286 NameInfo.setLoc(Name.StartLocation); 3287 NameInfo.setNamedTypeInfo(TInfo); 3288 return NameInfo; 3289 } 3290 3291 case UnqualifiedId::IK_TemplateId: { 3292 TemplateName TName = Name.TemplateId->Template.get(); 3293 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3294 return Context.getNameForTemplate(TName, TNameLoc); 3295 } 3296 3297 } // switch (Name.getKind()) 3298 3299 llvm_unreachable("Unknown name kind"); 3300 } 3301 3302 static QualType getCoreType(QualType Ty) { 3303 do { 3304 if (Ty->isPointerType() || Ty->isReferenceType()) 3305 Ty = Ty->getPointeeType(); 3306 else if (Ty->isArrayType()) 3307 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3308 else 3309 return Ty.withoutLocalFastQualifiers(); 3310 } while (true); 3311 } 3312 3313 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3314 /// and Definition have "nearly" matching parameters. This heuristic is 3315 /// used to improve diagnostics in the case where an out-of-line function 3316 /// definition doesn't match any declaration within the class or namespace. 3317 /// Also sets Params to the list of indices to the parameters that differ 3318 /// between the declaration and the definition. If hasSimilarParameters 3319 /// returns true and Params is empty, then all of the parameters match. 3320 static bool hasSimilarParameters(ASTContext &Context, 3321 FunctionDecl *Declaration, 3322 FunctionDecl *Definition, 3323 llvm::SmallVectorImpl<unsigned> &Params) { 3324 Params.clear(); 3325 if (Declaration->param_size() != Definition->param_size()) 3326 return false; 3327 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3328 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3329 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3330 3331 // The parameter types are identical 3332 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3333 continue; 3334 3335 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3336 QualType DefParamBaseTy = getCoreType(DefParamTy); 3337 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3338 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3339 3340 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3341 (DeclTyName && DeclTyName == DefTyName)) 3342 Params.push_back(Idx); 3343 else // The two parameters aren't even close 3344 return false; 3345 } 3346 3347 return true; 3348 } 3349 3350 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3351 /// declarator needs to be rebuilt in the current instantiation. 3352 /// Any bits of declarator which appear before the name are valid for 3353 /// consideration here. That's specifically the type in the decl spec 3354 /// and the base type in any member-pointer chunks. 3355 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3356 DeclarationName Name) { 3357 // The types we specifically need to rebuild are: 3358 // - typenames, typeofs, and decltypes 3359 // - types which will become injected class names 3360 // Of course, we also need to rebuild any type referencing such a 3361 // type. It's safest to just say "dependent", but we call out a 3362 // few cases here. 3363 3364 DeclSpec &DS = D.getMutableDeclSpec(); 3365 switch (DS.getTypeSpecType()) { 3366 case DeclSpec::TST_typename: 3367 case DeclSpec::TST_typeofType: 3368 case DeclSpec::TST_decltype: 3369 case DeclSpec::TST_underlyingType: 3370 case DeclSpec::TST_atomic: { 3371 // Grab the type from the parser. 3372 TypeSourceInfo *TSI = 0; 3373 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3374 if (T.isNull() || !T->isDependentType()) break; 3375 3376 // Make sure there's a type source info. This isn't really much 3377 // of a waste; most dependent types should have type source info 3378 // attached already. 3379 if (!TSI) 3380 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3381 3382 // Rebuild the type in the current instantiation. 3383 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3384 if (!TSI) return true; 3385 3386 // Store the new type back in the decl spec. 3387 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3388 DS.UpdateTypeRep(LocType); 3389 break; 3390 } 3391 3392 case DeclSpec::TST_typeofExpr: { 3393 Expr *E = DS.getRepAsExpr(); 3394 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3395 if (Result.isInvalid()) return true; 3396 DS.UpdateExprRep(Result.get()); 3397 break; 3398 } 3399 3400 default: 3401 // Nothing to do for these decl specs. 3402 break; 3403 } 3404 3405 // It doesn't matter what order we do this in. 3406 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3407 DeclaratorChunk &Chunk = D.getTypeObject(I); 3408 3409 // The only type information in the declarator which can come 3410 // before the declaration name is the base type of a member 3411 // pointer. 3412 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3413 continue; 3414 3415 // Rebuild the scope specifier in-place. 3416 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3417 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3418 return true; 3419 } 3420 3421 return false; 3422 } 3423 3424 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3425 D.setFunctionDefinitionKind(FDK_Declaration); 3426 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this)); 3427 3428 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 3429 Dcl && Dcl->getDeclContext()->isFileContext()) 3430 Dcl->setTopLevelDeclInObjCContainer(); 3431 3432 return Dcl; 3433 } 3434 3435 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3436 /// If T is the name of a class, then each of the following shall have a 3437 /// name different from T: 3438 /// - every static data member of class T; 3439 /// - every member function of class T 3440 /// - every member of class T that is itself a type; 3441 /// \returns true if the declaration name violates these rules. 3442 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3443 DeclarationNameInfo NameInfo) { 3444 DeclarationName Name = NameInfo.getName(); 3445 3446 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3447 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3448 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3449 return true; 3450 } 3451 3452 return false; 3453 } 3454 3455 /// \brief Diagnose a declaration whose declarator-id has the given 3456 /// nested-name-specifier. 3457 /// 3458 /// \param SS The nested-name-specifier of the declarator-id. 3459 /// 3460 /// \param DC The declaration context to which the nested-name-specifier 3461 /// resolves. 3462 /// 3463 /// \param Name The name of the entity being declared. 3464 /// 3465 /// \param Loc The location of the name of the entity being declared. 3466 /// 3467 /// \returns true if we cannot safely recover from this error, false otherwise. 3468 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 3469 DeclarationName Name, 3470 SourceLocation Loc) { 3471 DeclContext *Cur = CurContext; 3472 while (isa<LinkageSpecDecl>(Cur)) 3473 Cur = Cur->getParent(); 3474 3475 // C++ [dcl.meaning]p1: 3476 // A declarator-id shall not be qualified except for the definition 3477 // of a member function (9.3) or static data member (9.4) outside of 3478 // its class, the definition or explicit instantiation of a function 3479 // or variable member of a namespace outside of its namespace, or the 3480 // definition of an explicit specialization outside of its namespace, 3481 // or the declaration of a friend function that is a member of 3482 // another class or namespace (11.3). [...] 3483 3484 // The user provided a superfluous scope specifier that refers back to the 3485 // class or namespaces in which the entity is already declared. 3486 // 3487 // class X { 3488 // void X::f(); 3489 // }; 3490 if (Cur->Equals(DC)) { 3491 Diag(Loc, diag::warn_member_extra_qualification) 3492 << Name << FixItHint::CreateRemoval(SS.getRange()); 3493 SS.clear(); 3494 return false; 3495 } 3496 3497 // Check whether the qualifying scope encloses the scope of the original 3498 // declaration. 3499 if (!Cur->Encloses(DC)) { 3500 if (Cur->isRecord()) 3501 Diag(Loc, diag::err_member_qualification) 3502 << Name << SS.getRange(); 3503 else if (isa<TranslationUnitDecl>(DC)) 3504 Diag(Loc, diag::err_invalid_declarator_global_scope) 3505 << Name << SS.getRange(); 3506 else if (isa<FunctionDecl>(Cur)) 3507 Diag(Loc, diag::err_invalid_declarator_in_function) 3508 << Name << SS.getRange(); 3509 else 3510 Diag(Loc, diag::err_invalid_declarator_scope) 3511 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 3512 3513 return true; 3514 } 3515 3516 if (Cur->isRecord()) { 3517 // Cannot qualify members within a class. 3518 Diag(Loc, diag::err_member_qualification) 3519 << Name << SS.getRange(); 3520 SS.clear(); 3521 3522 // C++ constructors and destructors with incorrect scopes can break 3523 // our AST invariants by having the wrong underlying types. If 3524 // that's the case, then drop this declaration entirely. 3525 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 3526 Name.getNameKind() == DeclarationName::CXXDestructorName) && 3527 !Context.hasSameType(Name.getCXXNameType(), 3528 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 3529 return true; 3530 3531 return false; 3532 } 3533 3534 // C++11 [dcl.meaning]p1: 3535 // [...] "The nested-name-specifier of the qualified declarator-id shall 3536 // not begin with a decltype-specifer" 3537 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 3538 while (SpecLoc.getPrefix()) 3539 SpecLoc = SpecLoc.getPrefix(); 3540 if (dyn_cast_or_null<DecltypeType>( 3541 SpecLoc.getNestedNameSpecifier()->getAsType())) 3542 Diag(Loc, diag::err_decltype_in_declarator) 3543 << SpecLoc.getTypeLoc().getSourceRange(); 3544 3545 return false; 3546 } 3547 3548 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 3549 MultiTemplateParamsArg TemplateParamLists) { 3550 // TODO: consider using NameInfo for diagnostic. 3551 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3552 DeclarationName Name = NameInfo.getName(); 3553 3554 // All of these full declarators require an identifier. If it doesn't have 3555 // one, the ParsedFreeStandingDeclSpec action should be used. 3556 if (!Name) { 3557 if (!D.isInvalidType()) // Reject this if we think it is valid. 3558 Diag(D.getDeclSpec().getLocStart(), 3559 diag::err_declarator_need_ident) 3560 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 3561 return 0; 3562 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 3563 return 0; 3564 3565 // The scope passed in may not be a decl scope. Zip up the scope tree until 3566 // we find one that is. 3567 while ((S->getFlags() & Scope::DeclScope) == 0 || 3568 (S->getFlags() & Scope::TemplateParamScope) != 0) 3569 S = S->getParent(); 3570 3571 DeclContext *DC = CurContext; 3572 if (D.getCXXScopeSpec().isInvalid()) 3573 D.setInvalidType(); 3574 else if (D.getCXXScopeSpec().isSet()) { 3575 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 3576 UPPC_DeclarationQualifier)) 3577 return 0; 3578 3579 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 3580 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 3581 if (!DC) { 3582 // If we could not compute the declaration context, it's because the 3583 // declaration context is dependent but does not refer to a class, 3584 // class template, or class template partial specialization. Complain 3585 // and return early, to avoid the coming semantic disaster. 3586 Diag(D.getIdentifierLoc(), 3587 diag::err_template_qualified_declarator_no_match) 3588 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 3589 << D.getCXXScopeSpec().getRange(); 3590 return 0; 3591 } 3592 bool IsDependentContext = DC->isDependentContext(); 3593 3594 if (!IsDependentContext && 3595 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 3596 return 0; 3597 3598 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 3599 Diag(D.getIdentifierLoc(), 3600 diag::err_member_def_undefined_record) 3601 << Name << DC << D.getCXXScopeSpec().getRange(); 3602 D.setInvalidType(); 3603 } else if (!D.getDeclSpec().isFriendSpecified()) { 3604 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 3605 Name, D.getIdentifierLoc())) { 3606 if (DC->isRecord()) 3607 return 0; 3608 3609 D.setInvalidType(); 3610 } 3611 } 3612 3613 // Check whether we need to rebuild the type of the given 3614 // declaration in the current instantiation. 3615 if (EnteringContext && IsDependentContext && 3616 TemplateParamLists.size() != 0) { 3617 ContextRAII SavedContext(*this, DC); 3618 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 3619 D.setInvalidType(); 3620 } 3621 } 3622 3623 if (DiagnoseClassNameShadow(DC, NameInfo)) 3624 // If this is a typedef, we'll end up spewing multiple diagnostics. 3625 // Just return early; it's safer. 3626 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3627 return 0; 3628 3629 NamedDecl *New; 3630 3631 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3632 QualType R = TInfo->getType(); 3633 3634 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 3635 UPPC_DeclarationType)) 3636 D.setInvalidType(); 3637 3638 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 3639 ForRedeclaration); 3640 3641 // See if this is a redefinition of a variable in the same scope. 3642 if (!D.getCXXScopeSpec().isSet()) { 3643 bool IsLinkageLookup = false; 3644 3645 // If the declaration we're planning to build will be a function 3646 // or object with linkage, then look for another declaration with 3647 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 3648 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3649 /* Do nothing*/; 3650 else if (R->isFunctionType()) { 3651 if (CurContext->isFunctionOrMethod() || 3652 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3653 IsLinkageLookup = true; 3654 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 3655 IsLinkageLookup = true; 3656 else if (CurContext->getRedeclContext()->isTranslationUnit() && 3657 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3658 IsLinkageLookup = true; 3659 3660 if (IsLinkageLookup) 3661 Previous.clear(LookupRedeclarationWithLinkage); 3662 3663 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 3664 } else { // Something like "int foo::x;" 3665 LookupQualifiedName(Previous, DC); 3666 3667 // C++ [dcl.meaning]p1: 3668 // When the declarator-id is qualified, the declaration shall refer to a 3669 // previously declared member of the class or namespace to which the 3670 // qualifier refers (or, in the case of a namespace, of an element of the 3671 // inline namespace set of that namespace (7.3.1)) or to a specialization 3672 // thereof; [...] 3673 // 3674 // Note that we already checked the context above, and that we do not have 3675 // enough information to make sure that Previous contains the declaration 3676 // we want to match. For example, given: 3677 // 3678 // class X { 3679 // void f(); 3680 // void f(float); 3681 // }; 3682 // 3683 // void X::f(int) { } // ill-formed 3684 // 3685 // In this case, Previous will point to the overload set 3686 // containing the two f's declared in X, but neither of them 3687 // matches. 3688 3689 // C++ [dcl.meaning]p1: 3690 // [...] the member shall not merely have been introduced by a 3691 // using-declaration in the scope of the class or namespace nominated by 3692 // the nested-name-specifier of the declarator-id. 3693 RemoveUsingDecls(Previous); 3694 } 3695 3696 if (Previous.isSingleResult() && 3697 Previous.getFoundDecl()->isTemplateParameter()) { 3698 // Maybe we will complain about the shadowed template parameter. 3699 if (!D.isInvalidType()) 3700 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 3701 Previous.getFoundDecl()); 3702 3703 // Just pretend that we didn't see the previous declaration. 3704 Previous.clear(); 3705 } 3706 3707 // In C++, the previous declaration we find might be a tag type 3708 // (class or enum). In this case, the new declaration will hide the 3709 // tag type. Note that this does does not apply if we're declaring a 3710 // typedef (C++ [dcl.typedef]p4). 3711 if (Previous.isSingleTagDecl() && 3712 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 3713 Previous.clear(); 3714 3715 bool AddToScope = true; 3716 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3717 if (TemplateParamLists.size()) { 3718 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 3719 return 0; 3720 } 3721 3722 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 3723 } else if (R->isFunctionType()) { 3724 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 3725 move(TemplateParamLists), 3726 AddToScope); 3727 } else { 3728 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 3729 move(TemplateParamLists)); 3730 } 3731 3732 if (New == 0) 3733 return 0; 3734 3735 // If this has an identifier and is not an invalid redeclaration or 3736 // function template specialization, add it to the scope stack. 3737 if (New->getDeclName() && AddToScope && 3738 !(D.isRedeclaration() && New->isInvalidDecl())) 3739 PushOnScopeChains(New, S); 3740 3741 return New; 3742 } 3743 3744 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 3745 /// types into constant array types in certain situations which would otherwise 3746 /// be errors (for GCC compatibility). 3747 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3748 ASTContext &Context, 3749 bool &SizeIsNegative, 3750 llvm::APSInt &Oversized) { 3751 // This method tries to turn a variable array into a constant 3752 // array even when the size isn't an ICE. This is necessary 3753 // for compatibility with code that depends on gcc's buggy 3754 // constant expression folding, like struct {char x[(int)(char*)2];} 3755 SizeIsNegative = false; 3756 Oversized = 0; 3757 3758 if (T->isDependentType()) 3759 return QualType(); 3760 3761 QualifierCollector Qs; 3762 const Type *Ty = Qs.strip(T); 3763 3764 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 3765 QualType Pointee = PTy->getPointeeType(); 3766 QualType FixedType = 3767 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 3768 Oversized); 3769 if (FixedType.isNull()) return FixedType; 3770 FixedType = Context.getPointerType(FixedType); 3771 return Qs.apply(Context, FixedType); 3772 } 3773 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 3774 QualType Inner = PTy->getInnerType(); 3775 QualType FixedType = 3776 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 3777 Oversized); 3778 if (FixedType.isNull()) return FixedType; 3779 FixedType = Context.getParenType(FixedType); 3780 return Qs.apply(Context, FixedType); 3781 } 3782 3783 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3784 if (!VLATy) 3785 return QualType(); 3786 // FIXME: We should probably handle this case 3787 if (VLATy->getElementType()->isVariablyModifiedType()) 3788 return QualType(); 3789 3790 llvm::APSInt Res; 3791 if (!VLATy->getSizeExpr() || 3792 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 3793 return QualType(); 3794 3795 // Check whether the array size is negative. 3796 if (Res.isSigned() && Res.isNegative()) { 3797 SizeIsNegative = true; 3798 return QualType(); 3799 } 3800 3801 // Check whether the array is too large to be addressed. 3802 unsigned ActiveSizeBits 3803 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 3804 Res); 3805 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 3806 Oversized = Res; 3807 return QualType(); 3808 } 3809 3810 return Context.getConstantArrayType(VLATy->getElementType(), 3811 Res, ArrayType::Normal, 0); 3812 } 3813 3814 /// \brief Register the given locally-scoped external C declaration so 3815 /// that it can be found later for redeclarations 3816 void 3817 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 3818 const LookupResult &Previous, 3819 Scope *S) { 3820 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 3821 "Decl is not a locally-scoped decl!"); 3822 // Note that we have a locally-scoped external with this name. 3823 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 3824 3825 if (!Previous.isSingleResult()) 3826 return; 3827 3828 NamedDecl *PrevDecl = Previous.getFoundDecl(); 3829 3830 // If there was a previous declaration of this variable, it may be 3831 // in our identifier chain. Update the identifier chain with the new 3832 // declaration. 3833 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 3834 // The previous declaration was found on the identifer resolver 3835 // chain, so remove it from its scope. 3836 3837 if (S->isDeclScope(PrevDecl)) { 3838 // Special case for redeclarations in the SAME scope. 3839 // Because this declaration is going to be added to the identifier chain 3840 // later, we should temporarily take it OFF the chain. 3841 IdResolver.RemoveDecl(ND); 3842 3843 } else { 3844 // Find the scope for the original declaration. 3845 while (S && !S->isDeclScope(PrevDecl)) 3846 S = S->getParent(); 3847 } 3848 3849 if (S) 3850 S->RemoveDecl(PrevDecl); 3851 } 3852 } 3853 3854 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 3855 Sema::findLocallyScopedExternalDecl(DeclarationName Name) { 3856 if (ExternalSource) { 3857 // Load locally-scoped external decls from the external source. 3858 SmallVector<NamedDecl *, 4> Decls; 3859 ExternalSource->ReadLocallyScopedExternalDecls(Decls); 3860 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 3861 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3862 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName()); 3863 if (Pos == LocallyScopedExternalDecls.end()) 3864 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I]; 3865 } 3866 } 3867 3868 return LocallyScopedExternalDecls.find(Name); 3869 } 3870 3871 /// \brief Diagnose function specifiers on a declaration of an identifier that 3872 /// does not identify a function. 3873 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 3874 // FIXME: We should probably indicate the identifier in question to avoid 3875 // confusion for constructs like "inline int a(), b;" 3876 if (D.getDeclSpec().isInlineSpecified()) 3877 Diag(D.getDeclSpec().getInlineSpecLoc(), 3878 diag::err_inline_non_function); 3879 3880 if (D.getDeclSpec().isVirtualSpecified()) 3881 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3882 diag::err_virtual_non_function); 3883 3884 if (D.getDeclSpec().isExplicitSpecified()) 3885 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3886 diag::err_explicit_non_function); 3887 } 3888 3889 NamedDecl* 3890 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 3891 TypeSourceInfo *TInfo, LookupResult &Previous) { 3892 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 3893 if (D.getCXXScopeSpec().isSet()) { 3894 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 3895 << D.getCXXScopeSpec().getRange(); 3896 D.setInvalidType(); 3897 // Pretend we didn't see the scope specifier. 3898 DC = CurContext; 3899 Previous.clear(); 3900 } 3901 3902 if (getLangOpts().CPlusPlus) { 3903 // Check that there are no default arguments (C++ only). 3904 CheckExtraCXXDefaultArguments(D); 3905 } 3906 3907 DiagnoseFunctionSpecifiers(D); 3908 3909 if (D.getDeclSpec().isThreadSpecified()) 3910 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3911 if (D.getDeclSpec().isConstexprSpecified()) 3912 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 3913 << 1; 3914 3915 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 3916 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 3917 << D.getName().getSourceRange(); 3918 return 0; 3919 } 3920 3921 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 3922 if (!NewTD) return 0; 3923 3924 // Handle attributes prior to checking for duplicates in MergeVarDecl 3925 ProcessDeclAttributes(S, NewTD, D); 3926 3927 CheckTypedefForVariablyModifiedType(S, NewTD); 3928 3929 bool Redeclaration = D.isRedeclaration(); 3930 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 3931 D.setRedeclaration(Redeclaration); 3932 return ND; 3933 } 3934 3935 void 3936 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 3937 // C99 6.7.7p2: If a typedef name specifies a variably modified type 3938 // then it shall have block scope. 3939 // Note that variably modified types must be fixed before merging the decl so 3940 // that redeclarations will match. 3941 QualType T = NewTD->getUnderlyingType(); 3942 if (T->isVariablyModifiedType()) { 3943 getCurFunction()->setHasBranchProtectedScope(); 3944 3945 if (S->getFnParent() == 0) { 3946 bool SizeIsNegative; 3947 llvm::APSInt Oversized; 3948 QualType FixedTy = 3949 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 3950 Oversized); 3951 if (!FixedTy.isNull()) { 3952 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 3953 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 3954 } else { 3955 if (SizeIsNegative) 3956 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 3957 else if (T->isVariableArrayType()) 3958 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 3959 else if (Oversized.getBoolValue()) 3960 Diag(NewTD->getLocation(), diag::err_array_too_large) 3961 << Oversized.toString(10); 3962 else 3963 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 3964 NewTD->setInvalidDecl(); 3965 } 3966 } 3967 } 3968 } 3969 3970 3971 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 3972 /// declares a typedef-name, either using the 'typedef' type specifier or via 3973 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 3974 NamedDecl* 3975 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 3976 LookupResult &Previous, bool &Redeclaration) { 3977 // Merge the decl with the existing one if appropriate. If the decl is 3978 // in an outer scope, it isn't the same thing. 3979 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 3980 /*ExplicitInstantiationOrSpecialization=*/false); 3981 if (!Previous.empty()) { 3982 Redeclaration = true; 3983 MergeTypedefNameDecl(NewTD, Previous); 3984 } 3985 3986 // If this is the C FILE type, notify the AST context. 3987 if (IdentifierInfo *II = NewTD->getIdentifier()) 3988 if (!NewTD->isInvalidDecl() && 3989 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 3990 if (II->isStr("FILE")) 3991 Context.setFILEDecl(NewTD); 3992 else if (II->isStr("jmp_buf")) 3993 Context.setjmp_bufDecl(NewTD); 3994 else if (II->isStr("sigjmp_buf")) 3995 Context.setsigjmp_bufDecl(NewTD); 3996 else if (II->isStr("ucontext_t")) 3997 Context.setucontext_tDecl(NewTD); 3998 } 3999 4000 return NewTD; 4001 } 4002 4003 /// \brief Determines whether the given declaration is an out-of-scope 4004 /// previous declaration. 4005 /// 4006 /// This routine should be invoked when name lookup has found a 4007 /// previous declaration (PrevDecl) that is not in the scope where a 4008 /// new declaration by the same name is being introduced. If the new 4009 /// declaration occurs in a local scope, previous declarations with 4010 /// linkage may still be considered previous declarations (C99 4011 /// 6.2.2p4-5, C++ [basic.link]p6). 4012 /// 4013 /// \param PrevDecl the previous declaration found by name 4014 /// lookup 4015 /// 4016 /// \param DC the context in which the new declaration is being 4017 /// declared. 4018 /// 4019 /// \returns true if PrevDecl is an out-of-scope previous declaration 4020 /// for a new delcaration with the same name. 4021 static bool 4022 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4023 ASTContext &Context) { 4024 if (!PrevDecl) 4025 return false; 4026 4027 if (!PrevDecl->hasLinkage()) 4028 return false; 4029 4030 if (Context.getLangOpts().CPlusPlus) { 4031 // C++ [basic.link]p6: 4032 // If there is a visible declaration of an entity with linkage 4033 // having the same name and type, ignoring entities declared 4034 // outside the innermost enclosing namespace scope, the block 4035 // scope declaration declares that same entity and receives the 4036 // linkage of the previous declaration. 4037 DeclContext *OuterContext = DC->getRedeclContext(); 4038 if (!OuterContext->isFunctionOrMethod()) 4039 // This rule only applies to block-scope declarations. 4040 return false; 4041 4042 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4043 if (PrevOuterContext->isRecord()) 4044 // We found a member function: ignore it. 4045 return false; 4046 4047 // Find the innermost enclosing namespace for the new and 4048 // previous declarations. 4049 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4050 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4051 4052 // The previous declaration is in a different namespace, so it 4053 // isn't the same function. 4054 if (!OuterContext->Equals(PrevOuterContext)) 4055 return false; 4056 } 4057 4058 return true; 4059 } 4060 4061 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4062 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4063 if (!SS.isSet()) return; 4064 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4065 } 4066 4067 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4068 QualType type = decl->getType(); 4069 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4070 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4071 // Various kinds of declaration aren't allowed to be __autoreleasing. 4072 unsigned kind = -1U; 4073 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4074 if (var->hasAttr<BlocksAttr>()) 4075 kind = 0; // __block 4076 else if (!var->hasLocalStorage()) 4077 kind = 1; // global 4078 } else if (isa<ObjCIvarDecl>(decl)) { 4079 kind = 3; // ivar 4080 } else if (isa<FieldDecl>(decl)) { 4081 kind = 2; // field 4082 } 4083 4084 if (kind != -1U) { 4085 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4086 << kind; 4087 } 4088 } else if (lifetime == Qualifiers::OCL_None) { 4089 // Try to infer lifetime. 4090 if (!type->isObjCLifetimeType()) 4091 return false; 4092 4093 lifetime = type->getObjCARCImplicitLifetime(); 4094 type = Context.getLifetimeQualifiedType(type, lifetime); 4095 decl->setType(type); 4096 } 4097 4098 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4099 // Thread-local variables cannot have lifetime. 4100 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4101 var->isThreadSpecified()) { 4102 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4103 << var->getType(); 4104 return true; 4105 } 4106 } 4107 4108 return false; 4109 } 4110 4111 NamedDecl* 4112 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4113 TypeSourceInfo *TInfo, LookupResult &Previous, 4114 MultiTemplateParamsArg TemplateParamLists) { 4115 QualType R = TInfo->getType(); 4116 DeclarationName Name = GetNameForDeclarator(D).getName(); 4117 4118 // Check that there are no default arguments (C++ only). 4119 if (getLangOpts().CPlusPlus) 4120 CheckExtraCXXDefaultArguments(D); 4121 4122 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4123 assert(SCSpec != DeclSpec::SCS_typedef && 4124 "Parser allowed 'typedef' as storage class VarDecl."); 4125 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 4126 if (SCSpec == DeclSpec::SCS_mutable) { 4127 // mutable can only appear on non-static class members, so it's always 4128 // an error here 4129 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4130 D.setInvalidType(); 4131 SC = SC_None; 4132 } 4133 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4134 VarDecl::StorageClass SCAsWritten 4135 = StorageClassSpecToVarDeclStorageClass(SCSpec); 4136 4137 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4138 if (!II) { 4139 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4140 << Name; 4141 return 0; 4142 } 4143 4144 DiagnoseFunctionSpecifiers(D); 4145 4146 if (!DC->isRecord() && S->getFnParent() == 0) { 4147 // C99 6.9p2: The storage-class specifiers auto and register shall not 4148 // appear in the declaration specifiers in an external declaration. 4149 if (SC == SC_Auto || SC == SC_Register) { 4150 4151 // If this is a register variable with an asm label specified, then this 4152 // is a GNU extension. 4153 if (SC == SC_Register && D.getAsmLabel()) 4154 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4155 else 4156 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4157 D.setInvalidType(); 4158 } 4159 } 4160 4161 if (getLangOpts().OpenCL) { 4162 // Set up the special work-group-local storage class for variables in the 4163 // OpenCL __local address space. 4164 if (R.getAddressSpace() == LangAS::opencl_local) 4165 SC = SC_OpenCLWorkGroupLocal; 4166 } 4167 4168 bool isExplicitSpecialization = false; 4169 VarDecl *NewVD; 4170 if (!getLangOpts().CPlusPlus) { 4171 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4172 D.getIdentifierLoc(), II, 4173 R, TInfo, SC, SCAsWritten); 4174 4175 if (D.isInvalidType()) 4176 NewVD->setInvalidDecl(); 4177 } else { 4178 if (DC->isRecord() && !CurContext->isRecord()) { 4179 // This is an out-of-line definition of a static data member. 4180 if (SC == SC_Static) { 4181 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4182 diag::err_static_out_of_line) 4183 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4184 } else if (SC == SC_None) 4185 SC = SC_Static; 4186 } 4187 if (SC == SC_Static && CurContext->isRecord()) { 4188 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 4189 if (RD->isLocalClass()) 4190 Diag(D.getIdentifierLoc(), 4191 diag::err_static_data_member_not_allowed_in_local_class) 4192 << Name << RD->getDeclName(); 4193 4194 // C++98 [class.union]p1: If a union contains a static data member, 4195 // the program is ill-formed. C++11 drops this restriction. 4196 if (RD->isUnion()) 4197 Diag(D.getIdentifierLoc(), 4198 getLangOpts().CPlusPlus0x 4199 ? diag::warn_cxx98_compat_static_data_member_in_union 4200 : diag::ext_static_data_member_in_union) << Name; 4201 // We conservatively disallow static data members in anonymous structs. 4202 else if (!RD->getDeclName()) 4203 Diag(D.getIdentifierLoc(), 4204 diag::err_static_data_member_not_allowed_in_anon_struct) 4205 << Name << RD->isUnion(); 4206 } 4207 } 4208 4209 // Match up the template parameter lists with the scope specifier, then 4210 // determine whether we have a template or a template specialization. 4211 isExplicitSpecialization = false; 4212 bool Invalid = false; 4213 if (TemplateParameterList *TemplateParams 4214 = MatchTemplateParametersToScopeSpecifier( 4215 D.getDeclSpec().getLocStart(), 4216 D.getIdentifierLoc(), 4217 D.getCXXScopeSpec(), 4218 TemplateParamLists.get(), 4219 TemplateParamLists.size(), 4220 /*never a friend*/ false, 4221 isExplicitSpecialization, 4222 Invalid)) { 4223 if (TemplateParams->size() > 0) { 4224 // There is no such thing as a variable template. 4225 Diag(D.getIdentifierLoc(), diag::err_template_variable) 4226 << II 4227 << SourceRange(TemplateParams->getTemplateLoc(), 4228 TemplateParams->getRAngleLoc()); 4229 return 0; 4230 } else { 4231 // There is an extraneous 'template<>' for this variable. Complain 4232 // about it, but allow the declaration of the variable. 4233 Diag(TemplateParams->getTemplateLoc(), 4234 diag::err_template_variable_noparams) 4235 << II 4236 << SourceRange(TemplateParams->getTemplateLoc(), 4237 TemplateParams->getRAngleLoc()); 4238 } 4239 } 4240 4241 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4242 D.getIdentifierLoc(), II, 4243 R, TInfo, SC, SCAsWritten); 4244 4245 // If this decl has an auto type in need of deduction, make a note of the 4246 // Decl so we can diagnose uses of it in its own initializer. 4247 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 4248 R->getContainedAutoType()) 4249 ParsingInitForAutoVars.insert(NewVD); 4250 4251 if (D.isInvalidType() || Invalid) 4252 NewVD->setInvalidDecl(); 4253 4254 SetNestedNameSpecifier(NewVD, D); 4255 4256 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 4257 NewVD->setTemplateParameterListsInfo(Context, 4258 TemplateParamLists.size(), 4259 TemplateParamLists.release()); 4260 } 4261 4262 if (D.getDeclSpec().isConstexprSpecified()) 4263 NewVD->setConstexpr(true); 4264 } 4265 4266 // Set the lexical context. If the declarator has a C++ scope specifier, the 4267 // lexical context will be different from the semantic context. 4268 NewVD->setLexicalDeclContext(CurContext); 4269 4270 if (D.getDeclSpec().isThreadSpecified()) { 4271 if (NewVD->hasLocalStorage()) 4272 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 4273 else if (!Context.getTargetInfo().isTLSSupported()) 4274 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 4275 else 4276 NewVD->setThreadSpecified(true); 4277 } 4278 4279 if (D.getDeclSpec().isModulePrivateSpecified()) { 4280 if (isExplicitSpecialization) 4281 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 4282 << 2 4283 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4284 else if (NewVD->hasLocalStorage()) 4285 Diag(NewVD->getLocation(), diag::err_module_private_local) 4286 << 0 << NewVD->getDeclName() 4287 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 4288 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4289 else 4290 NewVD->setModulePrivate(); 4291 } 4292 4293 // Handle attributes prior to checking for duplicates in MergeVarDecl 4294 ProcessDeclAttributes(S, NewVD, D); 4295 4296 // In auto-retain/release, infer strong retension for variables of 4297 // retainable type. 4298 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 4299 NewVD->setInvalidDecl(); 4300 4301 // Handle GNU asm-label extension (encoded as an attribute). 4302 if (Expr *E = (Expr*)D.getAsmLabel()) { 4303 // The parser guarantees this is a string. 4304 StringLiteral *SE = cast<StringLiteral>(E); 4305 StringRef Label = SE->getString(); 4306 if (S->getFnParent() != 0) { 4307 switch (SC) { 4308 case SC_None: 4309 case SC_Auto: 4310 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 4311 break; 4312 case SC_Register: 4313 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 4314 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 4315 break; 4316 case SC_Static: 4317 case SC_Extern: 4318 case SC_PrivateExtern: 4319 case SC_OpenCLWorkGroupLocal: 4320 break; 4321 } 4322 } 4323 4324 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4325 Context, Label)); 4326 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 4327 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 4328 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 4329 if (I != ExtnameUndeclaredIdentifiers.end()) { 4330 NewVD->addAttr(I->second); 4331 ExtnameUndeclaredIdentifiers.erase(I); 4332 } 4333 } 4334 4335 // Diagnose shadowed variables before filtering for scope. 4336 if (!D.getCXXScopeSpec().isSet()) 4337 CheckShadow(S, NewVD, Previous); 4338 4339 // Don't consider existing declarations that are in a different 4340 // scope and are out-of-semantic-context declarations (if the new 4341 // declaration has linkage). 4342 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 4343 isExplicitSpecialization); 4344 4345 if (!getLangOpts().CPlusPlus) { 4346 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4347 } else { 4348 // Merge the decl with the existing one if appropriate. 4349 if (!Previous.empty()) { 4350 if (Previous.isSingleResult() && 4351 isa<FieldDecl>(Previous.getFoundDecl()) && 4352 D.getCXXScopeSpec().isSet()) { 4353 // The user tried to define a non-static data member 4354 // out-of-line (C++ [dcl.meaning]p1). 4355 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 4356 << D.getCXXScopeSpec().getRange(); 4357 Previous.clear(); 4358 NewVD->setInvalidDecl(); 4359 } 4360 } else if (D.getCXXScopeSpec().isSet()) { 4361 // No previous declaration in the qualifying scope. 4362 Diag(D.getIdentifierLoc(), diag::err_no_member) 4363 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 4364 << D.getCXXScopeSpec().getRange(); 4365 NewVD->setInvalidDecl(); 4366 } 4367 4368 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4369 4370 // This is an explicit specialization of a static data member. Check it. 4371 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 4372 CheckMemberSpecialization(NewVD, Previous)) 4373 NewVD->setInvalidDecl(); 4374 } 4375 4376 // If this is a locally-scoped extern C variable, update the map of 4377 // such variables. 4378 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 4379 !NewVD->isInvalidDecl()) 4380 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 4381 4382 // If there's a #pragma GCC visibility in scope, and this isn't a class 4383 // member, set the visibility of this variable. 4384 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 4385 AddPushedVisibilityAttribute(NewVD); 4386 4387 MarkUnusedFileScopedDecl(NewVD); 4388 4389 return NewVD; 4390 } 4391 4392 /// \brief Diagnose variable or built-in function shadowing. Implements 4393 /// -Wshadow. 4394 /// 4395 /// This method is called whenever a VarDecl is added to a "useful" 4396 /// scope. 4397 /// 4398 /// \param S the scope in which the shadowing name is being declared 4399 /// \param R the lookup of the name 4400 /// 4401 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 4402 // Return if warning is ignored. 4403 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 4404 DiagnosticsEngine::Ignored) 4405 return; 4406 4407 // Don't diagnose declarations at file scope. 4408 if (D->hasGlobalStorage()) 4409 return; 4410 4411 DeclContext *NewDC = D->getDeclContext(); 4412 4413 // Only diagnose if we're shadowing an unambiguous field or variable. 4414 if (R.getResultKind() != LookupResult::Found) 4415 return; 4416 4417 NamedDecl* ShadowedDecl = R.getFoundDecl(); 4418 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 4419 return; 4420 4421 // Fields are not shadowed by variables in C++ static methods. 4422 if (isa<FieldDecl>(ShadowedDecl)) 4423 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 4424 if (MD->isStatic()) 4425 return; 4426 4427 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 4428 if (shadowedVar->isExternC()) { 4429 // For shadowing external vars, make sure that we point to the global 4430 // declaration, not a locally scoped extern declaration. 4431 for (VarDecl::redecl_iterator 4432 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 4433 I != E; ++I) 4434 if (I->isFileVarDecl()) { 4435 ShadowedDecl = *I; 4436 break; 4437 } 4438 } 4439 4440 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 4441 4442 // Only warn about certain kinds of shadowing for class members. 4443 if (NewDC && NewDC->isRecord()) { 4444 // In particular, don't warn about shadowing non-class members. 4445 if (!OldDC->isRecord()) 4446 return; 4447 4448 // TODO: should we warn about static data members shadowing 4449 // static data members from base classes? 4450 4451 // TODO: don't diagnose for inaccessible shadowed members. 4452 // This is hard to do perfectly because we might friend the 4453 // shadowing context, but that's just a false negative. 4454 } 4455 4456 // Determine what kind of declaration we're shadowing. 4457 unsigned Kind; 4458 if (isa<RecordDecl>(OldDC)) { 4459 if (isa<FieldDecl>(ShadowedDecl)) 4460 Kind = 3; // field 4461 else 4462 Kind = 2; // static data member 4463 } else if (OldDC->isFileContext()) 4464 Kind = 1; // global 4465 else 4466 Kind = 0; // local 4467 4468 DeclarationName Name = R.getLookupName(); 4469 4470 // Emit warning and note. 4471 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 4472 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 4473 } 4474 4475 /// \brief Check -Wshadow without the advantage of a previous lookup. 4476 void Sema::CheckShadow(Scope *S, VarDecl *D) { 4477 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 4478 DiagnosticsEngine::Ignored) 4479 return; 4480 4481 LookupResult R(*this, D->getDeclName(), D->getLocation(), 4482 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4483 LookupName(R, S); 4484 CheckShadow(S, D, R); 4485 } 4486 4487 /// \brief Perform semantic checking on a newly-created variable 4488 /// declaration. 4489 /// 4490 /// This routine performs all of the type-checking required for a 4491 /// variable declaration once it has been built. It is used both to 4492 /// check variables after they have been parsed and their declarators 4493 /// have been translated into a declaration, and to check variables 4494 /// that have been instantiated from a template. 4495 /// 4496 /// Sets NewVD->isInvalidDecl() if an error was encountered. 4497 /// 4498 /// Returns true if the variable declaration is a redeclaration. 4499 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 4500 LookupResult &Previous) { 4501 // If the decl is already known invalid, don't check it. 4502 if (NewVD->isInvalidDecl()) 4503 return false; 4504 4505 QualType T = NewVD->getType(); 4506 4507 if (T->isObjCObjectType()) { 4508 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 4509 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 4510 T = Context.getObjCObjectPointerType(T); 4511 NewVD->setType(T); 4512 } 4513 4514 // Emit an error if an address space was applied to decl with local storage. 4515 // This includes arrays of objects with address space qualifiers, but not 4516 // automatic variables that point to other address spaces. 4517 // ISO/IEC TR 18037 S5.1.2 4518 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 4519 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 4520 NewVD->setInvalidDecl(); 4521 return false; 4522 } 4523 4524 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 4525 // scope. 4526 if ((getLangOpts().OpenCLVersion >= 120) 4527 && NewVD->isStaticLocal()) { 4528 Diag(NewVD->getLocation(), diag::err_static_function_scope); 4529 NewVD->setInvalidDecl(); 4530 return false; 4531 } 4532 4533 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 4534 && !NewVD->hasAttr<BlocksAttr>()) { 4535 if (getLangOpts().getGC() != LangOptions::NonGC) 4536 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 4537 else 4538 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 4539 } 4540 4541 bool isVM = T->isVariablyModifiedType(); 4542 if (isVM || NewVD->hasAttr<CleanupAttr>() || 4543 NewVD->hasAttr<BlocksAttr>()) 4544 getCurFunction()->setHasBranchProtectedScope(); 4545 4546 if ((isVM && NewVD->hasLinkage()) || 4547 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 4548 bool SizeIsNegative; 4549 llvm::APSInt Oversized; 4550 QualType FixedTy = 4551 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 4552 Oversized); 4553 4554 if (FixedTy.isNull() && T->isVariableArrayType()) { 4555 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 4556 // FIXME: This won't give the correct result for 4557 // int a[10][n]; 4558 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 4559 4560 if (NewVD->isFileVarDecl()) 4561 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 4562 << SizeRange; 4563 else if (NewVD->getStorageClass() == SC_Static) 4564 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 4565 << SizeRange; 4566 else 4567 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 4568 << SizeRange; 4569 NewVD->setInvalidDecl(); 4570 return false; 4571 } 4572 4573 if (FixedTy.isNull()) { 4574 if (NewVD->isFileVarDecl()) 4575 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 4576 else 4577 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 4578 NewVD->setInvalidDecl(); 4579 return false; 4580 } 4581 4582 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 4583 NewVD->setType(FixedTy); 4584 } 4585 4586 if (Previous.empty() && NewVD->isExternC()) { 4587 // Since we did not find anything by this name and we're declaring 4588 // an extern "C" variable, look for a non-visible extern "C" 4589 // declaration with the same name. 4590 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4591 = findLocallyScopedExternalDecl(NewVD->getDeclName()); 4592 if (Pos != LocallyScopedExternalDecls.end()) 4593 Previous.addDecl(Pos->second); 4594 } 4595 4596 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 4597 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 4598 << T; 4599 NewVD->setInvalidDecl(); 4600 return false; 4601 } 4602 4603 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 4604 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 4605 NewVD->setInvalidDecl(); 4606 return false; 4607 } 4608 4609 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 4610 Diag(NewVD->getLocation(), diag::err_block_on_vm); 4611 NewVD->setInvalidDecl(); 4612 return false; 4613 } 4614 4615 if (NewVD->isConstexpr() && !T->isDependentType() && 4616 RequireLiteralType(NewVD->getLocation(), T, 4617 diag::err_constexpr_var_non_literal)) { 4618 NewVD->setInvalidDecl(); 4619 return false; 4620 } 4621 4622 if (!Previous.empty()) { 4623 MergeVarDecl(NewVD, Previous); 4624 return true; 4625 } 4626 return false; 4627 } 4628 4629 /// \brief Data used with FindOverriddenMethod 4630 struct FindOverriddenMethodData { 4631 Sema *S; 4632 CXXMethodDecl *Method; 4633 }; 4634 4635 /// \brief Member lookup function that determines whether a given C++ 4636 /// method overrides a method in a base class, to be used with 4637 /// CXXRecordDecl::lookupInBases(). 4638 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 4639 CXXBasePath &Path, 4640 void *UserData) { 4641 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4642 4643 FindOverriddenMethodData *Data 4644 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 4645 4646 DeclarationName Name = Data->Method->getDeclName(); 4647 4648 // FIXME: Do we care about other names here too? 4649 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4650 // We really want to find the base class destructor here. 4651 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 4652 CanQualType CT = Data->S->Context.getCanonicalType(T); 4653 4654 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 4655 } 4656 4657 for (Path.Decls = BaseRecord->lookup(Name); 4658 Path.Decls.first != Path.Decls.second; 4659 ++Path.Decls.first) { 4660 NamedDecl *D = *Path.Decls.first; 4661 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4662 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 4663 return true; 4664 } 4665 } 4666 4667 return false; 4668 } 4669 4670 /// AddOverriddenMethods - See if a method overrides any in the base classes, 4671 /// and if so, check that it's a valid override and remember it. 4672 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4673 // Look for virtual methods in base classes that this method might override. 4674 CXXBasePaths Paths; 4675 FindOverriddenMethodData Data; 4676 Data.Method = MD; 4677 Data.S = this; 4678 bool AddedAny = false; 4679 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 4680 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 4681 E = Paths.found_decls_end(); I != E; ++I) { 4682 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 4683 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 4684 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 4685 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 4686 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 4687 AddedAny = true; 4688 } 4689 } 4690 } 4691 } 4692 4693 return AddedAny; 4694 } 4695 4696 namespace { 4697 // Struct for holding all of the extra arguments needed by 4698 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 4699 struct ActOnFDArgs { 4700 Scope *S; 4701 Declarator &D; 4702 MultiTemplateParamsArg TemplateParamLists; 4703 bool AddToScope; 4704 }; 4705 } 4706 4707 namespace { 4708 4709 // Callback to only accept typo corrections that have a non-zero edit distance. 4710 // Also only accept corrections that have the same parent decl. 4711 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 4712 public: 4713 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 4714 CXXRecordDecl *Parent) 4715 : Context(Context), OriginalFD(TypoFD), 4716 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 4717 4718 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 4719 if (candidate.getEditDistance() == 0) 4720 return false; 4721 4722 llvm::SmallVector<unsigned, 1> MismatchedParams; 4723 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 4724 CDeclEnd = candidate.end(); 4725 CDecl != CDeclEnd; ++CDecl) { 4726 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 4727 4728 if (FD && !FD->hasBody() && 4729 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 4730 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 4731 CXXRecordDecl *Parent = MD->getParent(); 4732 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 4733 return true; 4734 } else if (!ExpectedParent) { 4735 return true; 4736 } 4737 } 4738 } 4739 4740 return false; 4741 } 4742 4743 private: 4744 ASTContext &Context; 4745 FunctionDecl *OriginalFD; 4746 CXXRecordDecl *ExpectedParent; 4747 }; 4748 4749 } 4750 4751 /// \brief Generate diagnostics for an invalid function redeclaration. 4752 /// 4753 /// This routine handles generating the diagnostic messages for an invalid 4754 /// function redeclaration, including finding possible similar declarations 4755 /// or performing typo correction if there are no previous declarations with 4756 /// the same name. 4757 /// 4758 /// Returns a NamedDecl iff typo correction was performed and substituting in 4759 /// the new declaration name does not cause new errors. 4760 static NamedDecl* DiagnoseInvalidRedeclaration( 4761 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 4762 ActOnFDArgs &ExtraArgs) { 4763 NamedDecl *Result = NULL; 4764 DeclarationName Name = NewFD->getDeclName(); 4765 DeclContext *NewDC = NewFD->getDeclContext(); 4766 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 4767 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4768 llvm::SmallVector<unsigned, 1> MismatchedParams; 4769 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches; 4770 TypoCorrection Correction; 4771 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus && 4772 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 4773 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 4774 : diag::err_member_def_does_not_match; 4775 4776 NewFD->setInvalidDecl(); 4777 SemaRef.LookupQualifiedName(Prev, NewDC); 4778 assert(!Prev.isAmbiguous() && 4779 "Cannot have an ambiguity in previous-declaration lookup"); 4780 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 4781 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 4782 MD ? MD->getParent() : 0); 4783 if (!Prev.empty()) { 4784 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 4785 Func != FuncEnd; ++Func) { 4786 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 4787 if (FD && 4788 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 4789 // Add 1 to the index so that 0 can mean the mismatch didn't 4790 // involve a parameter 4791 unsigned ParamNum = 4792 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 4793 NearMatches.push_back(std::make_pair(FD, ParamNum)); 4794 } 4795 } 4796 // If the qualified name lookup yielded nothing, try typo correction 4797 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 4798 Prev.getLookupKind(), 0, 0, 4799 Validator, NewDC))) { 4800 // Trap errors. 4801 Sema::SFINAETrap Trap(SemaRef); 4802 4803 // Set up everything for the call to ActOnFunctionDeclarator 4804 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 4805 ExtraArgs.D.getIdentifierLoc()); 4806 Previous.clear(); 4807 Previous.setLookupName(Correction.getCorrection()); 4808 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 4809 CDeclEnd = Correction.end(); 4810 CDecl != CDeclEnd; ++CDecl) { 4811 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 4812 if (FD && !FD->hasBody() && 4813 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 4814 Previous.addDecl(FD); 4815 } 4816 } 4817 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 4818 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 4819 // pieces need to verify the typo-corrected C++ declaraction and hopefully 4820 // eliminate the need for the parameter pack ExtraArgs. 4821 Result = SemaRef.ActOnFunctionDeclarator( 4822 ExtraArgs.S, ExtraArgs.D, 4823 Correction.getCorrectionDecl()->getDeclContext(), 4824 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 4825 ExtraArgs.AddToScope); 4826 if (Trap.hasErrorOccurred()) { 4827 // Pretend the typo correction never occurred 4828 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 4829 ExtraArgs.D.getIdentifierLoc()); 4830 ExtraArgs.D.setRedeclaration(wasRedeclaration); 4831 Previous.clear(); 4832 Previous.setLookupName(Name); 4833 Result = NULL; 4834 } else { 4835 for (LookupResult::iterator Func = Previous.begin(), 4836 FuncEnd = Previous.end(); 4837 Func != FuncEnd; ++Func) { 4838 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 4839 NearMatches.push_back(std::make_pair(FD, 0)); 4840 } 4841 } 4842 if (NearMatches.empty()) { 4843 // Ignore the correction if it didn't yield any close FunctionDecl matches 4844 Correction = TypoCorrection(); 4845 } else { 4846 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 4847 : diag::err_member_def_does_not_match_suggest; 4848 } 4849 } 4850 4851 if (Correction) { 4852 SourceRange FixItLoc(NewFD->getLocation()); 4853 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec(); 4854 if (Correction.getCorrectionSpecifier() && SS.isValid()) 4855 FixItLoc.setBegin(SS.getBeginLoc()); 4856 SemaRef.Diag(NewFD->getLocStart(), DiagMsg) 4857 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts()) 4858 << FixItHint::CreateReplacement( 4859 FixItLoc, Correction.getAsString(SemaRef.getLangOpts())); 4860 } else { 4861 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 4862 << Name << NewDC << NewFD->getLocation(); 4863 } 4864 4865 bool NewFDisConst = false; 4866 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 4867 NewFDisConst = NewMD->isConst(); 4868 4869 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator 4870 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 4871 NearMatch != NearMatchEnd; ++NearMatch) { 4872 FunctionDecl *FD = NearMatch->first; 4873 bool FDisConst = false; 4874 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 4875 FDisConst = MD->isConst(); 4876 4877 if (unsigned Idx = NearMatch->second) { 4878 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 4879 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 4880 if (Loc.isInvalid()) Loc = FD->getLocation(); 4881 SemaRef.Diag(Loc, diag::note_member_def_close_param_match) 4882 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 4883 } else if (Correction) { 4884 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 4885 << Correction.getQuoted(SemaRef.getLangOpts()); 4886 } else if (FDisConst != NewFDisConst) { 4887 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 4888 << NewFDisConst << FD->getSourceRange().getEnd(); 4889 } else 4890 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 4891 } 4892 return Result; 4893 } 4894 4895 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 4896 Declarator &D) { 4897 switch (D.getDeclSpec().getStorageClassSpec()) { 4898 default: llvm_unreachable("Unknown storage class!"); 4899 case DeclSpec::SCS_auto: 4900 case DeclSpec::SCS_register: 4901 case DeclSpec::SCS_mutable: 4902 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4903 diag::err_typecheck_sclass_func); 4904 D.setInvalidType(); 4905 break; 4906 case DeclSpec::SCS_unspecified: break; 4907 case DeclSpec::SCS_extern: return SC_Extern; 4908 case DeclSpec::SCS_static: { 4909 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 4910 // C99 6.7.1p5: 4911 // The declaration of an identifier for a function that has 4912 // block scope shall have no explicit storage-class specifier 4913 // other than extern 4914 // See also (C++ [dcl.stc]p4). 4915 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4916 diag::err_static_block_func); 4917 break; 4918 } else 4919 return SC_Static; 4920 } 4921 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4922 } 4923 4924 // No explicit storage class has already been returned 4925 return SC_None; 4926 } 4927 4928 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 4929 DeclContext *DC, QualType &R, 4930 TypeSourceInfo *TInfo, 4931 FunctionDecl::StorageClass SC, 4932 bool &IsVirtualOkay) { 4933 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 4934 DeclarationName Name = NameInfo.getName(); 4935 4936 FunctionDecl *NewFD = 0; 4937 bool isInline = D.getDeclSpec().isInlineSpecified(); 4938 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4939 FunctionDecl::StorageClass SCAsWritten 4940 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 4941 4942 if (!SemaRef.getLangOpts().CPlusPlus) { 4943 // Determine whether the function was written with a 4944 // prototype. This true when: 4945 // - there is a prototype in the declarator, or 4946 // - the type R of the function is some kind of typedef or other reference 4947 // to a type name (which eventually refers to a function type). 4948 bool HasPrototype = 4949 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 4950 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 4951 4952 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 4953 D.getLocStart(), NameInfo, R, 4954 TInfo, SC, SCAsWritten, isInline, 4955 HasPrototype); 4956 if (D.isInvalidType()) 4957 NewFD->setInvalidDecl(); 4958 4959 // Set the lexical context. 4960 NewFD->setLexicalDeclContext(SemaRef.CurContext); 4961 4962 return NewFD; 4963 } 4964 4965 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 4966 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 4967 4968 // Check that the return type is not an abstract class type. 4969 // For record types, this is done by the AbstractClassUsageDiagnoser once 4970 // the class has been completely parsed. 4971 if (!DC->isRecord() && 4972 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 4973 R->getAs<FunctionType>()->getResultType(), 4974 diag::err_abstract_type_in_decl, 4975 SemaRef.AbstractReturnType)) 4976 D.setInvalidType(); 4977 4978 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 4979 // This is a C++ constructor declaration. 4980 assert(DC->isRecord() && 4981 "Constructors can only be declared in a member context"); 4982 4983 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 4984 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 4985 D.getLocStart(), NameInfo, 4986 R, TInfo, isExplicit, isInline, 4987 /*isImplicitlyDeclared=*/false, 4988 isConstexpr); 4989 4990 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4991 // This is a C++ destructor declaration. 4992 if (DC->isRecord()) { 4993 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 4994 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 4995 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 4996 SemaRef.Context, Record, 4997 D.getLocStart(), 4998 NameInfo, R, TInfo, isInline, 4999 /*isImplicitlyDeclared=*/false); 5000 5001 // If the class is complete, then we now create the implicit exception 5002 // specification. If the class is incomplete or dependent, we can't do 5003 // it yet. 5004 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() && 5005 Record->getDefinition() && !Record->isBeingDefined() && 5006 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 5007 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 5008 } 5009 5010 IsVirtualOkay = true; 5011 return NewDD; 5012 5013 } else { 5014 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 5015 D.setInvalidType(); 5016 5017 // Create a FunctionDecl to satisfy the function definition parsing 5018 // code path. 5019 return FunctionDecl::Create(SemaRef.Context, DC, 5020 D.getLocStart(), 5021 D.getIdentifierLoc(), Name, R, TInfo, 5022 SC, SCAsWritten, isInline, 5023 /*hasPrototype=*/true, isConstexpr); 5024 } 5025 5026 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 5027 if (!DC->isRecord()) { 5028 SemaRef.Diag(D.getIdentifierLoc(), 5029 diag::err_conv_function_not_member); 5030 return 0; 5031 } 5032 5033 SemaRef.CheckConversionDeclarator(D, R, SC); 5034 IsVirtualOkay = true; 5035 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5036 D.getLocStart(), NameInfo, 5037 R, TInfo, isInline, isExplicit, 5038 isConstexpr, SourceLocation()); 5039 5040 } else if (DC->isRecord()) { 5041 // If the name of the function is the same as the name of the record, 5042 // then this must be an invalid constructor that has a return type. 5043 // (The parser checks for a return type and makes the declarator a 5044 // constructor if it has no return type). 5045 if (Name.getAsIdentifierInfo() && 5046 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 5047 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 5048 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5049 << SourceRange(D.getIdentifierLoc()); 5050 return 0; 5051 } 5052 5053 bool isStatic = SC == SC_Static; 5054 5055 // [class.free]p1: 5056 // Any allocation function for a class T is a static member 5057 // (even if not explicitly declared static). 5058 if (Name.getCXXOverloadedOperator() == OO_New || 5059 Name.getCXXOverloadedOperator() == OO_Array_New) 5060 isStatic = true; 5061 5062 // [class.free]p6 Any deallocation function for a class X is a static member 5063 // (even if not explicitly declared static). 5064 if (Name.getCXXOverloadedOperator() == OO_Delete || 5065 Name.getCXXOverloadedOperator() == OO_Array_Delete) 5066 isStatic = true; 5067 5068 IsVirtualOkay = !isStatic; 5069 5070 // This is a C++ method declaration. 5071 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5072 D.getLocStart(), NameInfo, R, 5073 TInfo, isStatic, SCAsWritten, isInline, 5074 isConstexpr, SourceLocation()); 5075 5076 } else { 5077 // Determine whether the function was written with a 5078 // prototype. This true when: 5079 // - we're in C++ (where every function has a prototype), 5080 return FunctionDecl::Create(SemaRef.Context, DC, 5081 D.getLocStart(), 5082 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 5083 true/*HasPrototype*/, isConstexpr); 5084 } 5085 } 5086 5087 NamedDecl* 5088 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5089 TypeSourceInfo *TInfo, LookupResult &Previous, 5090 MultiTemplateParamsArg TemplateParamLists, 5091 bool &AddToScope) { 5092 QualType R = TInfo->getType(); 5093 5094 assert(R.getTypePtr()->isFunctionType()); 5095 5096 // TODO: consider using NameInfo for diagnostic. 5097 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5098 DeclarationName Name = NameInfo.getName(); 5099 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 5100 5101 if (D.getDeclSpec().isThreadSpecified()) 5102 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5103 5104 // Do not allow returning a objc interface by-value. 5105 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 5106 Diag(D.getIdentifierLoc(), 5107 diag::err_object_cannot_be_passed_returned_by_value) << 0 5108 << R->getAs<FunctionType>()->getResultType() 5109 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 5110 5111 QualType T = R->getAs<FunctionType>()->getResultType(); 5112 T = Context.getObjCObjectPointerType(T); 5113 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 5114 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 5115 R = Context.getFunctionType(T, FPT->arg_type_begin(), 5116 FPT->getNumArgs(), EPI); 5117 } 5118 else if (isa<FunctionNoProtoType>(R)) 5119 R = Context.getFunctionNoProtoType(T); 5120 } 5121 5122 bool isFriend = false; 5123 FunctionTemplateDecl *FunctionTemplate = 0; 5124 bool isExplicitSpecialization = false; 5125 bool isFunctionTemplateSpecialization = false; 5126 5127 bool isDependentClassScopeExplicitSpecialization = false; 5128 bool HasExplicitTemplateArgs = false; 5129 TemplateArgumentListInfo TemplateArgs; 5130 5131 bool isVirtualOkay = false; 5132 5133 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 5134 isVirtualOkay); 5135 if (!NewFD) return 0; 5136 5137 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 5138 NewFD->setTopLevelDeclInObjCContainer(); 5139 5140 if (getLangOpts().CPlusPlus) { 5141 bool isInline = D.getDeclSpec().isInlineSpecified(); 5142 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5143 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5144 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5145 isFriend = D.getDeclSpec().isFriendSpecified(); 5146 if (isFriend && !isInline && D.isFunctionDefinition()) { 5147 // C++ [class.friend]p5 5148 // A function can be defined in a friend declaration of a 5149 // class . . . . Such a function is implicitly inline. 5150 NewFD->setImplicitlyInline(); 5151 } 5152 5153 SetNestedNameSpecifier(NewFD, D); 5154 isExplicitSpecialization = false; 5155 isFunctionTemplateSpecialization = false; 5156 if (D.isInvalidType()) 5157 NewFD->setInvalidDecl(); 5158 5159 // Set the lexical context. If the declarator has a C++ 5160 // scope specifier, or is the object of a friend declaration, the 5161 // lexical context will be different from the semantic context. 5162 NewFD->setLexicalDeclContext(CurContext); 5163 5164 // Match up the template parameter lists with the scope specifier, then 5165 // determine whether we have a template or a template specialization. 5166 bool Invalid = false; 5167 if (TemplateParameterList *TemplateParams 5168 = MatchTemplateParametersToScopeSpecifier( 5169 D.getDeclSpec().getLocStart(), 5170 D.getIdentifierLoc(), 5171 D.getCXXScopeSpec(), 5172 TemplateParamLists.get(), 5173 TemplateParamLists.size(), 5174 isFriend, 5175 isExplicitSpecialization, 5176 Invalid)) { 5177 if (TemplateParams->size() > 0) { 5178 // This is a function template 5179 5180 // Check that we can declare a template here. 5181 if (CheckTemplateDeclScope(S, TemplateParams)) 5182 return 0; 5183 5184 // A destructor cannot be a template. 5185 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5186 Diag(NewFD->getLocation(), diag::err_destructor_template); 5187 return 0; 5188 } 5189 5190 // If we're adding a template to a dependent context, we may need to 5191 // rebuilding some of the types used within the template parameter list, 5192 // now that we know what the current instantiation is. 5193 if (DC->isDependentContext()) { 5194 ContextRAII SavedContext(*this, DC); 5195 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 5196 Invalid = true; 5197 } 5198 5199 5200 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 5201 NewFD->getLocation(), 5202 Name, TemplateParams, 5203 NewFD); 5204 FunctionTemplate->setLexicalDeclContext(CurContext); 5205 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 5206 5207 // For source fidelity, store the other template param lists. 5208 if (TemplateParamLists.size() > 1) { 5209 NewFD->setTemplateParameterListsInfo(Context, 5210 TemplateParamLists.size() - 1, 5211 TemplateParamLists.release()); 5212 } 5213 } else { 5214 // This is a function template specialization. 5215 isFunctionTemplateSpecialization = true; 5216 // For source fidelity, store all the template param lists. 5217 NewFD->setTemplateParameterListsInfo(Context, 5218 TemplateParamLists.size(), 5219 TemplateParamLists.release()); 5220 5221 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 5222 if (isFriend) { 5223 // We want to remove the "template<>", found here. 5224 SourceRange RemoveRange = TemplateParams->getSourceRange(); 5225 5226 // If we remove the template<> and the name is not a 5227 // template-id, we're actually silently creating a problem: 5228 // the friend declaration will refer to an untemplated decl, 5229 // and clearly the user wants a template specialization. So 5230 // we need to insert '<>' after the name. 5231 SourceLocation InsertLoc; 5232 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5233 InsertLoc = D.getName().getSourceRange().getEnd(); 5234 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 5235 } 5236 5237 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 5238 << Name << RemoveRange 5239 << FixItHint::CreateRemoval(RemoveRange) 5240 << FixItHint::CreateInsertion(InsertLoc, "<>"); 5241 } 5242 } 5243 } 5244 else { 5245 // All template param lists were matched against the scope specifier: 5246 // this is NOT (an explicit specialization of) a template. 5247 if (TemplateParamLists.size() > 0) 5248 // For source fidelity, store all the template param lists. 5249 NewFD->setTemplateParameterListsInfo(Context, 5250 TemplateParamLists.size(), 5251 TemplateParamLists.release()); 5252 } 5253 5254 if (Invalid) { 5255 NewFD->setInvalidDecl(); 5256 if (FunctionTemplate) 5257 FunctionTemplate->setInvalidDecl(); 5258 } 5259 5260 // C++ [dcl.fct.spec]p5: 5261 // The virtual specifier shall only be used in declarations of 5262 // nonstatic class member functions that appear within a 5263 // member-specification of a class declaration; see 10.3. 5264 // 5265 if (isVirtual && !NewFD->isInvalidDecl()) { 5266 if (!isVirtualOkay) { 5267 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5268 diag::err_virtual_non_function); 5269 } else if (!CurContext->isRecord()) { 5270 // 'virtual' was specified outside of the class. 5271 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5272 diag::err_virtual_out_of_class) 5273 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5274 } else if (NewFD->getDescribedFunctionTemplate()) { 5275 // C++ [temp.mem]p3: 5276 // A member function template shall not be virtual. 5277 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5278 diag::err_virtual_member_function_template) 5279 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5280 } else { 5281 // Okay: Add virtual to the method. 5282 NewFD->setVirtualAsWritten(true); 5283 } 5284 } 5285 5286 // C++ [dcl.fct.spec]p3: 5287 // The inline specifier shall not appear on a block scope function 5288 // declaration. 5289 if (isInline && !NewFD->isInvalidDecl()) { 5290 if (CurContext->isFunctionOrMethod()) { 5291 // 'inline' is not allowed on block scope function declaration. 5292 Diag(D.getDeclSpec().getInlineSpecLoc(), 5293 diag::err_inline_declaration_block_scope) << Name 5294 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 5295 } 5296 } 5297 5298 // C++ [dcl.fct.spec]p6: 5299 // The explicit specifier shall be used only in the declaration of a 5300 // constructor or conversion function within its class definition; 5301 // see 12.3.1 and 12.3.2. 5302 if (isExplicit && !NewFD->isInvalidDecl()) { 5303 if (!CurContext->isRecord()) { 5304 // 'explicit' was specified outside of the class. 5305 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5306 diag::err_explicit_out_of_class) 5307 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5308 } else if (!isa<CXXConstructorDecl>(NewFD) && 5309 !isa<CXXConversionDecl>(NewFD)) { 5310 // 'explicit' was specified on a function that wasn't a constructor 5311 // or conversion function. 5312 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5313 diag::err_explicit_non_ctor_or_conv_function) 5314 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5315 } 5316 } 5317 5318 if (isConstexpr) { 5319 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors 5320 // are implicitly inline. 5321 NewFD->setImplicitlyInline(); 5322 5323 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to 5324 // be either constructors or to return a literal type. Therefore, 5325 // destructors cannot be declared constexpr. 5326 if (isa<CXXDestructorDecl>(NewFD)) 5327 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 5328 } 5329 5330 // If __module_private__ was specified, mark the function accordingly. 5331 if (D.getDeclSpec().isModulePrivateSpecified()) { 5332 if (isFunctionTemplateSpecialization) { 5333 SourceLocation ModulePrivateLoc 5334 = D.getDeclSpec().getModulePrivateSpecLoc(); 5335 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 5336 << 0 5337 << FixItHint::CreateRemoval(ModulePrivateLoc); 5338 } else { 5339 NewFD->setModulePrivate(); 5340 if (FunctionTemplate) 5341 FunctionTemplate->setModulePrivate(); 5342 } 5343 } 5344 5345 if (isFriend) { 5346 // For now, claim that the objects have no previous declaration. 5347 if (FunctionTemplate) { 5348 FunctionTemplate->setObjectOfFriendDecl(false); 5349 FunctionTemplate->setAccess(AS_public); 5350 } 5351 NewFD->setObjectOfFriendDecl(false); 5352 NewFD->setAccess(AS_public); 5353 } 5354 5355 // If a function is defined as defaulted or deleted, mark it as such now. 5356 switch (D.getFunctionDefinitionKind()) { 5357 case FDK_Declaration: 5358 case FDK_Definition: 5359 break; 5360 5361 case FDK_Defaulted: 5362 NewFD->setDefaulted(); 5363 break; 5364 5365 case FDK_Deleted: 5366 NewFD->setDeletedAsWritten(); 5367 break; 5368 } 5369 5370 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 5371 D.isFunctionDefinition()) { 5372 // C++ [class.mfct]p2: 5373 // A member function may be defined (8.4) in its class definition, in 5374 // which case it is an inline member function (7.1.2) 5375 NewFD->setImplicitlyInline(); 5376 } 5377 5378 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 5379 !CurContext->isRecord()) { 5380 // C++ [class.static]p1: 5381 // A data or function member of a class may be declared static 5382 // in a class definition, in which case it is a static member of 5383 // the class. 5384 5385 // Complain about the 'static' specifier if it's on an out-of-line 5386 // member function definition. 5387 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5388 diag::err_static_out_of_line) 5389 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5390 } 5391 } 5392 5393 // Filter out previous declarations that don't match the scope. 5394 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 5395 isExplicitSpecialization || 5396 isFunctionTemplateSpecialization); 5397 5398 // Handle GNU asm-label extension (encoded as an attribute). 5399 if (Expr *E = (Expr*) D.getAsmLabel()) { 5400 // The parser guarantees this is a string. 5401 StringLiteral *SE = cast<StringLiteral>(E); 5402 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 5403 SE->getString())); 5404 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5405 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5406 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 5407 if (I != ExtnameUndeclaredIdentifiers.end()) { 5408 NewFD->addAttr(I->second); 5409 ExtnameUndeclaredIdentifiers.erase(I); 5410 } 5411 } 5412 5413 // Copy the parameter declarations from the declarator D to the function 5414 // declaration NewFD, if they are available. First scavenge them into Params. 5415 SmallVector<ParmVarDecl*, 16> Params; 5416 if (D.isFunctionDeclarator()) { 5417 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5418 5419 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 5420 // function that takes no arguments, not a function that takes a 5421 // single void argument. 5422 // We let through "const void" here because Sema::GetTypeForDeclarator 5423 // already checks for that case. 5424 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5425 FTI.ArgInfo[0].Param && 5426 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 5427 // Empty arg list, don't push any params. 5428 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param); 5429 5430 // In C++, the empty parameter-type-list must be spelled "void"; a 5431 // typedef of void is not permitted. 5432 if (getLangOpts().CPlusPlus && 5433 Param->getType().getUnqualifiedType() != Context.VoidTy) { 5434 bool IsTypeAlias = false; 5435 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 5436 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 5437 else if (const TemplateSpecializationType *TST = 5438 Param->getType()->getAs<TemplateSpecializationType>()) 5439 IsTypeAlias = TST->isTypeAlias(); 5440 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 5441 << IsTypeAlias; 5442 } 5443 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 5444 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 5445 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 5446 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 5447 Param->setDeclContext(NewFD); 5448 Params.push_back(Param); 5449 5450 if (Param->isInvalidDecl()) 5451 NewFD->setInvalidDecl(); 5452 } 5453 } 5454 5455 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 5456 // When we're declaring a function with a typedef, typeof, etc as in the 5457 // following example, we'll need to synthesize (unnamed) 5458 // parameters for use in the declaration. 5459 // 5460 // @code 5461 // typedef void fn(int); 5462 // fn f; 5463 // @endcode 5464 5465 // Synthesize a parameter for each argument type. 5466 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 5467 AE = FT->arg_type_end(); AI != AE; ++AI) { 5468 ParmVarDecl *Param = 5469 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 5470 Param->setScopeInfo(0, Params.size()); 5471 Params.push_back(Param); 5472 } 5473 } else { 5474 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 5475 "Should not need args for typedef of non-prototype fn"); 5476 } 5477 5478 // Finally, we know we have the right number of parameters, install them. 5479 NewFD->setParams(Params); 5480 5481 // Find all anonymous symbols defined during the declaration of this function 5482 // and add to NewFD. This lets us track decls such 'enum Y' in: 5483 // 5484 // void f(enum Y {AA} x) {} 5485 // 5486 // which would otherwise incorrectly end up in the translation unit scope. 5487 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 5488 DeclsInPrototypeScope.clear(); 5489 5490 // Process the non-inheritable attributes on this declaration. 5491 ProcessDeclAttributes(S, NewFD, D, 5492 /*NonInheritable=*/true, /*Inheritable=*/false); 5493 5494 // Functions returning a variably modified type violate C99 6.7.5.2p2 5495 // because all functions have linkage. 5496 if (!NewFD->isInvalidDecl() && 5497 NewFD->getResultType()->isVariablyModifiedType()) { 5498 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 5499 NewFD->setInvalidDecl(); 5500 } 5501 5502 // Handle attributes. 5503 ProcessDeclAttributes(S, NewFD, D, 5504 /*NonInheritable=*/false, /*Inheritable=*/true); 5505 5506 if (!getLangOpts().CPlusPlus) { 5507 // Perform semantic checking on the function declaration. 5508 bool isExplicitSpecialization=false; 5509 if (!NewFD->isInvalidDecl()) { 5510 if (NewFD->isMain()) 5511 CheckMain(NewFD, D.getDeclSpec()); 5512 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5513 isExplicitSpecialization)); 5514 } 5515 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5516 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5517 "previous declaration set still overloaded"); 5518 } else { 5519 // If the declarator is a template-id, translate the parser's template 5520 // argument list into our AST format. 5521 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5522 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5523 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 5524 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 5525 ASTTemplateArgsPtr TemplateArgsPtr(*this, 5526 TemplateId->getTemplateArgs(), 5527 TemplateId->NumArgs); 5528 translateTemplateArguments(TemplateArgsPtr, 5529 TemplateArgs); 5530 TemplateArgsPtr.release(); 5531 5532 HasExplicitTemplateArgs = true; 5533 5534 if (NewFD->isInvalidDecl()) { 5535 HasExplicitTemplateArgs = false; 5536 } else if (FunctionTemplate) { 5537 // Function template with explicit template arguments. 5538 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 5539 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 5540 5541 HasExplicitTemplateArgs = false; 5542 } else if (!isFunctionTemplateSpecialization && 5543 !D.getDeclSpec().isFriendSpecified()) { 5544 // We have encountered something that the user meant to be a 5545 // specialization (because it has explicitly-specified template 5546 // arguments) but that was not introduced with a "template<>" (or had 5547 // too few of them). 5548 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5549 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5550 << FixItHint::CreateInsertion( 5551 D.getDeclSpec().getLocStart(), 5552 "template<> "); 5553 isFunctionTemplateSpecialization = true; 5554 } else { 5555 // "friend void foo<>(int);" is an implicit specialization decl. 5556 isFunctionTemplateSpecialization = true; 5557 } 5558 } else if (isFriend && isFunctionTemplateSpecialization) { 5559 // This combination is only possible in a recovery case; the user 5560 // wrote something like: 5561 // template <> friend void foo(int); 5562 // which we're recovering from as if the user had written: 5563 // friend void foo<>(int); 5564 // Go ahead and fake up a template id. 5565 HasExplicitTemplateArgs = true; 5566 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 5567 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 5568 } 5569 5570 // If it's a friend (and only if it's a friend), it's possible 5571 // that either the specialized function type or the specialized 5572 // template is dependent, and therefore matching will fail. In 5573 // this case, don't check the specialization yet. 5574 bool InstantiationDependent = false; 5575 if (isFunctionTemplateSpecialization && isFriend && 5576 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 5577 TemplateSpecializationType::anyDependentTemplateArguments( 5578 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 5579 InstantiationDependent))) { 5580 assert(HasExplicitTemplateArgs && 5581 "friend function specialization without template args"); 5582 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 5583 Previous)) 5584 NewFD->setInvalidDecl(); 5585 } else if (isFunctionTemplateSpecialization) { 5586 if (CurContext->isDependentContext() && CurContext->isRecord() 5587 && !isFriend) { 5588 isDependentClassScopeExplicitSpecialization = true; 5589 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 5590 diag::ext_function_specialization_in_class : 5591 diag::err_function_specialization_in_class) 5592 << NewFD->getDeclName(); 5593 } else if (CheckFunctionTemplateSpecialization(NewFD, 5594 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 5595 Previous)) 5596 NewFD->setInvalidDecl(); 5597 5598 // C++ [dcl.stc]p1: 5599 // A storage-class-specifier shall not be specified in an explicit 5600 // specialization (14.7.3) 5601 if (SC != SC_None) { 5602 if (SC != NewFD->getStorageClass()) 5603 Diag(NewFD->getLocation(), 5604 diag::err_explicit_specialization_inconsistent_storage_class) 5605 << SC 5606 << FixItHint::CreateRemoval( 5607 D.getDeclSpec().getStorageClassSpecLoc()); 5608 5609 else 5610 Diag(NewFD->getLocation(), 5611 diag::ext_explicit_specialization_storage_class) 5612 << FixItHint::CreateRemoval( 5613 D.getDeclSpec().getStorageClassSpecLoc()); 5614 } 5615 5616 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 5617 if (CheckMemberSpecialization(NewFD, Previous)) 5618 NewFD->setInvalidDecl(); 5619 } 5620 5621 // Perform semantic checking on the function declaration. 5622 if (!isDependentClassScopeExplicitSpecialization) { 5623 if (NewFD->isInvalidDecl()) { 5624 // If this is a class member, mark the class invalid immediately. 5625 // This avoids some consistency errors later. 5626 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 5627 methodDecl->getParent()->setInvalidDecl(); 5628 } else { 5629 if (NewFD->isMain()) 5630 CheckMain(NewFD, D.getDeclSpec()); 5631 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5632 isExplicitSpecialization)); 5633 } 5634 } 5635 5636 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5637 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5638 "previous declaration set still overloaded"); 5639 5640 NamedDecl *PrincipalDecl = (FunctionTemplate 5641 ? cast<NamedDecl>(FunctionTemplate) 5642 : NewFD); 5643 5644 if (isFriend && D.isRedeclaration()) { 5645 AccessSpecifier Access = AS_public; 5646 if (!NewFD->isInvalidDecl()) 5647 Access = NewFD->getPreviousDecl()->getAccess(); 5648 5649 NewFD->setAccess(Access); 5650 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 5651 5652 PrincipalDecl->setObjectOfFriendDecl(true); 5653 } 5654 5655 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 5656 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5657 PrincipalDecl->setNonMemberOperator(); 5658 5659 // If we have a function template, check the template parameter 5660 // list. This will check and merge default template arguments. 5661 if (FunctionTemplate) { 5662 FunctionTemplateDecl *PrevTemplate = 5663 FunctionTemplate->getPreviousDecl(); 5664 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 5665 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 5666 D.getDeclSpec().isFriendSpecified() 5667 ? (D.isFunctionDefinition() 5668 ? TPC_FriendFunctionTemplateDefinition 5669 : TPC_FriendFunctionTemplate) 5670 : (D.getCXXScopeSpec().isSet() && 5671 DC && DC->isRecord() && 5672 DC->isDependentContext()) 5673 ? TPC_ClassTemplateMember 5674 : TPC_FunctionTemplate); 5675 } 5676 5677 if (NewFD->isInvalidDecl()) { 5678 // Ignore all the rest of this. 5679 } else if (!D.isRedeclaration()) { 5680 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 5681 AddToScope }; 5682 // Fake up an access specifier if it's supposed to be a class member. 5683 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 5684 NewFD->setAccess(AS_public); 5685 5686 // Qualified decls generally require a previous declaration. 5687 if (D.getCXXScopeSpec().isSet()) { 5688 // ...with the major exception of templated-scope or 5689 // dependent-scope friend declarations. 5690 5691 // TODO: we currently also suppress this check in dependent 5692 // contexts because (1) the parameter depth will be off when 5693 // matching friend templates and (2) we might actually be 5694 // selecting a friend based on a dependent factor. But there 5695 // are situations where these conditions don't apply and we 5696 // can actually do this check immediately. 5697 if (isFriend && 5698 (TemplateParamLists.size() || 5699 D.getCXXScopeSpec().getScopeRep()->isDependent() || 5700 CurContext->isDependentContext())) { 5701 // ignore these 5702 } else { 5703 // The user tried to provide an out-of-line definition for a 5704 // function that is a member of a class or namespace, but there 5705 // was no such member function declared (C++ [class.mfct]p2, 5706 // C++ [namespace.memdef]p2). For example: 5707 // 5708 // class X { 5709 // void f() const; 5710 // }; 5711 // 5712 // void X::f() { } // ill-formed 5713 // 5714 // Complain about this problem, and attempt to suggest close 5715 // matches (e.g., those that differ only in cv-qualifiers and 5716 // whether the parameter types are references). 5717 5718 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 5719 NewFD, 5720 ExtraArgs)) { 5721 AddToScope = ExtraArgs.AddToScope; 5722 return Result; 5723 } 5724 } 5725 5726 // Unqualified local friend declarations are required to resolve 5727 // to something. 5728 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 5729 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 5730 NewFD, 5731 ExtraArgs)) { 5732 AddToScope = ExtraArgs.AddToScope; 5733 return Result; 5734 } 5735 } 5736 5737 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 5738 !isFriend && !isFunctionTemplateSpecialization && 5739 !isExplicitSpecialization) { 5740 // An out-of-line member function declaration must also be a 5741 // definition (C++ [dcl.meaning]p1). 5742 // Note that this is not the case for explicit specializations of 5743 // function templates or member functions of class templates, per 5744 // C++ [temp.expl.spec]p2. We also allow these declarations as an 5745 // extension for compatibility with old SWIG code which likes to 5746 // generate them. 5747 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 5748 << D.getCXXScopeSpec().getRange(); 5749 } 5750 } 5751 5752 AddKnownFunctionAttributes(NewFD); 5753 5754 if (NewFD->hasAttr<OverloadableAttr>() && 5755 !NewFD->getType()->getAs<FunctionProtoType>()) { 5756 Diag(NewFD->getLocation(), 5757 diag::err_attribute_overloadable_no_prototype) 5758 << NewFD; 5759 5760 // Turn this into a variadic function with no parameters. 5761 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 5762 FunctionProtoType::ExtProtoInfo EPI; 5763 EPI.Variadic = true; 5764 EPI.ExtInfo = FT->getExtInfo(); 5765 5766 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 5767 NewFD->setType(R); 5768 } 5769 5770 // If there's a #pragma GCC visibility in scope, and this isn't a class 5771 // member, set the visibility of this function. 5772 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 5773 AddPushedVisibilityAttribute(NewFD); 5774 5775 // If there's a #pragma clang arc_cf_code_audited in scope, consider 5776 // marking the function. 5777 AddCFAuditedAttribute(NewFD); 5778 5779 // If this is a locally-scoped extern C function, update the 5780 // map of such names. 5781 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 5782 && !NewFD->isInvalidDecl()) 5783 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 5784 5785 // Set this FunctionDecl's range up to the right paren. 5786 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 5787 5788 if (getLangOpts().CPlusPlus) { 5789 if (FunctionTemplate) { 5790 if (NewFD->isInvalidDecl()) 5791 FunctionTemplate->setInvalidDecl(); 5792 return FunctionTemplate; 5793 } 5794 } 5795 5796 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 5797 if ((getLangOpts().OpenCLVersion >= 120) 5798 && NewFD->hasAttr<OpenCLKernelAttr>() 5799 && (SC == SC_Static)) { 5800 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 5801 D.setInvalidType(); 5802 } 5803 5804 MarkUnusedFileScopedDecl(NewFD); 5805 5806 if (getLangOpts().CUDA) 5807 if (IdentifierInfo *II = NewFD->getIdentifier()) 5808 if (!NewFD->isInvalidDecl() && 5809 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5810 if (II->isStr("cudaConfigureCall")) { 5811 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 5812 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 5813 5814 Context.setcudaConfigureCallDecl(NewFD); 5815 } 5816 } 5817 5818 // Here we have an function template explicit specialization at class scope. 5819 // The actually specialization will be postponed to template instatiation 5820 // time via the ClassScopeFunctionSpecializationDecl node. 5821 if (isDependentClassScopeExplicitSpecialization) { 5822 ClassScopeFunctionSpecializationDecl *NewSpec = 5823 ClassScopeFunctionSpecializationDecl::Create( 5824 Context, CurContext, SourceLocation(), 5825 cast<CXXMethodDecl>(NewFD), 5826 HasExplicitTemplateArgs, TemplateArgs); 5827 CurContext->addDecl(NewSpec); 5828 AddToScope = false; 5829 } 5830 5831 return NewFD; 5832 } 5833 5834 /// \brief Perform semantic checking of a new function declaration. 5835 /// 5836 /// Performs semantic analysis of the new function declaration 5837 /// NewFD. This routine performs all semantic checking that does not 5838 /// require the actual declarator involved in the declaration, and is 5839 /// used both for the declaration of functions as they are parsed 5840 /// (called via ActOnDeclarator) and for the declaration of functions 5841 /// that have been instantiated via C++ template instantiation (called 5842 /// via InstantiateDecl). 5843 /// 5844 /// \param IsExplicitSpecialization whether this new function declaration is 5845 /// an explicit specialization of the previous declaration. 5846 /// 5847 /// This sets NewFD->isInvalidDecl() to true if there was an error. 5848 /// 5849 /// \returns true if the function declaration is a redeclaration. 5850 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 5851 LookupResult &Previous, 5852 bool IsExplicitSpecialization) { 5853 assert(!NewFD->getResultType()->isVariablyModifiedType() 5854 && "Variably modified return types are not handled here"); 5855 5856 // Check for a previous declaration of this name. 5857 if (Previous.empty() && NewFD->isExternC()) { 5858 // Since we did not find anything by this name and we're declaring 5859 // an extern "C" function, look for a non-visible extern "C" 5860 // declaration with the same name. 5861 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5862 = findLocallyScopedExternalDecl(NewFD->getDeclName()); 5863 if (Pos != LocallyScopedExternalDecls.end()) 5864 Previous.addDecl(Pos->second); 5865 } 5866 5867 bool Redeclaration = false; 5868 5869 // Merge or overload the declaration with an existing declaration of 5870 // the same name, if appropriate. 5871 if (!Previous.empty()) { 5872 // Determine whether NewFD is an overload of PrevDecl or 5873 // a declaration that requires merging. If it's an overload, 5874 // there's no more work to do here; we'll just add the new 5875 // function to the scope. 5876 5877 NamedDecl *OldDecl = 0; 5878 if (!AllowOverloadingOfFunction(Previous, Context)) { 5879 Redeclaration = true; 5880 OldDecl = Previous.getFoundDecl(); 5881 } else { 5882 switch (CheckOverload(S, NewFD, Previous, OldDecl, 5883 /*NewIsUsingDecl*/ false)) { 5884 case Ovl_Match: 5885 Redeclaration = true; 5886 break; 5887 5888 case Ovl_NonFunction: 5889 Redeclaration = true; 5890 break; 5891 5892 case Ovl_Overload: 5893 Redeclaration = false; 5894 break; 5895 } 5896 5897 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 5898 // If a function name is overloadable in C, then every function 5899 // with that name must be marked "overloadable". 5900 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 5901 << Redeclaration << NewFD; 5902 NamedDecl *OverloadedDecl = 0; 5903 if (Redeclaration) 5904 OverloadedDecl = OldDecl; 5905 else if (!Previous.empty()) 5906 OverloadedDecl = Previous.getRepresentativeDecl(); 5907 if (OverloadedDecl) 5908 Diag(OverloadedDecl->getLocation(), 5909 diag::note_attribute_overloadable_prev_overload); 5910 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 5911 Context)); 5912 } 5913 } 5914 5915 if (Redeclaration) { 5916 // NewFD and OldDecl represent declarations that need to be 5917 // merged. 5918 if (MergeFunctionDecl(NewFD, OldDecl, S)) { 5919 NewFD->setInvalidDecl(); 5920 return Redeclaration; 5921 } 5922 5923 Previous.clear(); 5924 Previous.addDecl(OldDecl); 5925 5926 if (FunctionTemplateDecl *OldTemplateDecl 5927 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 5928 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 5929 FunctionTemplateDecl *NewTemplateDecl 5930 = NewFD->getDescribedFunctionTemplate(); 5931 assert(NewTemplateDecl && "Template/non-template mismatch"); 5932 if (CXXMethodDecl *Method 5933 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 5934 Method->setAccess(OldTemplateDecl->getAccess()); 5935 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 5936 } 5937 5938 // If this is an explicit specialization of a member that is a function 5939 // template, mark it as a member specialization. 5940 if (IsExplicitSpecialization && 5941 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 5942 NewTemplateDecl->setMemberSpecialization(); 5943 assert(OldTemplateDecl->isMemberSpecialization()); 5944 } 5945 5946 } else { 5947 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 5948 NewFD->setAccess(OldDecl->getAccess()); 5949 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 5950 } 5951 } 5952 } 5953 5954 // Semantic checking for this function declaration (in isolation). 5955 if (getLangOpts().CPlusPlus) { 5956 // C++-specific checks. 5957 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 5958 CheckConstructor(Constructor); 5959 } else if (CXXDestructorDecl *Destructor = 5960 dyn_cast<CXXDestructorDecl>(NewFD)) { 5961 CXXRecordDecl *Record = Destructor->getParent(); 5962 QualType ClassType = Context.getTypeDeclType(Record); 5963 5964 // FIXME: Shouldn't we be able to perform this check even when the class 5965 // type is dependent? Both gcc and edg can handle that. 5966 if (!ClassType->isDependentType()) { 5967 DeclarationName Name 5968 = Context.DeclarationNames.getCXXDestructorName( 5969 Context.getCanonicalType(ClassType)); 5970 if (NewFD->getDeclName() != Name) { 5971 Diag(NewFD->getLocation(), diag::err_destructor_name); 5972 NewFD->setInvalidDecl(); 5973 return Redeclaration; 5974 } 5975 } 5976 } else if (CXXConversionDecl *Conversion 5977 = dyn_cast<CXXConversionDecl>(NewFD)) { 5978 ActOnConversionDeclarator(Conversion); 5979 } 5980 5981 // Find any virtual functions that this function overrides. 5982 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 5983 if (!Method->isFunctionTemplateSpecialization() && 5984 !Method->getDescribedFunctionTemplate()) { 5985 if (AddOverriddenMethods(Method->getParent(), Method)) { 5986 // If the function was marked as "static", we have a problem. 5987 if (NewFD->getStorageClass() == SC_Static) { 5988 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual) 5989 << NewFD->getDeclName(); 5990 for (CXXMethodDecl::method_iterator 5991 Overridden = Method->begin_overridden_methods(), 5992 OverriddenEnd = Method->end_overridden_methods(); 5993 Overridden != OverriddenEnd; 5994 ++Overridden) { 5995 Diag((*Overridden)->getLocation(), 5996 diag::note_overridden_virtual_function); 5997 } 5998 } 5999 } 6000 } 6001 6002 if (Method->isStatic()) 6003 checkThisInStaticMemberFunctionType(Method); 6004 } 6005 6006 // Extra checking for C++ overloaded operators (C++ [over.oper]). 6007 if (NewFD->isOverloadedOperator() && 6008 CheckOverloadedOperatorDeclaration(NewFD)) { 6009 NewFD->setInvalidDecl(); 6010 return Redeclaration; 6011 } 6012 6013 // Extra checking for C++0x literal operators (C++0x [over.literal]). 6014 if (NewFD->getLiteralIdentifier() && 6015 CheckLiteralOperatorDeclaration(NewFD)) { 6016 NewFD->setInvalidDecl(); 6017 return Redeclaration; 6018 } 6019 6020 // In C++, check default arguments now that we have merged decls. Unless 6021 // the lexical context is the class, because in this case this is done 6022 // during delayed parsing anyway. 6023 if (!CurContext->isRecord()) 6024 CheckCXXDefaultArguments(NewFD); 6025 6026 // If this function declares a builtin function, check the type of this 6027 // declaration against the expected type for the builtin. 6028 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 6029 ASTContext::GetBuiltinTypeError Error; 6030 QualType T = Context.GetBuiltinType(BuiltinID, Error); 6031 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 6032 // The type of this function differs from the type of the builtin, 6033 // so forget about the builtin entirely. 6034 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 6035 } 6036 } 6037 6038 // If this function is declared as being extern "C", then check to see if 6039 // the function returns a UDT (class, struct, or union type) that is not C 6040 // compatible, and if it does, warn the user. 6041 if (NewFD->isExternC()) { 6042 QualType R = NewFD->getResultType(); 6043 if (R->isIncompleteType() && !R->isVoidType()) 6044 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 6045 << NewFD << R; 6046 else if (!R.isPODType(Context) && !R->isVoidType() && 6047 !R->isObjCObjectPointerType()) 6048 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 6049 } 6050 } 6051 return Redeclaration; 6052 } 6053 6054 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 6055 // C++11 [basic.start.main]p3: A program that declares main to be inline, 6056 // static or constexpr is ill-formed. 6057 // C99 6.7.4p4: In a hosted environment, the inline function specifier 6058 // shall not appear in a declaration of main. 6059 // static main is not an error under C99, but we should warn about it. 6060 if (FD->getStorageClass() == SC_Static) 6061 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 6062 ? diag::err_static_main : diag::warn_static_main) 6063 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 6064 if (FD->isInlineSpecified()) 6065 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 6066 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 6067 if (FD->isConstexpr()) { 6068 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 6069 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 6070 FD->setConstexpr(false); 6071 } 6072 6073 QualType T = FD->getType(); 6074 assert(T->isFunctionType() && "function decl is not of function type"); 6075 const FunctionType* FT = T->castAs<FunctionType>(); 6076 6077 // All the standards say that main() should should return 'int'. 6078 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 6079 // In C and C++, main magically returns 0 if you fall off the end; 6080 // set the flag which tells us that. 6081 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6082 FD->setHasImplicitReturnZero(true); 6083 6084 // In C with GNU extensions we allow main() to have non-integer return 6085 // type, but we should warn about the extension, and we disable the 6086 // implicit-return-zero rule. 6087 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 6088 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 6089 6090 // Otherwise, this is just a flat-out error. 6091 } else { 6092 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 6093 FD->setInvalidDecl(true); 6094 } 6095 6096 // Treat protoless main() as nullary. 6097 if (isa<FunctionNoProtoType>(FT)) return; 6098 6099 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 6100 unsigned nparams = FTP->getNumArgs(); 6101 assert(FD->getNumParams() == nparams); 6102 6103 bool HasExtraParameters = (nparams > 3); 6104 6105 // Darwin passes an undocumented fourth argument of type char**. If 6106 // other platforms start sprouting these, the logic below will start 6107 // getting shifty. 6108 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 6109 HasExtraParameters = false; 6110 6111 if (HasExtraParameters) { 6112 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 6113 FD->setInvalidDecl(true); 6114 nparams = 3; 6115 } 6116 6117 // FIXME: a lot of the following diagnostics would be improved 6118 // if we had some location information about types. 6119 6120 QualType CharPP = 6121 Context.getPointerType(Context.getPointerType(Context.CharTy)); 6122 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 6123 6124 for (unsigned i = 0; i < nparams; ++i) { 6125 QualType AT = FTP->getArgType(i); 6126 6127 bool mismatch = true; 6128 6129 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 6130 mismatch = false; 6131 else if (Expected[i] == CharPP) { 6132 // As an extension, the following forms are okay: 6133 // char const ** 6134 // char const * const * 6135 // char * const * 6136 6137 QualifierCollector qs; 6138 const PointerType* PT; 6139 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 6140 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 6141 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 6142 qs.removeConst(); 6143 mismatch = !qs.empty(); 6144 } 6145 } 6146 6147 if (mismatch) { 6148 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 6149 // TODO: suggest replacing given type with expected type 6150 FD->setInvalidDecl(true); 6151 } 6152 } 6153 6154 if (nparams == 1 && !FD->isInvalidDecl()) { 6155 Diag(FD->getLocation(), diag::warn_main_one_arg); 6156 } 6157 6158 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 6159 Diag(FD->getLocation(), diag::err_main_template_decl); 6160 FD->setInvalidDecl(); 6161 } 6162 } 6163 6164 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 6165 // FIXME: Need strict checking. In C89, we need to check for 6166 // any assignment, increment, decrement, function-calls, or 6167 // commas outside of a sizeof. In C99, it's the same list, 6168 // except that the aforementioned are allowed in unevaluated 6169 // expressions. Everything else falls under the 6170 // "may accept other forms of constant expressions" exception. 6171 // (We never end up here for C++, so the constant expression 6172 // rules there don't matter.) 6173 if (Init->isConstantInitializer(Context, false)) 6174 return false; 6175 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 6176 << Init->getSourceRange(); 6177 return true; 6178 } 6179 6180 namespace { 6181 // Visits an initialization expression to see if OrigDecl is evaluated in 6182 // its own initialization and throws a warning if it does. 6183 class SelfReferenceChecker 6184 : public EvaluatedExprVisitor<SelfReferenceChecker> { 6185 Sema &S; 6186 Decl *OrigDecl; 6187 bool isRecordType; 6188 bool isPODType; 6189 bool isReferenceType; 6190 6191 public: 6192 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 6193 6194 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 6195 S(S), OrigDecl(OrigDecl) { 6196 isPODType = false; 6197 isRecordType = false; 6198 isReferenceType = false; 6199 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 6200 isPODType = VD->getType().isPODType(S.Context); 6201 isRecordType = VD->getType()->isRecordType(); 6202 isReferenceType = VD->getType()->isReferenceType(); 6203 } 6204 } 6205 6206 // Sometimes, the expression passed in lacks the casts that are used 6207 // to determine which DeclRefExpr's to check. Assume that the casts 6208 // are present and continue visiting the expression. 6209 void HandleExpr(Expr *E) { 6210 // Skip checking T a = a where T is not a record or reference type. 6211 // Doing so is a way to silence uninitialized warnings. 6212 if (isRecordType || isReferenceType) 6213 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 6214 HandleDeclRefExpr(DRE); 6215 6216 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6217 HandleValue(CO->getTrueExpr()); 6218 HandleValue(CO->getFalseExpr()); 6219 } 6220 6221 Visit(E); 6222 } 6223 6224 // For most expressions, the cast is directly above the DeclRefExpr. 6225 // For conditional operators, the cast can be outside the conditional 6226 // operator if both expressions are DeclRefExpr's. 6227 void HandleValue(Expr *E) { 6228 E = E->IgnoreParenImpCasts(); 6229 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 6230 HandleDeclRefExpr(DRE); 6231 return; 6232 } 6233 6234 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6235 HandleValue(CO->getTrueExpr()); 6236 HandleValue(CO->getFalseExpr()); 6237 } 6238 } 6239 6240 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 6241 if ((!isRecordType && E->getCastKind() == CK_LValueToRValue) || 6242 (isRecordType && E->getCastKind() == CK_NoOp)) 6243 HandleValue(E->getSubExpr()); 6244 6245 Inherited::VisitImplicitCastExpr(E); 6246 } 6247 6248 void VisitMemberExpr(MemberExpr *E) { 6249 // Don't warn on arrays since they can be treated as pointers. 6250 if (E->getType()->canDecayToPointerType()) return; 6251 6252 ValueDecl *VD = E->getMemberDecl(); 6253 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD); 6254 if (isa<FieldDecl>(VD) || (MD && !MD->isStatic())) 6255 if (DeclRefExpr *DRE 6256 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) { 6257 HandleDeclRefExpr(DRE); 6258 return; 6259 } 6260 6261 Inherited::VisitMemberExpr(E); 6262 } 6263 6264 void VisitUnaryOperator(UnaryOperator *E) { 6265 // For POD record types, addresses of its own members are well-defined. 6266 if (E->getOpcode() == UO_AddrOf && isRecordType && isPODType && 6267 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) return; 6268 Inherited::VisitUnaryOperator(E); 6269 } 6270 6271 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 6272 6273 void HandleDeclRefExpr(DeclRefExpr *DRE) { 6274 Decl* ReferenceDecl = DRE->getDecl(); 6275 if (OrigDecl != ReferenceDecl) return; 6276 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName, 6277 Sema::NotForRedeclaration); 6278 unsigned diag = isReferenceType 6279 ? diag::warn_uninit_self_reference_in_reference_init 6280 : diag::warn_uninit_self_reference_in_init; 6281 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 6282 S.PDiag(diag) 6283 << Result.getLookupName() 6284 << OrigDecl->getLocation() 6285 << DRE->getSourceRange()); 6286 } 6287 }; 6288 } 6289 6290 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 6291 void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) { 6292 SelfReferenceChecker(*this, OrigDecl).HandleExpr(E); 6293 } 6294 6295 /// AddInitializerToDecl - Adds the initializer Init to the 6296 /// declaration dcl. If DirectInit is true, this is C++ direct 6297 /// initialization rather than copy initialization. 6298 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 6299 bool DirectInit, bool TypeMayContainAuto) { 6300 // If there is no declaration, there was an error parsing it. Just ignore 6301 // the initializer. 6302 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 6303 return; 6304 6305 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 6306 // With declarators parsed the way they are, the parser cannot 6307 // distinguish between a normal initializer and a pure-specifier. 6308 // Thus this grotesque test. 6309 IntegerLiteral *IL; 6310 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 6311 Context.getCanonicalType(IL->getType()) == Context.IntTy) 6312 CheckPureMethod(Method, Init->getSourceRange()); 6313 else { 6314 Diag(Method->getLocation(), diag::err_member_function_initialization) 6315 << Method->getDeclName() << Init->getSourceRange(); 6316 Method->setInvalidDecl(); 6317 } 6318 return; 6319 } 6320 6321 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 6322 if (!VDecl) { 6323 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 6324 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 6325 RealDecl->setInvalidDecl(); 6326 return; 6327 } 6328 6329 // Check for self-references within variable initializers. 6330 // Variables declared within a function/method body (except for references) 6331 // are handled by a dataflow analysis. 6332 // Record types initialized by initializer list are handled here. 6333 // Initialization by constructors are handled in TryConstructorInitialization. 6334 if ((!VDecl->hasLocalStorage() || VDecl->getType()->isReferenceType()) && 6335 (isa<InitListExpr>(Init) || !VDecl->getType()->isRecordType())) 6336 CheckSelfReference(RealDecl, Init); 6337 6338 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 6339 6340 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 6341 AutoType *Auto = 0; 6342 if (TypeMayContainAuto && 6343 (Auto = VDecl->getType()->getContainedAutoType()) && 6344 !Auto->isDeduced()) { 6345 Expr *DeduceInit = Init; 6346 // Initializer could be a C++ direct-initializer. Deduction only works if it 6347 // contains exactly one expression. 6348 if (CXXDirectInit) { 6349 if (CXXDirectInit->getNumExprs() == 0) { 6350 // It isn't possible to write this directly, but it is possible to 6351 // end up in this situation with "auto x(some_pack...);" 6352 Diag(CXXDirectInit->getLocStart(), 6353 diag::err_auto_var_init_no_expression) 6354 << VDecl->getDeclName() << VDecl->getType() 6355 << VDecl->getSourceRange(); 6356 RealDecl->setInvalidDecl(); 6357 return; 6358 } else if (CXXDirectInit->getNumExprs() > 1) { 6359 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 6360 diag::err_auto_var_init_multiple_expressions) 6361 << VDecl->getDeclName() << VDecl->getType() 6362 << VDecl->getSourceRange(); 6363 RealDecl->setInvalidDecl(); 6364 return; 6365 } else { 6366 DeduceInit = CXXDirectInit->getExpr(0); 6367 } 6368 } 6369 TypeSourceInfo *DeducedType = 0; 6370 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 6371 DAR_Failed) 6372 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 6373 if (!DeducedType) { 6374 RealDecl->setInvalidDecl(); 6375 return; 6376 } 6377 VDecl->setTypeSourceInfo(DeducedType); 6378 VDecl->setType(DeducedType->getType()); 6379 VDecl->ClearLinkageCache(); 6380 6381 // In ARC, infer lifetime. 6382 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 6383 VDecl->setInvalidDecl(); 6384 6385 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 6386 // 'id' instead of a specific object type prevents most of our usual checks. 6387 // We only want to warn outside of template instantiations, though: 6388 // inside a template, the 'id' could have come from a parameter. 6389 if (ActiveTemplateInstantiations.empty() && 6390 DeducedType->getType()->isObjCIdType()) { 6391 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc(); 6392 Diag(Loc, diag::warn_auto_var_is_id) 6393 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 6394 } 6395 6396 // If this is a redeclaration, check that the type we just deduced matches 6397 // the previously declared type. 6398 if (VarDecl *Old = VDecl->getPreviousDecl()) 6399 MergeVarDeclTypes(VDecl, Old); 6400 } 6401 6402 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 6403 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 6404 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 6405 VDecl->setInvalidDecl(); 6406 return; 6407 } 6408 6409 if (!VDecl->getType()->isDependentType()) { 6410 // A definition must end up with a complete type, which means it must be 6411 // complete with the restriction that an array type might be completed by 6412 // the initializer; note that later code assumes this restriction. 6413 QualType BaseDeclType = VDecl->getType(); 6414 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 6415 BaseDeclType = Array->getElementType(); 6416 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 6417 diag::err_typecheck_decl_incomplete_type)) { 6418 RealDecl->setInvalidDecl(); 6419 return; 6420 } 6421 6422 // The variable can not have an abstract class type. 6423 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 6424 diag::err_abstract_type_in_decl, 6425 AbstractVariableType)) 6426 VDecl->setInvalidDecl(); 6427 } 6428 6429 const VarDecl *Def; 6430 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 6431 Diag(VDecl->getLocation(), diag::err_redefinition) 6432 << VDecl->getDeclName(); 6433 Diag(Def->getLocation(), diag::note_previous_definition); 6434 VDecl->setInvalidDecl(); 6435 return; 6436 } 6437 6438 const VarDecl* PrevInit = 0; 6439 if (getLangOpts().CPlusPlus) { 6440 // C++ [class.static.data]p4 6441 // If a static data member is of const integral or const 6442 // enumeration type, its declaration in the class definition can 6443 // specify a constant-initializer which shall be an integral 6444 // constant expression (5.19). In that case, the member can appear 6445 // in integral constant expressions. The member shall still be 6446 // defined in a namespace scope if it is used in the program and the 6447 // namespace scope definition shall not contain an initializer. 6448 // 6449 // We already performed a redefinition check above, but for static 6450 // data members we also need to check whether there was an in-class 6451 // declaration with an initializer. 6452 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 6453 Diag(VDecl->getLocation(), diag::err_redefinition) 6454 << VDecl->getDeclName(); 6455 Diag(PrevInit->getLocation(), diag::note_previous_definition); 6456 return; 6457 } 6458 6459 if (VDecl->hasLocalStorage()) 6460 getCurFunction()->setHasBranchProtectedScope(); 6461 6462 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 6463 VDecl->setInvalidDecl(); 6464 return; 6465 } 6466 } 6467 6468 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 6469 // a kernel function cannot be initialized." 6470 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 6471 Diag(VDecl->getLocation(), diag::err_local_cant_init); 6472 VDecl->setInvalidDecl(); 6473 return; 6474 } 6475 6476 // Get the decls type and save a reference for later, since 6477 // CheckInitializerTypes may change it. 6478 QualType DclT = VDecl->getType(), SavT = DclT; 6479 6480 // Top-level message sends default to 'id' when we're in a debugger 6481 // and we are assigning it to a variable of 'id' type. 6482 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType()) 6483 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) { 6484 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 6485 if (Result.isInvalid()) { 6486 VDecl->setInvalidDecl(); 6487 return; 6488 } 6489 Init = Result.take(); 6490 } 6491 6492 // Perform the initialization. 6493 if (!VDecl->isInvalidDecl()) { 6494 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 6495 InitializationKind Kind 6496 = DirectInit ? 6497 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 6498 Init->getLocStart(), 6499 Init->getLocEnd()) 6500 : InitializationKind::CreateDirectList( 6501 VDecl->getLocation()) 6502 : InitializationKind::CreateCopy(VDecl->getLocation(), 6503 Init->getLocStart()); 6504 6505 Expr **Args = &Init; 6506 unsigned NumArgs = 1; 6507 if (CXXDirectInit) { 6508 Args = CXXDirectInit->getExprs(); 6509 NumArgs = CXXDirectInit->getNumExprs(); 6510 } 6511 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs); 6512 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6513 MultiExprArg(*this, Args,NumArgs), 6514 &DclT); 6515 if (Result.isInvalid()) { 6516 VDecl->setInvalidDecl(); 6517 return; 6518 } 6519 6520 Init = Result.takeAs<Expr>(); 6521 } 6522 6523 // If the type changed, it means we had an incomplete type that was 6524 // completed by the initializer. For example: 6525 // int ary[] = { 1, 3, 5 }; 6526 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 6527 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 6528 VDecl->setType(DclT); 6529 6530 // Check any implicit conversions within the expression. 6531 CheckImplicitConversions(Init, VDecl->getLocation()); 6532 6533 if (!VDecl->isInvalidDecl()) 6534 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 6535 6536 Init = MaybeCreateExprWithCleanups(Init); 6537 // Attach the initializer to the decl. 6538 VDecl->setInit(Init); 6539 6540 if (VDecl->isLocalVarDecl()) { 6541 // C99 6.7.8p4: All the expressions in an initializer for an object that has 6542 // static storage duration shall be constant expressions or string literals. 6543 // C++ does not have this restriction. 6544 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && 6545 VDecl->getStorageClass() == SC_Static) 6546 CheckForConstantInitializer(Init, DclT); 6547 } else if (VDecl->isStaticDataMember() && 6548 VDecl->getLexicalDeclContext()->isRecord()) { 6549 // This is an in-class initialization for a static data member, e.g., 6550 // 6551 // struct S { 6552 // static const int value = 17; 6553 // }; 6554 6555 // C++ [class.mem]p4: 6556 // A member-declarator can contain a constant-initializer only 6557 // if it declares a static member (9.4) of const integral or 6558 // const enumeration type, see 9.4.2. 6559 // 6560 // C++11 [class.static.data]p3: 6561 // If a non-volatile const static data member is of integral or 6562 // enumeration type, its declaration in the class definition can 6563 // specify a brace-or-equal-initializer in which every initalizer-clause 6564 // that is an assignment-expression is a constant expression. A static 6565 // data member of literal type can be declared in the class definition 6566 // with the constexpr specifier; if so, its declaration shall specify a 6567 // brace-or-equal-initializer in which every initializer-clause that is 6568 // an assignment-expression is a constant expression. 6569 6570 // Do nothing on dependent types. 6571 if (DclT->isDependentType()) { 6572 6573 // Allow any 'static constexpr' members, whether or not they are of literal 6574 // type. We separately check that every constexpr variable is of literal 6575 // type. 6576 } else if (VDecl->isConstexpr()) { 6577 6578 // Require constness. 6579 } else if (!DclT.isConstQualified()) { 6580 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 6581 << Init->getSourceRange(); 6582 VDecl->setInvalidDecl(); 6583 6584 // We allow integer constant expressions in all cases. 6585 } else if (DclT->isIntegralOrEnumerationType()) { 6586 // Check whether the expression is a constant expression. 6587 SourceLocation Loc; 6588 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified()) 6589 // In C++11, a non-constexpr const static data member with an 6590 // in-class initializer cannot be volatile. 6591 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 6592 else if (Init->isValueDependent()) 6593 ; // Nothing to check. 6594 else if (Init->isIntegerConstantExpr(Context, &Loc)) 6595 ; // Ok, it's an ICE! 6596 else if (Init->isEvaluatable(Context)) { 6597 // If we can constant fold the initializer through heroics, accept it, 6598 // but report this as a use of an extension for -pedantic. 6599 Diag(Loc, diag::ext_in_class_initializer_non_constant) 6600 << Init->getSourceRange(); 6601 } else { 6602 // Otherwise, this is some crazy unknown case. Report the issue at the 6603 // location provided by the isIntegerConstantExpr failed check. 6604 Diag(Loc, diag::err_in_class_initializer_non_constant) 6605 << Init->getSourceRange(); 6606 VDecl->setInvalidDecl(); 6607 } 6608 6609 // We allow foldable floating-point constants as an extension. 6610 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 6611 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 6612 << DclT << Init->getSourceRange(); 6613 if (getLangOpts().CPlusPlus0x) 6614 Diag(VDecl->getLocation(), 6615 diag::note_in_class_initializer_float_type_constexpr) 6616 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 6617 6618 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 6619 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 6620 << Init->getSourceRange(); 6621 VDecl->setInvalidDecl(); 6622 } 6623 6624 // Suggest adding 'constexpr' in C++11 for literal types. 6625 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) { 6626 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 6627 << DclT << Init->getSourceRange() 6628 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 6629 VDecl->setConstexpr(true); 6630 6631 } else { 6632 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 6633 << DclT << Init->getSourceRange(); 6634 VDecl->setInvalidDecl(); 6635 } 6636 } else if (VDecl->isFileVarDecl()) { 6637 if (VDecl->getStorageClassAsWritten() == SC_Extern && 6638 (!getLangOpts().CPlusPlus || 6639 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 6640 Diag(VDecl->getLocation(), diag::warn_extern_init); 6641 6642 // C99 6.7.8p4. All file scoped initializers need to be constant. 6643 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 6644 CheckForConstantInitializer(Init, DclT); 6645 } 6646 6647 // We will represent direct-initialization similarly to copy-initialization: 6648 // int x(1); -as-> int x = 1; 6649 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 6650 // 6651 // Clients that want to distinguish between the two forms, can check for 6652 // direct initializer using VarDecl::getInitStyle(). 6653 // A major benefit is that clients that don't particularly care about which 6654 // exactly form was it (like the CodeGen) can handle both cases without 6655 // special case code. 6656 6657 // C++ 8.5p11: 6658 // The form of initialization (using parentheses or '=') is generally 6659 // insignificant, but does matter when the entity being initialized has a 6660 // class type. 6661 if (CXXDirectInit) { 6662 assert(DirectInit && "Call-style initializer must be direct init."); 6663 VDecl->setInitStyle(VarDecl::CallInit); 6664 } else if (DirectInit) { 6665 // This must be list-initialization. No other way is direct-initialization. 6666 VDecl->setInitStyle(VarDecl::ListInit); 6667 } 6668 6669 CheckCompleteVariableDeclaration(VDecl); 6670 } 6671 6672 /// ActOnInitializerError - Given that there was an error parsing an 6673 /// initializer for the given declaration, try to return to some form 6674 /// of sanity. 6675 void Sema::ActOnInitializerError(Decl *D) { 6676 // Our main concern here is re-establishing invariants like "a 6677 // variable's type is either dependent or complete". 6678 if (!D || D->isInvalidDecl()) return; 6679 6680 VarDecl *VD = dyn_cast<VarDecl>(D); 6681 if (!VD) return; 6682 6683 // Auto types are meaningless if we can't make sense of the initializer. 6684 if (ParsingInitForAutoVars.count(D)) { 6685 D->setInvalidDecl(); 6686 return; 6687 } 6688 6689 QualType Ty = VD->getType(); 6690 if (Ty->isDependentType()) return; 6691 6692 // Require a complete type. 6693 if (RequireCompleteType(VD->getLocation(), 6694 Context.getBaseElementType(Ty), 6695 diag::err_typecheck_decl_incomplete_type)) { 6696 VD->setInvalidDecl(); 6697 return; 6698 } 6699 6700 // Require an abstract type. 6701 if (RequireNonAbstractType(VD->getLocation(), Ty, 6702 diag::err_abstract_type_in_decl, 6703 AbstractVariableType)) { 6704 VD->setInvalidDecl(); 6705 return; 6706 } 6707 6708 // Don't bother complaining about constructors or destructors, 6709 // though. 6710 } 6711 6712 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 6713 bool TypeMayContainAuto) { 6714 // If there is no declaration, there was an error parsing it. Just ignore it. 6715 if (RealDecl == 0) 6716 return; 6717 6718 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 6719 QualType Type = Var->getType(); 6720 6721 // C++11 [dcl.spec.auto]p3 6722 if (TypeMayContainAuto && Type->getContainedAutoType()) { 6723 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 6724 << Var->getDeclName() << Type; 6725 Var->setInvalidDecl(); 6726 return; 6727 } 6728 6729 // C++11 [class.static.data]p3: A static data member can be declared with 6730 // the constexpr specifier; if so, its declaration shall specify 6731 // a brace-or-equal-initializer. 6732 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 6733 // the definition of a variable [...] or the declaration of a static data 6734 // member. 6735 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 6736 if (Var->isStaticDataMember()) 6737 Diag(Var->getLocation(), 6738 diag::err_constexpr_static_mem_var_requires_init) 6739 << Var->getDeclName(); 6740 else 6741 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 6742 Var->setInvalidDecl(); 6743 return; 6744 } 6745 6746 switch (Var->isThisDeclarationADefinition()) { 6747 case VarDecl::Definition: 6748 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 6749 break; 6750 6751 // We have an out-of-line definition of a static data member 6752 // that has an in-class initializer, so we type-check this like 6753 // a declaration. 6754 // 6755 // Fall through 6756 6757 case VarDecl::DeclarationOnly: 6758 // It's only a declaration. 6759 6760 // Block scope. C99 6.7p7: If an identifier for an object is 6761 // declared with no linkage (C99 6.2.2p6), the type for the 6762 // object shall be complete. 6763 if (!Type->isDependentType() && Var->isLocalVarDecl() && 6764 !Var->getLinkage() && !Var->isInvalidDecl() && 6765 RequireCompleteType(Var->getLocation(), Type, 6766 diag::err_typecheck_decl_incomplete_type)) 6767 Var->setInvalidDecl(); 6768 6769 // Make sure that the type is not abstract. 6770 if (!Type->isDependentType() && !Var->isInvalidDecl() && 6771 RequireNonAbstractType(Var->getLocation(), Type, 6772 diag::err_abstract_type_in_decl, 6773 AbstractVariableType)) 6774 Var->setInvalidDecl(); 6775 if (!Type->isDependentType() && !Var->isInvalidDecl() && 6776 Var->getStorageClass() == SC_PrivateExtern) { 6777 Diag(Var->getLocation(), diag::warn_private_extern); 6778 Diag(Var->getLocation(), diag::note_private_extern); 6779 } 6780 6781 return; 6782 6783 case VarDecl::TentativeDefinition: 6784 // File scope. C99 6.9.2p2: A declaration of an identifier for an 6785 // object that has file scope without an initializer, and without a 6786 // storage-class specifier or with the storage-class specifier "static", 6787 // constitutes a tentative definition. Note: A tentative definition with 6788 // external linkage is valid (C99 6.2.2p5). 6789 if (!Var->isInvalidDecl()) { 6790 if (const IncompleteArrayType *ArrayT 6791 = Context.getAsIncompleteArrayType(Type)) { 6792 if (RequireCompleteType(Var->getLocation(), 6793 ArrayT->getElementType(), 6794 diag::err_illegal_decl_array_incomplete_type)) 6795 Var->setInvalidDecl(); 6796 } else if (Var->getStorageClass() == SC_Static) { 6797 // C99 6.9.2p3: If the declaration of an identifier for an object is 6798 // a tentative definition and has internal linkage (C99 6.2.2p3), the 6799 // declared type shall not be an incomplete type. 6800 // NOTE: code such as the following 6801 // static struct s; 6802 // struct s { int a; }; 6803 // is accepted by gcc. Hence here we issue a warning instead of 6804 // an error and we do not invalidate the static declaration. 6805 // NOTE: to avoid multiple warnings, only check the first declaration. 6806 if (Var->getPreviousDecl() == 0) 6807 RequireCompleteType(Var->getLocation(), Type, 6808 diag::ext_typecheck_decl_incomplete_type); 6809 } 6810 } 6811 6812 // Record the tentative definition; we're done. 6813 if (!Var->isInvalidDecl()) 6814 TentativeDefinitions.push_back(Var); 6815 return; 6816 } 6817 6818 // Provide a specific diagnostic for uninitialized variable 6819 // definitions with incomplete array type. 6820 if (Type->isIncompleteArrayType()) { 6821 Diag(Var->getLocation(), 6822 diag::err_typecheck_incomplete_array_needs_initializer); 6823 Var->setInvalidDecl(); 6824 return; 6825 } 6826 6827 // Provide a specific diagnostic for uninitialized variable 6828 // definitions with reference type. 6829 if (Type->isReferenceType()) { 6830 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 6831 << Var->getDeclName() 6832 << SourceRange(Var->getLocation(), Var->getLocation()); 6833 Var->setInvalidDecl(); 6834 return; 6835 } 6836 6837 // Do not attempt to type-check the default initializer for a 6838 // variable with dependent type. 6839 if (Type->isDependentType()) 6840 return; 6841 6842 if (Var->isInvalidDecl()) 6843 return; 6844 6845 if (RequireCompleteType(Var->getLocation(), 6846 Context.getBaseElementType(Type), 6847 diag::err_typecheck_decl_incomplete_type)) { 6848 Var->setInvalidDecl(); 6849 return; 6850 } 6851 6852 // The variable can not have an abstract class type. 6853 if (RequireNonAbstractType(Var->getLocation(), Type, 6854 diag::err_abstract_type_in_decl, 6855 AbstractVariableType)) { 6856 Var->setInvalidDecl(); 6857 return; 6858 } 6859 6860 // Check for jumps past the implicit initializer. C++0x 6861 // clarifies that this applies to a "variable with automatic 6862 // storage duration", not a "local variable". 6863 // C++11 [stmt.dcl]p3 6864 // A program that jumps from a point where a variable with automatic 6865 // storage duration is not in scope to a point where it is in scope is 6866 // ill-formed unless the variable has scalar type, class type with a 6867 // trivial default constructor and a trivial destructor, a cv-qualified 6868 // version of one of these types, or an array of one of the preceding 6869 // types and is declared without an initializer. 6870 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 6871 if (const RecordType *Record 6872 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 6873 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 6874 // Mark the function for further checking even if the looser rules of 6875 // C++11 do not require such checks, so that we can diagnose 6876 // incompatibilities with C++98. 6877 if (!CXXRecord->isPOD()) 6878 getCurFunction()->setHasBranchProtectedScope(); 6879 } 6880 } 6881 6882 // C++03 [dcl.init]p9: 6883 // If no initializer is specified for an object, and the 6884 // object is of (possibly cv-qualified) non-POD class type (or 6885 // array thereof), the object shall be default-initialized; if 6886 // the object is of const-qualified type, the underlying class 6887 // type shall have a user-declared default 6888 // constructor. Otherwise, if no initializer is specified for 6889 // a non- static object, the object and its subobjects, if 6890 // any, have an indeterminate initial value); if the object 6891 // or any of its subobjects are of const-qualified type, the 6892 // program is ill-formed. 6893 // C++0x [dcl.init]p11: 6894 // If no initializer is specified for an object, the object is 6895 // default-initialized; [...]. 6896 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 6897 InitializationKind Kind 6898 = InitializationKind::CreateDefault(Var->getLocation()); 6899 6900 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 6901 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 6902 MultiExprArg(*this, 0, 0)); 6903 if (Init.isInvalid()) 6904 Var->setInvalidDecl(); 6905 else if (Init.get()) { 6906 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 6907 // This is important for template substitution. 6908 Var->setInitStyle(VarDecl::CallInit); 6909 } 6910 6911 CheckCompleteVariableDeclaration(Var); 6912 } 6913 } 6914 6915 void Sema::ActOnCXXForRangeDecl(Decl *D) { 6916 VarDecl *VD = dyn_cast<VarDecl>(D); 6917 if (!VD) { 6918 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 6919 D->setInvalidDecl(); 6920 return; 6921 } 6922 6923 VD->setCXXForRangeDecl(true); 6924 6925 // for-range-declaration cannot be given a storage class specifier. 6926 int Error = -1; 6927 switch (VD->getStorageClassAsWritten()) { 6928 case SC_None: 6929 break; 6930 case SC_Extern: 6931 Error = 0; 6932 break; 6933 case SC_Static: 6934 Error = 1; 6935 break; 6936 case SC_PrivateExtern: 6937 Error = 2; 6938 break; 6939 case SC_Auto: 6940 Error = 3; 6941 break; 6942 case SC_Register: 6943 Error = 4; 6944 break; 6945 case SC_OpenCLWorkGroupLocal: 6946 llvm_unreachable("Unexpected storage class"); 6947 } 6948 if (VD->isConstexpr()) 6949 Error = 5; 6950 if (Error != -1) { 6951 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 6952 << VD->getDeclName() << Error; 6953 D->setInvalidDecl(); 6954 } 6955 } 6956 6957 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 6958 if (var->isInvalidDecl()) return; 6959 6960 // In ARC, don't allow jumps past the implicit initialization of a 6961 // local retaining variable. 6962 if (getLangOpts().ObjCAutoRefCount && 6963 var->hasLocalStorage()) { 6964 switch (var->getType().getObjCLifetime()) { 6965 case Qualifiers::OCL_None: 6966 case Qualifiers::OCL_ExplicitNone: 6967 case Qualifiers::OCL_Autoreleasing: 6968 break; 6969 6970 case Qualifiers::OCL_Weak: 6971 case Qualifiers::OCL_Strong: 6972 getCurFunction()->setHasBranchProtectedScope(); 6973 break; 6974 } 6975 } 6976 6977 // All the following checks are C++ only. 6978 if (!getLangOpts().CPlusPlus) return; 6979 6980 QualType baseType = Context.getBaseElementType(var->getType()); 6981 if (baseType->isDependentType()) return; 6982 6983 // __block variables might require us to capture a copy-initializer. 6984 if (var->hasAttr<BlocksAttr>()) { 6985 // It's currently invalid to ever have a __block variable with an 6986 // array type; should we diagnose that here? 6987 6988 // Regardless, we don't want to ignore array nesting when 6989 // constructing this copy. 6990 QualType type = var->getType(); 6991 6992 if (type->isStructureOrClassType()) { 6993 SourceLocation poi = var->getLocation(); 6994 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 6995 ExprResult result = 6996 PerformCopyInitialization( 6997 InitializedEntity::InitializeBlock(poi, type, false), 6998 poi, Owned(varRef)); 6999 if (!result.isInvalid()) { 7000 result = MaybeCreateExprWithCleanups(result); 7001 Expr *init = result.takeAs<Expr>(); 7002 Context.setBlockVarCopyInits(var, init); 7003 } 7004 } 7005 } 7006 7007 Expr *Init = var->getInit(); 7008 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 7009 7010 if (!var->getDeclContext()->isDependentContext() && Init) { 7011 if (IsGlobal && !var->isConstexpr() && 7012 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 7013 var->getLocation()) 7014 != DiagnosticsEngine::Ignored && 7015 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 7016 Diag(var->getLocation(), diag::warn_global_constructor) 7017 << Init->getSourceRange(); 7018 7019 if (var->isConstexpr()) { 7020 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 7021 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 7022 SourceLocation DiagLoc = var->getLocation(); 7023 // If the note doesn't add any useful information other than a source 7024 // location, fold it into the primary diagnostic. 7025 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 7026 diag::note_invalid_subexpr_in_const_expr) { 7027 DiagLoc = Notes[0].first; 7028 Notes.clear(); 7029 } 7030 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 7031 << var << Init->getSourceRange(); 7032 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 7033 Diag(Notes[I].first, Notes[I].second); 7034 } 7035 } else if (var->isUsableInConstantExpressions(Context)) { 7036 // Check whether the initializer of a const variable of integral or 7037 // enumeration type is an ICE now, since we can't tell whether it was 7038 // initialized by a constant expression if we check later. 7039 var->checkInitIsICE(); 7040 } 7041 } 7042 7043 // Require the destructor. 7044 if (const RecordType *recordType = baseType->getAs<RecordType>()) 7045 FinalizeVarWithDestructor(var, recordType); 7046 } 7047 7048 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 7049 /// any semantic actions necessary after any initializer has been attached. 7050 void 7051 Sema::FinalizeDeclaration(Decl *ThisDecl) { 7052 // Note that we are no longer parsing the initializer for this declaration. 7053 ParsingInitForAutoVars.erase(ThisDecl); 7054 7055 // Now we have parsed the initializer and can update the table of magic 7056 // tag values. 7057 if (ThisDecl && ThisDecl->hasAttr<TypeTagForDatatypeAttr>()) { 7058 const VarDecl *VD = dyn_cast<VarDecl>(ThisDecl); 7059 if (VD && VD->getType()->isIntegralOrEnumerationType()) { 7060 for (specific_attr_iterator<TypeTagForDatatypeAttr> 7061 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 7062 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 7063 I != E; ++I) { 7064 const Expr *MagicValueExpr = VD->getInit(); 7065 if (!MagicValueExpr) { 7066 continue; 7067 } 7068 llvm::APSInt MagicValueInt; 7069 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 7070 Diag(I->getRange().getBegin(), 7071 diag::err_type_tag_for_datatype_not_ice) 7072 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 7073 continue; 7074 } 7075 if (MagicValueInt.getActiveBits() > 64) { 7076 Diag(I->getRange().getBegin(), 7077 diag::err_type_tag_for_datatype_too_large) 7078 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 7079 continue; 7080 } 7081 uint64_t MagicValue = MagicValueInt.getZExtValue(); 7082 RegisterTypeTagForDatatype(I->getArgumentKind(), 7083 MagicValue, 7084 I->getMatchingCType(), 7085 I->getLayoutCompatible(), 7086 I->getMustBeNull()); 7087 } 7088 } 7089 } 7090 } 7091 7092 Sema::DeclGroupPtrTy 7093 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 7094 Decl **Group, unsigned NumDecls) { 7095 SmallVector<Decl*, 8> Decls; 7096 7097 if (DS.isTypeSpecOwned()) 7098 Decls.push_back(DS.getRepAsDecl()); 7099 7100 for (unsigned i = 0; i != NumDecls; ++i) 7101 if (Decl *D = Group[i]) 7102 Decls.push_back(D); 7103 7104 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 7105 DS.getTypeSpecType() == DeclSpec::TST_auto); 7106 } 7107 7108 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 7109 /// group, performing any necessary semantic checking. 7110 Sema::DeclGroupPtrTy 7111 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 7112 bool TypeMayContainAuto) { 7113 // C++0x [dcl.spec.auto]p7: 7114 // If the type deduced for the template parameter U is not the same in each 7115 // deduction, the program is ill-formed. 7116 // FIXME: When initializer-list support is added, a distinction is needed 7117 // between the deduced type U and the deduced type which 'auto' stands for. 7118 // auto a = 0, b = { 1, 2, 3 }; 7119 // is legal because the deduced type U is 'int' in both cases. 7120 if (TypeMayContainAuto && NumDecls > 1) { 7121 QualType Deduced; 7122 CanQualType DeducedCanon; 7123 VarDecl *DeducedDecl = 0; 7124 for (unsigned i = 0; i != NumDecls; ++i) { 7125 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 7126 AutoType *AT = D->getType()->getContainedAutoType(); 7127 // Don't reissue diagnostics when instantiating a template. 7128 if (AT && D->isInvalidDecl()) 7129 break; 7130 if (AT && AT->isDeduced()) { 7131 QualType U = AT->getDeducedType(); 7132 CanQualType UCanon = Context.getCanonicalType(U); 7133 if (Deduced.isNull()) { 7134 Deduced = U; 7135 DeducedCanon = UCanon; 7136 DeducedDecl = D; 7137 } else if (DeducedCanon != UCanon) { 7138 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 7139 diag::err_auto_different_deductions) 7140 << Deduced << DeducedDecl->getDeclName() 7141 << U << D->getDeclName() 7142 << DeducedDecl->getInit()->getSourceRange() 7143 << D->getInit()->getSourceRange(); 7144 D->setInvalidDecl(); 7145 break; 7146 } 7147 } 7148 } 7149 } 7150 } 7151 7152 ActOnDocumentableDecls(Group, NumDecls); 7153 7154 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 7155 } 7156 7157 void Sema::ActOnDocumentableDecl(Decl *D) { 7158 ActOnDocumentableDecls(&D, 1); 7159 } 7160 7161 void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) { 7162 // Don't parse the comment if Doxygen diagnostics are ignored. 7163 if (NumDecls == 0 || !Group[0]) 7164 return; 7165 7166 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 7167 Group[0]->getLocation()) 7168 == DiagnosticsEngine::Ignored) 7169 return; 7170 7171 if (NumDecls >= 2) { 7172 // This is a decl group. Normally it will contain only declarations 7173 // procuded from declarator list. But in case we have any definitions or 7174 // additional declaration references: 7175 // 'typedef struct S {} S;' 7176 // 'typedef struct S *S;' 7177 // 'struct S *pS;' 7178 // FinalizeDeclaratorGroup adds these as separate declarations. 7179 Decl *MaybeTagDecl = Group[0]; 7180 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 7181 Group++; 7182 NumDecls--; 7183 } 7184 } 7185 7186 // See if there are any new comments that are not attached to a decl. 7187 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 7188 if (!Comments.empty() && 7189 !Comments.back()->isAttached()) { 7190 // There is at least one comment that not attached to a decl. 7191 // Maybe it should be attached to one of these decls? 7192 // 7193 // Note that this way we pick up not only comments that precede the 7194 // declaration, but also comments that *follow* the declaration -- thanks to 7195 // the lookahead in the lexer: we've consumed the semicolon and looked 7196 // ahead through comments. 7197 for (unsigned i = 0; i != NumDecls; ++i) 7198 Context.getCommentForDecl(Group[i]); 7199 } 7200 } 7201 7202 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 7203 /// to introduce parameters into function prototype scope. 7204 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 7205 const DeclSpec &DS = D.getDeclSpec(); 7206 7207 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 7208 // C++03 [dcl.stc]p2 also permits 'auto'. 7209 VarDecl::StorageClass StorageClass = SC_None; 7210 VarDecl::StorageClass StorageClassAsWritten = SC_None; 7211 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 7212 StorageClass = SC_Register; 7213 StorageClassAsWritten = SC_Register; 7214 } else if (getLangOpts().CPlusPlus && 7215 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 7216 StorageClass = SC_Auto; 7217 StorageClassAsWritten = SC_Auto; 7218 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 7219 Diag(DS.getStorageClassSpecLoc(), 7220 diag::err_invalid_storage_class_in_func_decl); 7221 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7222 } 7223 7224 if (D.getDeclSpec().isThreadSpecified()) 7225 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 7226 if (D.getDeclSpec().isConstexprSpecified()) 7227 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 7228 << 0; 7229 7230 DiagnoseFunctionSpecifiers(D); 7231 7232 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7233 QualType parmDeclType = TInfo->getType(); 7234 7235 if (getLangOpts().CPlusPlus) { 7236 // Check that there are no default arguments inside the type of this 7237 // parameter. 7238 CheckExtraCXXDefaultArguments(D); 7239 7240 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 7241 if (D.getCXXScopeSpec().isSet()) { 7242 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 7243 << D.getCXXScopeSpec().getRange(); 7244 D.getCXXScopeSpec().clear(); 7245 } 7246 } 7247 7248 // Ensure we have a valid name 7249 IdentifierInfo *II = 0; 7250 if (D.hasName()) { 7251 II = D.getIdentifier(); 7252 if (!II) { 7253 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 7254 << GetNameForDeclarator(D).getName().getAsString(); 7255 D.setInvalidType(true); 7256 } 7257 } 7258 7259 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 7260 if (II) { 7261 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 7262 ForRedeclaration); 7263 LookupName(R, S); 7264 if (R.isSingleResult()) { 7265 NamedDecl *PrevDecl = R.getFoundDecl(); 7266 if (PrevDecl->isTemplateParameter()) { 7267 // Maybe we will complain about the shadowed template parameter. 7268 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 7269 // Just pretend that we didn't see the previous declaration. 7270 PrevDecl = 0; 7271 } else if (S->isDeclScope(PrevDecl)) { 7272 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 7273 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 7274 7275 // Recover by removing the name 7276 II = 0; 7277 D.SetIdentifier(0, D.getIdentifierLoc()); 7278 D.setInvalidType(true); 7279 } 7280 } 7281 } 7282 7283 // Temporarily put parameter variables in the translation unit, not 7284 // the enclosing context. This prevents them from accidentally 7285 // looking like class members in C++. 7286 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 7287 D.getLocStart(), 7288 D.getIdentifierLoc(), II, 7289 parmDeclType, TInfo, 7290 StorageClass, StorageClassAsWritten); 7291 7292 if (D.isInvalidType()) 7293 New->setInvalidDecl(); 7294 7295 assert(S->isFunctionPrototypeScope()); 7296 assert(S->getFunctionPrototypeDepth() >= 1); 7297 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 7298 S->getNextFunctionPrototypeIndex()); 7299 7300 // Add the parameter declaration into this scope. 7301 S->AddDecl(New); 7302 if (II) 7303 IdResolver.AddDecl(New); 7304 7305 ProcessDeclAttributes(S, New, D); 7306 7307 if (D.getDeclSpec().isModulePrivateSpecified()) 7308 Diag(New->getLocation(), diag::err_module_private_local) 7309 << 1 << New->getDeclName() 7310 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7311 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7312 7313 if (New->hasAttr<BlocksAttr>()) { 7314 Diag(New->getLocation(), diag::err_block_on_nonlocal); 7315 } 7316 return New; 7317 } 7318 7319 /// \brief Synthesizes a variable for a parameter arising from a 7320 /// typedef. 7321 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 7322 SourceLocation Loc, 7323 QualType T) { 7324 /* FIXME: setting StartLoc == Loc. 7325 Would it be worth to modify callers so as to provide proper source 7326 location for the unnamed parameters, embedding the parameter's type? */ 7327 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 7328 T, Context.getTrivialTypeSourceInfo(T, Loc), 7329 SC_None, SC_None, 0); 7330 Param->setImplicit(); 7331 return Param; 7332 } 7333 7334 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 7335 ParmVarDecl * const *ParamEnd) { 7336 // Don't diagnose unused-parameter errors in template instantiations; we 7337 // will already have done so in the template itself. 7338 if (!ActiveTemplateInstantiations.empty()) 7339 return; 7340 7341 for (; Param != ParamEnd; ++Param) { 7342 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 7343 !(*Param)->hasAttr<UnusedAttr>()) { 7344 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 7345 << (*Param)->getDeclName(); 7346 } 7347 } 7348 } 7349 7350 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 7351 ParmVarDecl * const *ParamEnd, 7352 QualType ReturnTy, 7353 NamedDecl *D) { 7354 if (LangOpts.NumLargeByValueCopy == 0) // No check. 7355 return; 7356 7357 // Warn if the return value is pass-by-value and larger than the specified 7358 // threshold. 7359 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 7360 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 7361 if (Size > LangOpts.NumLargeByValueCopy) 7362 Diag(D->getLocation(), diag::warn_return_value_size) 7363 << D->getDeclName() << Size; 7364 } 7365 7366 // Warn if any parameter is pass-by-value and larger than the specified 7367 // threshold. 7368 for (; Param != ParamEnd; ++Param) { 7369 QualType T = (*Param)->getType(); 7370 if (T->isDependentType() || !T.isPODType(Context)) 7371 continue; 7372 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 7373 if (Size > LangOpts.NumLargeByValueCopy) 7374 Diag((*Param)->getLocation(), diag::warn_parameter_size) 7375 << (*Param)->getDeclName() << Size; 7376 } 7377 } 7378 7379 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 7380 SourceLocation NameLoc, IdentifierInfo *Name, 7381 QualType T, TypeSourceInfo *TSInfo, 7382 VarDecl::StorageClass StorageClass, 7383 VarDecl::StorageClass StorageClassAsWritten) { 7384 // In ARC, infer a lifetime qualifier for appropriate parameter types. 7385 if (getLangOpts().ObjCAutoRefCount && 7386 T.getObjCLifetime() == Qualifiers::OCL_None && 7387 T->isObjCLifetimeType()) { 7388 7389 Qualifiers::ObjCLifetime lifetime; 7390 7391 // Special cases for arrays: 7392 // - if it's const, use __unsafe_unretained 7393 // - otherwise, it's an error 7394 if (T->isArrayType()) { 7395 if (!T.isConstQualified()) { 7396 DelayedDiagnostics.add( 7397 sema::DelayedDiagnostic::makeForbiddenType( 7398 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 7399 } 7400 lifetime = Qualifiers::OCL_ExplicitNone; 7401 } else { 7402 lifetime = T->getObjCARCImplicitLifetime(); 7403 } 7404 T = Context.getLifetimeQualifiedType(T, lifetime); 7405 } 7406 7407 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 7408 Context.getAdjustedParameterType(T), 7409 TSInfo, 7410 StorageClass, StorageClassAsWritten, 7411 0); 7412 7413 // Parameters can not be abstract class types. 7414 // For record types, this is done by the AbstractClassUsageDiagnoser once 7415 // the class has been completely parsed. 7416 if (!CurContext->isRecord() && 7417 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 7418 AbstractParamType)) 7419 New->setInvalidDecl(); 7420 7421 // Parameter declarators cannot be interface types. All ObjC objects are 7422 // passed by reference. 7423 if (T->isObjCObjectType()) { 7424 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 7425 Diag(NameLoc, 7426 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 7427 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 7428 T = Context.getObjCObjectPointerType(T); 7429 New->setType(T); 7430 } 7431 7432 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 7433 // duration shall not be qualified by an address-space qualifier." 7434 // Since all parameters have automatic store duration, they can not have 7435 // an address space. 7436 if (T.getAddressSpace() != 0) { 7437 Diag(NameLoc, diag::err_arg_with_address_space); 7438 New->setInvalidDecl(); 7439 } 7440 7441 return New; 7442 } 7443 7444 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 7445 SourceLocation LocAfterDecls) { 7446 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7447 7448 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 7449 // for a K&R function. 7450 if (!FTI.hasPrototype) { 7451 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 7452 --i; 7453 if (FTI.ArgInfo[i].Param == 0) { 7454 SmallString<256> Code; 7455 llvm::raw_svector_ostream(Code) << " int " 7456 << FTI.ArgInfo[i].Ident->getName() 7457 << ";\n"; 7458 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 7459 << FTI.ArgInfo[i].Ident 7460 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 7461 7462 // Implicitly declare the argument as type 'int' for lack of a better 7463 // type. 7464 AttributeFactory attrs; 7465 DeclSpec DS(attrs); 7466 const char* PrevSpec; // unused 7467 unsigned DiagID; // unused 7468 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 7469 PrevSpec, DiagID); 7470 Declarator ParamD(DS, Declarator::KNRTypeListContext); 7471 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 7472 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 7473 } 7474 } 7475 } 7476 } 7477 7478 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 7479 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 7480 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 7481 Scope *ParentScope = FnBodyScope->getParent(); 7482 7483 D.setFunctionDefinitionKind(FDK_Definition); 7484 Decl *DP = HandleDeclarator(ParentScope, D, 7485 MultiTemplateParamsArg(*this)); 7486 return ActOnStartOfFunctionDef(FnBodyScope, DP); 7487 } 7488 7489 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 7490 // Don't warn about invalid declarations. 7491 if (FD->isInvalidDecl()) 7492 return false; 7493 7494 // Or declarations that aren't global. 7495 if (!FD->isGlobal()) 7496 return false; 7497 7498 // Don't warn about C++ member functions. 7499 if (isa<CXXMethodDecl>(FD)) 7500 return false; 7501 7502 // Don't warn about 'main'. 7503 if (FD->isMain()) 7504 return false; 7505 7506 // Don't warn about inline functions. 7507 if (FD->isInlined()) 7508 return false; 7509 7510 // Don't warn about function templates. 7511 if (FD->getDescribedFunctionTemplate()) 7512 return false; 7513 7514 // Don't warn about function template specializations. 7515 if (FD->isFunctionTemplateSpecialization()) 7516 return false; 7517 7518 // Don't warn for OpenCL kernels. 7519 if (FD->hasAttr<OpenCLKernelAttr>()) 7520 return false; 7521 7522 bool MissingPrototype = true; 7523 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 7524 Prev; Prev = Prev->getPreviousDecl()) { 7525 // Ignore any declarations that occur in function or method 7526 // scope, because they aren't visible from the header. 7527 if (Prev->getDeclContext()->isFunctionOrMethod()) 7528 continue; 7529 7530 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 7531 break; 7532 } 7533 7534 return MissingPrototype; 7535 } 7536 7537 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 7538 // Don't complain if we're in GNU89 mode and the previous definition 7539 // was an extern inline function. 7540 const FunctionDecl *Definition; 7541 if (FD->isDefined(Definition) && 7542 !canRedefineFunction(Definition, getLangOpts())) { 7543 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 7544 Definition->getStorageClass() == SC_Extern) 7545 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 7546 << FD->getDeclName() << getLangOpts().CPlusPlus; 7547 else 7548 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 7549 Diag(Definition->getLocation(), diag::note_previous_definition); 7550 FD->setInvalidDecl(); 7551 } 7552 } 7553 7554 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 7555 // Clear the last template instantiation error context. 7556 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 7557 7558 if (!D) 7559 return D; 7560 FunctionDecl *FD = 0; 7561 7562 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 7563 FD = FunTmpl->getTemplatedDecl(); 7564 else 7565 FD = cast<FunctionDecl>(D); 7566 7567 // Enter a new function scope 7568 PushFunctionScope(); 7569 7570 // See if this is a redefinition. 7571 if (!FD->isLateTemplateParsed()) 7572 CheckForFunctionRedefinition(FD); 7573 7574 // Builtin functions cannot be defined. 7575 if (unsigned BuiltinID = FD->getBuiltinID()) { 7576 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 7577 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 7578 FD->setInvalidDecl(); 7579 } 7580 } 7581 7582 // The return type of a function definition must be complete 7583 // (C99 6.9.1p3, C++ [dcl.fct]p6). 7584 QualType ResultType = FD->getResultType(); 7585 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 7586 !FD->isInvalidDecl() && 7587 RequireCompleteType(FD->getLocation(), ResultType, 7588 diag::err_func_def_incomplete_result)) 7589 FD->setInvalidDecl(); 7590 7591 // GNU warning -Wmissing-prototypes: 7592 // Warn if a global function is defined without a previous 7593 // prototype declaration. This warning is issued even if the 7594 // definition itself provides a prototype. The aim is to detect 7595 // global functions that fail to be declared in header files. 7596 if (ShouldWarnAboutMissingPrototype(FD)) 7597 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 7598 7599 if (FnBodyScope) 7600 PushDeclContext(FnBodyScope, FD); 7601 7602 // Check the validity of our function parameters 7603 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 7604 /*CheckParameterNames=*/true); 7605 7606 // Introduce our parameters into the function scope 7607 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 7608 ParmVarDecl *Param = FD->getParamDecl(p); 7609 Param->setOwningFunction(FD); 7610 7611 // If this has an identifier, add it to the scope stack. 7612 if (Param->getIdentifier() && FnBodyScope) { 7613 CheckShadow(FnBodyScope, Param); 7614 7615 PushOnScopeChains(Param, FnBodyScope); 7616 } 7617 } 7618 7619 // If we had any tags defined in the function prototype, 7620 // introduce them into the function scope. 7621 if (FnBodyScope) { 7622 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(), 7623 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) { 7624 NamedDecl *D = *I; 7625 7626 // Some of these decls (like enums) may have been pinned to the translation unit 7627 // for lack of a real context earlier. If so, remove from the translation unit 7628 // and reattach to the current context. 7629 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 7630 // Is the decl actually in the context? 7631 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 7632 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 7633 if (*DI == D) { 7634 Context.getTranslationUnitDecl()->removeDecl(D); 7635 break; 7636 } 7637 } 7638 // Either way, reassign the lexical decl context to our FunctionDecl. 7639 D->setLexicalDeclContext(CurContext); 7640 } 7641 7642 // If the decl has a non-null name, make accessible in the current scope. 7643 if (!D->getName().empty()) 7644 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 7645 7646 // Similarly, dive into enums and fish their constants out, making them 7647 // accessible in this scope. 7648 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 7649 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 7650 EE = ED->enumerator_end(); EI != EE; ++EI) 7651 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 7652 } 7653 } 7654 } 7655 7656 // Ensure that the function's exception specification is instantiated. 7657 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 7658 ResolveExceptionSpec(D->getLocation(), FPT); 7659 7660 // Checking attributes of current function definition 7661 // dllimport attribute. 7662 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 7663 if (DA && (!FD->getAttr<DLLExportAttr>())) { 7664 // dllimport attribute cannot be directly applied to definition. 7665 // Microsoft accepts dllimport for functions defined within class scope. 7666 if (!DA->isInherited() && 7667 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 7668 Diag(FD->getLocation(), 7669 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 7670 << "dllimport"; 7671 FD->setInvalidDecl(); 7672 return FD; 7673 } 7674 7675 // Visual C++ appears to not think this is an issue, so only issue 7676 // a warning when Microsoft extensions are disabled. 7677 if (!LangOpts.MicrosoftExt) { 7678 // If a symbol previously declared dllimport is later defined, the 7679 // attribute is ignored in subsequent references, and a warning is 7680 // emitted. 7681 Diag(FD->getLocation(), 7682 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 7683 << FD->getName() << "dllimport"; 7684 } 7685 } 7686 // We want to attach documentation to original Decl (which might be 7687 // a function template). 7688 ActOnDocumentableDecl(D); 7689 return FD; 7690 } 7691 7692 /// \brief Given the set of return statements within a function body, 7693 /// compute the variables that are subject to the named return value 7694 /// optimization. 7695 /// 7696 /// Each of the variables that is subject to the named return value 7697 /// optimization will be marked as NRVO variables in the AST, and any 7698 /// return statement that has a marked NRVO variable as its NRVO candidate can 7699 /// use the named return value optimization. 7700 /// 7701 /// This function applies a very simplistic algorithm for NRVO: if every return 7702 /// statement in the function has the same NRVO candidate, that candidate is 7703 /// the NRVO variable. 7704 /// 7705 /// FIXME: Employ a smarter algorithm that accounts for multiple return 7706 /// statements and the lifetimes of the NRVO candidates. We should be able to 7707 /// find a maximal set of NRVO variables. 7708 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 7709 ReturnStmt **Returns = Scope->Returns.data(); 7710 7711 const VarDecl *NRVOCandidate = 0; 7712 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 7713 if (!Returns[I]->getNRVOCandidate()) 7714 return; 7715 7716 if (!NRVOCandidate) 7717 NRVOCandidate = Returns[I]->getNRVOCandidate(); 7718 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 7719 return; 7720 } 7721 7722 if (NRVOCandidate) 7723 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 7724 } 7725 7726 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 7727 return ActOnFinishFunctionBody(D, move(BodyArg), false); 7728 } 7729 7730 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 7731 bool IsInstantiation) { 7732 FunctionDecl *FD = 0; 7733 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 7734 if (FunTmpl) 7735 FD = FunTmpl->getTemplatedDecl(); 7736 else 7737 FD = dyn_cast_or_null<FunctionDecl>(dcl); 7738 7739 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 7740 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 7741 7742 if (FD) { 7743 FD->setBody(Body); 7744 7745 // If the function implicitly returns zero (like 'main') or is naked, 7746 // don't complain about missing return statements. 7747 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 7748 WP.disableCheckFallThrough(); 7749 7750 // MSVC permits the use of pure specifier (=0) on function definition, 7751 // defined at class scope, warn about this non standard construct. 7752 if (getLangOpts().MicrosoftExt && FD->isPure()) 7753 Diag(FD->getLocation(), diag::warn_pure_function_definition); 7754 7755 if (!FD->isInvalidDecl()) { 7756 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 7757 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 7758 FD->getResultType(), FD); 7759 7760 // If this is a constructor, we need a vtable. 7761 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 7762 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 7763 7764 // Try to apply the named return value optimization. We have to check 7765 // if we can do this here because lambdas keep return statements around 7766 // to deduce an implicit return type. 7767 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 7768 !FD->isDependentContext()) 7769 computeNRVO(Body, getCurFunction()); 7770 } 7771 7772 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 7773 "Function parsing confused"); 7774 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 7775 assert(MD == getCurMethodDecl() && "Method parsing confused"); 7776 MD->setBody(Body); 7777 if (!MD->isInvalidDecl()) { 7778 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 7779 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 7780 MD->getResultType(), MD); 7781 7782 if (Body) 7783 computeNRVO(Body, getCurFunction()); 7784 } 7785 if (getCurFunction()->ObjCShouldCallSuperDealloc) { 7786 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc); 7787 getCurFunction()->ObjCShouldCallSuperDealloc = false; 7788 } 7789 if (getCurFunction()->ObjCShouldCallSuperFinalize) { 7790 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize); 7791 getCurFunction()->ObjCShouldCallSuperFinalize = false; 7792 } 7793 } else { 7794 return 0; 7795 } 7796 7797 assert(!getCurFunction()->ObjCShouldCallSuperDealloc && 7798 "This should only be set for ObjC methods, which should have been " 7799 "handled in the block above."); 7800 assert(!getCurFunction()->ObjCShouldCallSuperFinalize && 7801 "This should only be set for ObjC methods, which should have been " 7802 "handled in the block above."); 7803 7804 // Verify and clean out per-function state. 7805 if (Body) { 7806 // C++ constructors that have function-try-blocks can't have return 7807 // statements in the handlers of that block. (C++ [except.handle]p14) 7808 // Verify this. 7809 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 7810 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 7811 7812 // Verify that gotos and switch cases don't jump into scopes illegally. 7813 if (getCurFunction()->NeedsScopeChecking() && 7814 !dcl->isInvalidDecl() && 7815 !hasAnyUnrecoverableErrorsInThisFunction() && 7816 !PP.isCodeCompletionEnabled()) 7817 DiagnoseInvalidJumps(Body); 7818 7819 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 7820 if (!Destructor->getParent()->isDependentType()) 7821 CheckDestructor(Destructor); 7822 7823 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7824 Destructor->getParent()); 7825 } 7826 7827 // If any errors have occurred, clear out any temporaries that may have 7828 // been leftover. This ensures that these temporaries won't be picked up for 7829 // deletion in some later function. 7830 if (PP.getDiagnostics().hasErrorOccurred() || 7831 PP.getDiagnostics().getSuppressAllDiagnostics()) { 7832 DiscardCleanupsInEvaluationContext(); 7833 } else if (!isa<FunctionTemplateDecl>(dcl)) { 7834 // Since the body is valid, issue any analysis-based warnings that are 7835 // enabled. 7836 ActivePolicy = &WP; 7837 } 7838 7839 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 7840 (!CheckConstexprFunctionDecl(FD) || 7841 !CheckConstexprFunctionBody(FD, Body))) 7842 FD->setInvalidDecl(); 7843 7844 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 7845 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 7846 assert(MaybeODRUseExprs.empty() && 7847 "Leftover expressions for odr-use checking"); 7848 } 7849 7850 if (!IsInstantiation) 7851 PopDeclContext(); 7852 7853 PopFunctionScopeInfo(ActivePolicy, dcl); 7854 7855 // If any errors have occurred, clear out any temporaries that may have 7856 // been leftover. This ensures that these temporaries won't be picked up for 7857 // deletion in some later function. 7858 if (getDiagnostics().hasErrorOccurred()) { 7859 DiscardCleanupsInEvaluationContext(); 7860 } 7861 7862 return dcl; 7863 } 7864 7865 7866 /// When we finish delayed parsing of an attribute, we must attach it to the 7867 /// relevant Decl. 7868 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 7869 ParsedAttributes &Attrs) { 7870 // Always attach attributes to the underlying decl. 7871 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7872 D = TD->getTemplatedDecl(); 7873 ProcessDeclAttributeList(S, D, Attrs.getList()); 7874 7875 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 7876 if (Method->isStatic()) 7877 checkThisInStaticMemberFunctionAttributes(Method); 7878 } 7879 7880 7881 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 7882 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 7883 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 7884 IdentifierInfo &II, Scope *S) { 7885 // Before we produce a declaration for an implicitly defined 7886 // function, see whether there was a locally-scoped declaration of 7887 // this name as a function or variable. If so, use that 7888 // (non-visible) declaration, and complain about it. 7889 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 7890 = findLocallyScopedExternalDecl(&II); 7891 if (Pos != LocallyScopedExternalDecls.end()) { 7892 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 7893 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 7894 return Pos->second; 7895 } 7896 7897 // Extension in C99. Legal in C90, but warn about it. 7898 unsigned diag_id; 7899 if (II.getName().startswith("__builtin_")) 7900 diag_id = diag::warn_builtin_unknown; 7901 else if (getLangOpts().C99) 7902 diag_id = diag::ext_implicit_function_decl; 7903 else 7904 diag_id = diag::warn_implicit_function_decl; 7905 Diag(Loc, diag_id) << &II; 7906 7907 // Because typo correction is expensive, only do it if the implicit 7908 // function declaration is going to be treated as an error. 7909 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 7910 TypoCorrection Corrected; 7911 DeclFilterCCC<FunctionDecl> Validator; 7912 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 7913 LookupOrdinaryName, S, 0, Validator))) { 7914 std::string CorrectedStr = Corrected.getAsString(getLangOpts()); 7915 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts()); 7916 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>(); 7917 7918 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr 7919 << FixItHint::CreateReplacement(Loc, CorrectedStr); 7920 7921 if (Func->getLocation().isValid() 7922 && !II.getName().startswith("__builtin_")) 7923 Diag(Func->getLocation(), diag::note_previous_decl) 7924 << CorrectedQuotedStr; 7925 } 7926 } 7927 7928 // Set a Declarator for the implicit definition: int foo(); 7929 const char *Dummy; 7930 AttributeFactory attrFactory; 7931 DeclSpec DS(attrFactory); 7932 unsigned DiagID; 7933 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 7934 (void)Error; // Silence warning. 7935 assert(!Error && "Error setting up implicit decl!"); 7936 Declarator D(DS, Declarator::BlockContext); 7937 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, false, 7938 SourceLocation(), 0, 0, 0, true, 7939 SourceLocation(), SourceLocation(), 7940 SourceLocation(), SourceLocation(), 7941 EST_None, SourceLocation(), 7942 0, 0, 0, 0, Loc, Loc, D), 7943 DS.getAttributes(), 7944 SourceLocation()); 7945 D.SetIdentifier(&II, Loc); 7946 7947 // Insert this function into translation-unit scope. 7948 7949 DeclContext *PrevDC = CurContext; 7950 CurContext = Context.getTranslationUnitDecl(); 7951 7952 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 7953 FD->setImplicit(); 7954 7955 CurContext = PrevDC; 7956 7957 AddKnownFunctionAttributes(FD); 7958 7959 return FD; 7960 } 7961 7962 /// \brief Adds any function attributes that we know a priori based on 7963 /// the declaration of this function. 7964 /// 7965 /// These attributes can apply both to implicitly-declared builtins 7966 /// (like __builtin___printf_chk) or to library-declared functions 7967 /// like NSLog or printf. 7968 /// 7969 /// We need to check for duplicate attributes both here and where user-written 7970 /// attributes are applied to declarations. 7971 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 7972 if (FD->isInvalidDecl()) 7973 return; 7974 7975 // If this is a built-in function, map its builtin attributes to 7976 // actual attributes. 7977 if (unsigned BuiltinID = FD->getBuiltinID()) { 7978 // Handle printf-formatting attributes. 7979 unsigned FormatIdx; 7980 bool HasVAListArg; 7981 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 7982 if (!FD->getAttr<FormatAttr>()) { 7983 const char *fmt = "printf"; 7984 unsigned int NumParams = FD->getNumParams(); 7985 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 7986 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 7987 fmt = "NSString"; 7988 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7989 fmt, FormatIdx+1, 7990 HasVAListArg ? 0 : FormatIdx+2)); 7991 } 7992 } 7993 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 7994 HasVAListArg)) { 7995 if (!FD->getAttr<FormatAttr>()) 7996 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7997 "scanf", FormatIdx+1, 7998 HasVAListArg ? 0 : FormatIdx+2)); 7999 } 8000 8001 // Mark const if we don't care about errno and that is the only 8002 // thing preventing the function from being const. This allows 8003 // IRgen to use LLVM intrinsics for such functions. 8004 if (!getLangOpts().MathErrno && 8005 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 8006 if (!FD->getAttr<ConstAttr>()) 8007 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 8008 } 8009 8010 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 8011 !FD->getAttr<ReturnsTwiceAttr>()) 8012 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 8013 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 8014 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 8015 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 8016 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 8017 } 8018 8019 IdentifierInfo *Name = FD->getIdentifier(); 8020 if (!Name) 8021 return; 8022 if ((!getLangOpts().CPlusPlus && 8023 FD->getDeclContext()->isTranslationUnit()) || 8024 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 8025 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 8026 LinkageSpecDecl::lang_c)) { 8027 // Okay: this could be a libc/libm/Objective-C function we know 8028 // about. 8029 } else 8030 return; 8031 8032 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 8033 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 8034 // target-specific builtins, perhaps? 8035 if (!FD->getAttr<FormatAttr>()) 8036 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8037 "printf", 2, 8038 Name->isStr("vasprintf") ? 0 : 3)); 8039 } 8040 8041 if (Name->isStr("__CFStringMakeConstantString")) { 8042 // We already have a __builtin___CFStringMakeConstantString, 8043 // but builds that use -fno-constant-cfstrings don't go through that. 8044 if (!FD->getAttr<FormatArgAttr>()) 8045 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 8046 } 8047 } 8048 8049 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 8050 TypeSourceInfo *TInfo) { 8051 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 8052 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 8053 8054 if (!TInfo) { 8055 assert(D.isInvalidType() && "no declarator info for valid type"); 8056 TInfo = Context.getTrivialTypeSourceInfo(T); 8057 } 8058 8059 // Scope manipulation handled by caller. 8060 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 8061 D.getLocStart(), 8062 D.getIdentifierLoc(), 8063 D.getIdentifier(), 8064 TInfo); 8065 8066 // Bail out immediately if we have an invalid declaration. 8067 if (D.isInvalidType()) { 8068 NewTD->setInvalidDecl(); 8069 return NewTD; 8070 } 8071 8072 if (D.getDeclSpec().isModulePrivateSpecified()) { 8073 if (CurContext->isFunctionOrMethod()) 8074 Diag(NewTD->getLocation(), diag::err_module_private_local) 8075 << 2 << NewTD->getDeclName() 8076 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 8077 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 8078 else 8079 NewTD->setModulePrivate(); 8080 } 8081 8082 // C++ [dcl.typedef]p8: 8083 // If the typedef declaration defines an unnamed class (or 8084 // enum), the first typedef-name declared by the declaration 8085 // to be that class type (or enum type) is used to denote the 8086 // class type (or enum type) for linkage purposes only. 8087 // We need to check whether the type was declared in the declaration. 8088 switch (D.getDeclSpec().getTypeSpecType()) { 8089 case TST_enum: 8090 case TST_struct: 8091 case TST_union: 8092 case TST_class: { 8093 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 8094 8095 // Do nothing if the tag is not anonymous or already has an 8096 // associated typedef (from an earlier typedef in this decl group). 8097 if (tagFromDeclSpec->getIdentifier()) break; 8098 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 8099 8100 // A well-formed anonymous tag must always be a TUK_Definition. 8101 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 8102 8103 // The type must match the tag exactly; no qualifiers allowed. 8104 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 8105 break; 8106 8107 // Otherwise, set this is the anon-decl typedef for the tag. 8108 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 8109 break; 8110 } 8111 8112 default: 8113 break; 8114 } 8115 8116 return NewTD; 8117 } 8118 8119 8120 /// \brief Check that this is a valid underlying type for an enum declaration. 8121 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 8122 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 8123 QualType T = TI->getType(); 8124 8125 if (T->isDependentType() || T->isIntegralType(Context)) 8126 return false; 8127 8128 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 8129 return true; 8130 } 8131 8132 /// Check whether this is a valid redeclaration of a previous enumeration. 8133 /// \return true if the redeclaration was invalid. 8134 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 8135 QualType EnumUnderlyingTy, 8136 const EnumDecl *Prev) { 8137 bool IsFixed = !EnumUnderlyingTy.isNull(); 8138 8139 if (IsScoped != Prev->isScoped()) { 8140 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 8141 << Prev->isScoped(); 8142 Diag(Prev->getLocation(), diag::note_previous_use); 8143 return true; 8144 } 8145 8146 if (IsFixed && Prev->isFixed()) { 8147 if (!EnumUnderlyingTy->isDependentType() && 8148 !Prev->getIntegerType()->isDependentType() && 8149 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 8150 Prev->getIntegerType())) { 8151 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 8152 << EnumUnderlyingTy << Prev->getIntegerType(); 8153 Diag(Prev->getLocation(), diag::note_previous_use); 8154 return true; 8155 } 8156 } else if (IsFixed != Prev->isFixed()) { 8157 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 8158 << Prev->isFixed(); 8159 Diag(Prev->getLocation(), diag::note_previous_use); 8160 return true; 8161 } 8162 8163 return false; 8164 } 8165 8166 /// \brief Determine whether a tag with a given kind is acceptable 8167 /// as a redeclaration of the given tag declaration. 8168 /// 8169 /// \returns true if the new tag kind is acceptable, false otherwise. 8170 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 8171 TagTypeKind NewTag, bool isDefinition, 8172 SourceLocation NewTagLoc, 8173 const IdentifierInfo &Name) { 8174 // C++ [dcl.type.elab]p3: 8175 // The class-key or enum keyword present in the 8176 // elaborated-type-specifier shall agree in kind with the 8177 // declaration to which the name in the elaborated-type-specifier 8178 // refers. This rule also applies to the form of 8179 // elaborated-type-specifier that declares a class-name or 8180 // friend class since it can be construed as referring to the 8181 // definition of the class. Thus, in any 8182 // elaborated-type-specifier, the enum keyword shall be used to 8183 // refer to an enumeration (7.2), the union class-key shall be 8184 // used to refer to a union (clause 9), and either the class or 8185 // struct class-key shall be used to refer to a class (clause 9) 8186 // declared using the class or struct class-key. 8187 TagTypeKind OldTag = Previous->getTagKind(); 8188 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct)) 8189 if (OldTag == NewTag) 8190 return true; 8191 8192 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 8193 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 8194 // Warn about the struct/class tag mismatch. 8195 bool isTemplate = false; 8196 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 8197 isTemplate = Record->getDescribedClassTemplate(); 8198 8199 if (!ActiveTemplateInstantiations.empty()) { 8200 // In a template instantiation, do not offer fix-its for tag mismatches 8201 // since they usually mess up the template instead of fixing the problem. 8202 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 8203 << (NewTag == TTK_Class) << isTemplate << &Name; 8204 return true; 8205 } 8206 8207 if (isDefinition) { 8208 // On definitions, check previous tags and issue a fix-it for each 8209 // one that doesn't match the current tag. 8210 if (Previous->getDefinition()) { 8211 // Don't suggest fix-its for redefinitions. 8212 return true; 8213 } 8214 8215 bool previousMismatch = false; 8216 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 8217 E(Previous->redecls_end()); I != E; ++I) { 8218 if (I->getTagKind() != NewTag) { 8219 if (!previousMismatch) { 8220 previousMismatch = true; 8221 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 8222 << (NewTag == TTK_Class) << isTemplate << &Name; 8223 } 8224 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 8225 << (NewTag == TTK_Class) 8226 << FixItHint::CreateReplacement(I->getInnerLocStart(), 8227 NewTag == TTK_Class? 8228 "class" : "struct"); 8229 } 8230 } 8231 return true; 8232 } 8233 8234 // Check for a previous definition. If current tag and definition 8235 // are same type, do nothing. If no definition, but disagree with 8236 // with previous tag type, give a warning, but no fix-it. 8237 const TagDecl *Redecl = Previous->getDefinition() ? 8238 Previous->getDefinition() : Previous; 8239 if (Redecl->getTagKind() == NewTag) { 8240 return true; 8241 } 8242 8243 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 8244 << (NewTag == TTK_Class) 8245 << isTemplate << &Name; 8246 Diag(Redecl->getLocation(), diag::note_previous_use); 8247 8248 // If there is a previous defintion, suggest a fix-it. 8249 if (Previous->getDefinition()) { 8250 Diag(NewTagLoc, diag::note_struct_class_suggestion) 8251 << (Redecl->getTagKind() == TTK_Class) 8252 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 8253 Redecl->getTagKind() == TTK_Class? "class" : "struct"); 8254 } 8255 8256 return true; 8257 } 8258 return false; 8259 } 8260 8261 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 8262 /// former case, Name will be non-null. In the later case, Name will be null. 8263 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 8264 /// reference/declaration/definition of a tag. 8265 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 8266 SourceLocation KWLoc, CXXScopeSpec &SS, 8267 IdentifierInfo *Name, SourceLocation NameLoc, 8268 AttributeList *Attr, AccessSpecifier AS, 8269 SourceLocation ModulePrivateLoc, 8270 MultiTemplateParamsArg TemplateParameterLists, 8271 bool &OwnedDecl, bool &IsDependent, 8272 SourceLocation ScopedEnumKWLoc, 8273 bool ScopedEnumUsesClassTag, 8274 TypeResult UnderlyingType) { 8275 // If this is not a definition, it must have a name. 8276 IdentifierInfo *OrigName = Name; 8277 assert((Name != 0 || TUK == TUK_Definition) && 8278 "Nameless record must be a definition!"); 8279 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 8280 8281 OwnedDecl = false; 8282 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 8283 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 8284 8285 // FIXME: Check explicit specializations more carefully. 8286 bool isExplicitSpecialization = false; 8287 bool Invalid = false; 8288 8289 // We only need to do this matching if we have template parameters 8290 // or a scope specifier, which also conveniently avoids this work 8291 // for non-C++ cases. 8292 if (TemplateParameterLists.size() > 0 || 8293 (SS.isNotEmpty() && TUK != TUK_Reference)) { 8294 if (TemplateParameterList *TemplateParams 8295 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 8296 TemplateParameterLists.get(), 8297 TemplateParameterLists.size(), 8298 TUK == TUK_Friend, 8299 isExplicitSpecialization, 8300 Invalid)) { 8301 if (TemplateParams->size() > 0) { 8302 // This is a declaration or definition of a class template (which may 8303 // be a member of another template). 8304 8305 if (Invalid) 8306 return 0; 8307 8308 OwnedDecl = false; 8309 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 8310 SS, Name, NameLoc, Attr, 8311 TemplateParams, AS, 8312 ModulePrivateLoc, 8313 TemplateParameterLists.size() - 1, 8314 (TemplateParameterList**) TemplateParameterLists.release()); 8315 return Result.get(); 8316 } else { 8317 // The "template<>" header is extraneous. 8318 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 8319 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 8320 isExplicitSpecialization = true; 8321 } 8322 } 8323 } 8324 8325 // Figure out the underlying type if this a enum declaration. We need to do 8326 // this early, because it's needed to detect if this is an incompatible 8327 // redeclaration. 8328 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 8329 8330 if (Kind == TTK_Enum) { 8331 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 8332 // No underlying type explicitly specified, or we failed to parse the 8333 // type, default to int. 8334 EnumUnderlying = Context.IntTy.getTypePtr(); 8335 else if (UnderlyingType.get()) { 8336 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 8337 // integral type; any cv-qualification is ignored. 8338 TypeSourceInfo *TI = 0; 8339 GetTypeFromParser(UnderlyingType.get(), &TI); 8340 EnumUnderlying = TI; 8341 8342 if (CheckEnumUnderlyingType(TI)) 8343 // Recover by falling back to int. 8344 EnumUnderlying = Context.IntTy.getTypePtr(); 8345 8346 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 8347 UPPC_FixedUnderlyingType)) 8348 EnumUnderlying = Context.IntTy.getTypePtr(); 8349 8350 } else if (getLangOpts().MicrosoftMode) 8351 // Microsoft enums are always of int type. 8352 EnumUnderlying = Context.IntTy.getTypePtr(); 8353 } 8354 8355 DeclContext *SearchDC = CurContext; 8356 DeclContext *DC = CurContext; 8357 bool isStdBadAlloc = false; 8358 8359 RedeclarationKind Redecl = ForRedeclaration; 8360 if (TUK == TUK_Friend || TUK == TUK_Reference) 8361 Redecl = NotForRedeclaration; 8362 8363 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 8364 8365 if (Name && SS.isNotEmpty()) { 8366 // We have a nested-name tag ('struct foo::bar'). 8367 8368 // Check for invalid 'foo::'. 8369 if (SS.isInvalid()) { 8370 Name = 0; 8371 goto CreateNewDecl; 8372 } 8373 8374 // If this is a friend or a reference to a class in a dependent 8375 // context, don't try to make a decl for it. 8376 if (TUK == TUK_Friend || TUK == TUK_Reference) { 8377 DC = computeDeclContext(SS, false); 8378 if (!DC) { 8379 IsDependent = true; 8380 return 0; 8381 } 8382 } else { 8383 DC = computeDeclContext(SS, true); 8384 if (!DC) { 8385 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 8386 << SS.getRange(); 8387 return 0; 8388 } 8389 } 8390 8391 if (RequireCompleteDeclContext(SS, DC)) 8392 return 0; 8393 8394 SearchDC = DC; 8395 // Look-up name inside 'foo::'. 8396 LookupQualifiedName(Previous, DC); 8397 8398 if (Previous.isAmbiguous()) 8399 return 0; 8400 8401 if (Previous.empty()) { 8402 // Name lookup did not find anything. However, if the 8403 // nested-name-specifier refers to the current instantiation, 8404 // and that current instantiation has any dependent base 8405 // classes, we might find something at instantiation time: treat 8406 // this as a dependent elaborated-type-specifier. 8407 // But this only makes any sense for reference-like lookups. 8408 if (Previous.wasNotFoundInCurrentInstantiation() && 8409 (TUK == TUK_Reference || TUK == TUK_Friend)) { 8410 IsDependent = true; 8411 return 0; 8412 } 8413 8414 // A tag 'foo::bar' must already exist. 8415 Diag(NameLoc, diag::err_not_tag_in_scope) 8416 << Kind << Name << DC << SS.getRange(); 8417 Name = 0; 8418 Invalid = true; 8419 goto CreateNewDecl; 8420 } 8421 } else if (Name) { 8422 // If this is a named struct, check to see if there was a previous forward 8423 // declaration or definition. 8424 // FIXME: We're looking into outer scopes here, even when we 8425 // shouldn't be. Doing so can result in ambiguities that we 8426 // shouldn't be diagnosing. 8427 LookupName(Previous, S); 8428 8429 if (Previous.isAmbiguous() && 8430 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 8431 LookupResult::Filter F = Previous.makeFilter(); 8432 while (F.hasNext()) { 8433 NamedDecl *ND = F.next(); 8434 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 8435 F.erase(); 8436 } 8437 F.done(); 8438 } 8439 8440 // Note: there used to be some attempt at recovery here. 8441 if (Previous.isAmbiguous()) 8442 return 0; 8443 8444 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 8445 // FIXME: This makes sure that we ignore the contexts associated 8446 // with C structs, unions, and enums when looking for a matching 8447 // tag declaration or definition. See the similar lookup tweak 8448 // in Sema::LookupName; is there a better way to deal with this? 8449 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 8450 SearchDC = SearchDC->getParent(); 8451 } 8452 } else if (S->isFunctionPrototypeScope()) { 8453 // If this is an enum declaration in function prototype scope, set its 8454 // initial context to the translation unit. 8455 // FIXME: [citation needed] 8456 SearchDC = Context.getTranslationUnitDecl(); 8457 } 8458 8459 if (Previous.isSingleResult() && 8460 Previous.getFoundDecl()->isTemplateParameter()) { 8461 // Maybe we will complain about the shadowed template parameter. 8462 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 8463 // Just pretend that we didn't see the previous declaration. 8464 Previous.clear(); 8465 } 8466 8467 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 8468 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 8469 // This is a declaration of or a reference to "std::bad_alloc". 8470 isStdBadAlloc = true; 8471 8472 if (Previous.empty() && StdBadAlloc) { 8473 // std::bad_alloc has been implicitly declared (but made invisible to 8474 // name lookup). Fill in this implicit declaration as the previous 8475 // declaration, so that the declarations get chained appropriately. 8476 Previous.addDecl(getStdBadAlloc()); 8477 } 8478 } 8479 8480 // If we didn't find a previous declaration, and this is a reference 8481 // (or friend reference), move to the correct scope. In C++, we 8482 // also need to do a redeclaration lookup there, just in case 8483 // there's a shadow friend decl. 8484 if (Name && Previous.empty() && 8485 (TUK == TUK_Reference || TUK == TUK_Friend)) { 8486 if (Invalid) goto CreateNewDecl; 8487 assert(SS.isEmpty()); 8488 8489 if (TUK == TUK_Reference) { 8490 // C++ [basic.scope.pdecl]p5: 8491 // -- for an elaborated-type-specifier of the form 8492 // 8493 // class-key identifier 8494 // 8495 // if the elaborated-type-specifier is used in the 8496 // decl-specifier-seq or parameter-declaration-clause of a 8497 // function defined in namespace scope, the identifier is 8498 // declared as a class-name in the namespace that contains 8499 // the declaration; otherwise, except as a friend 8500 // declaration, the identifier is declared in the smallest 8501 // non-class, non-function-prototype scope that contains the 8502 // declaration. 8503 // 8504 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 8505 // C structs and unions. 8506 // 8507 // It is an error in C++ to declare (rather than define) an enum 8508 // type, including via an elaborated type specifier. We'll 8509 // diagnose that later; for now, declare the enum in the same 8510 // scope as we would have picked for any other tag type. 8511 // 8512 // GNU C also supports this behavior as part of its incomplete 8513 // enum types extension, while GNU C++ does not. 8514 // 8515 // Find the context where we'll be declaring the tag. 8516 // FIXME: We would like to maintain the current DeclContext as the 8517 // lexical context, 8518 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 8519 SearchDC = SearchDC->getParent(); 8520 8521 // Find the scope where we'll be declaring the tag. 8522 while (S->isClassScope() || 8523 (getLangOpts().CPlusPlus && 8524 S->isFunctionPrototypeScope()) || 8525 ((S->getFlags() & Scope::DeclScope) == 0) || 8526 (S->getEntity() && 8527 ((DeclContext *)S->getEntity())->isTransparentContext())) 8528 S = S->getParent(); 8529 } else { 8530 assert(TUK == TUK_Friend); 8531 // C++ [namespace.memdef]p3: 8532 // If a friend declaration in a non-local class first declares a 8533 // class or function, the friend class or function is a member of 8534 // the innermost enclosing namespace. 8535 SearchDC = SearchDC->getEnclosingNamespaceContext(); 8536 } 8537 8538 // In C++, we need to do a redeclaration lookup to properly 8539 // diagnose some problems. 8540 if (getLangOpts().CPlusPlus) { 8541 Previous.setRedeclarationKind(ForRedeclaration); 8542 LookupQualifiedName(Previous, SearchDC); 8543 } 8544 } 8545 8546 if (!Previous.empty()) { 8547 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 8548 8549 // It's okay to have a tag decl in the same scope as a typedef 8550 // which hides a tag decl in the same scope. Finding this 8551 // insanity with a redeclaration lookup can only actually happen 8552 // in C++. 8553 // 8554 // This is also okay for elaborated-type-specifiers, which is 8555 // technically forbidden by the current standard but which is 8556 // okay according to the likely resolution of an open issue; 8557 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 8558 if (getLangOpts().CPlusPlus) { 8559 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 8560 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 8561 TagDecl *Tag = TT->getDecl(); 8562 if (Tag->getDeclName() == Name && 8563 Tag->getDeclContext()->getRedeclContext() 8564 ->Equals(TD->getDeclContext()->getRedeclContext())) { 8565 PrevDecl = Tag; 8566 Previous.clear(); 8567 Previous.addDecl(Tag); 8568 Previous.resolveKind(); 8569 } 8570 } 8571 } 8572 } 8573 8574 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 8575 // If this is a use of a previous tag, or if the tag is already declared 8576 // in the same scope (so that the definition/declaration completes or 8577 // rementions the tag), reuse the decl. 8578 if (TUK == TUK_Reference || TUK == TUK_Friend || 8579 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 8580 // Make sure that this wasn't declared as an enum and now used as a 8581 // struct or something similar. 8582 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 8583 TUK == TUK_Definition, KWLoc, 8584 *Name)) { 8585 bool SafeToContinue 8586 = (PrevTagDecl->getTagKind() != TTK_Enum && 8587 Kind != TTK_Enum); 8588 if (SafeToContinue) 8589 Diag(KWLoc, diag::err_use_with_wrong_tag) 8590 << Name 8591 << FixItHint::CreateReplacement(SourceRange(KWLoc), 8592 PrevTagDecl->getKindName()); 8593 else 8594 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 8595 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 8596 8597 if (SafeToContinue) 8598 Kind = PrevTagDecl->getTagKind(); 8599 else { 8600 // Recover by making this an anonymous redefinition. 8601 Name = 0; 8602 Previous.clear(); 8603 Invalid = true; 8604 } 8605 } 8606 8607 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 8608 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 8609 8610 // If this is an elaborated-type-specifier for a scoped enumeration, 8611 // the 'class' keyword is not necessary and not permitted. 8612 if (TUK == TUK_Reference || TUK == TUK_Friend) { 8613 if (ScopedEnum) 8614 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 8615 << PrevEnum->isScoped() 8616 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 8617 return PrevTagDecl; 8618 } 8619 8620 QualType EnumUnderlyingTy; 8621 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 8622 EnumUnderlyingTy = TI->getType(); 8623 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 8624 EnumUnderlyingTy = QualType(T, 0); 8625 8626 // All conflicts with previous declarations are recovered by 8627 // returning the previous declaration, unless this is a definition, 8628 // in which case we want the caller to bail out. 8629 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 8630 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 8631 return TUK == TUK_Declaration ? PrevTagDecl : 0; 8632 } 8633 8634 if (!Invalid) { 8635 // If this is a use, just return the declaration we found. 8636 8637 // FIXME: In the future, return a variant or some other clue 8638 // for the consumer of this Decl to know it doesn't own it. 8639 // For our current ASTs this shouldn't be a problem, but will 8640 // need to be changed with DeclGroups. 8641 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 8642 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 8643 return PrevTagDecl; 8644 8645 // Diagnose attempts to redefine a tag. 8646 if (TUK == TUK_Definition) { 8647 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 8648 // If we're defining a specialization and the previous definition 8649 // is from an implicit instantiation, don't emit an error 8650 // here; we'll catch this in the general case below. 8651 bool IsExplicitSpecializationAfterInstantiation = false; 8652 if (isExplicitSpecialization) { 8653 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 8654 IsExplicitSpecializationAfterInstantiation = 8655 RD->getTemplateSpecializationKind() != 8656 TSK_ExplicitSpecialization; 8657 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 8658 IsExplicitSpecializationAfterInstantiation = 8659 ED->getTemplateSpecializationKind() != 8660 TSK_ExplicitSpecialization; 8661 } 8662 8663 if (!IsExplicitSpecializationAfterInstantiation) { 8664 // A redeclaration in function prototype scope in C isn't 8665 // visible elsewhere, so merely issue a warning. 8666 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 8667 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 8668 else 8669 Diag(NameLoc, diag::err_redefinition) << Name; 8670 Diag(Def->getLocation(), diag::note_previous_definition); 8671 // If this is a redefinition, recover by making this 8672 // struct be anonymous, which will make any later 8673 // references get the previous definition. 8674 Name = 0; 8675 Previous.clear(); 8676 Invalid = true; 8677 } 8678 } else { 8679 // If the type is currently being defined, complain 8680 // about a nested redefinition. 8681 const TagType *Tag 8682 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 8683 if (Tag->isBeingDefined()) { 8684 Diag(NameLoc, diag::err_nested_redefinition) << Name; 8685 Diag(PrevTagDecl->getLocation(), 8686 diag::note_previous_definition); 8687 Name = 0; 8688 Previous.clear(); 8689 Invalid = true; 8690 } 8691 } 8692 8693 // Okay, this is definition of a previously declared or referenced 8694 // tag PrevDecl. We're going to create a new Decl for it. 8695 } 8696 } 8697 // If we get here we have (another) forward declaration or we 8698 // have a definition. Just create a new decl. 8699 8700 } else { 8701 // If we get here, this is a definition of a new tag type in a nested 8702 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 8703 // new decl/type. We set PrevDecl to NULL so that the entities 8704 // have distinct types. 8705 Previous.clear(); 8706 } 8707 // If we get here, we're going to create a new Decl. If PrevDecl 8708 // is non-NULL, it's a definition of the tag declared by 8709 // PrevDecl. If it's NULL, we have a new definition. 8710 8711 8712 // Otherwise, PrevDecl is not a tag, but was found with tag 8713 // lookup. This is only actually possible in C++, where a few 8714 // things like templates still live in the tag namespace. 8715 } else { 8716 // Use a better diagnostic if an elaborated-type-specifier 8717 // found the wrong kind of type on the first 8718 // (non-redeclaration) lookup. 8719 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 8720 !Previous.isForRedeclaration()) { 8721 unsigned Kind = 0; 8722 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 8723 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 8724 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 8725 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 8726 Diag(PrevDecl->getLocation(), diag::note_declared_at); 8727 Invalid = true; 8728 8729 // Otherwise, only diagnose if the declaration is in scope. 8730 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 8731 isExplicitSpecialization)) { 8732 // do nothing 8733 8734 // Diagnose implicit declarations introduced by elaborated types. 8735 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 8736 unsigned Kind = 0; 8737 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 8738 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 8739 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 8740 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 8741 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 8742 Invalid = true; 8743 8744 // Otherwise it's a declaration. Call out a particularly common 8745 // case here. 8746 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 8747 unsigned Kind = 0; 8748 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 8749 Diag(NameLoc, diag::err_tag_definition_of_typedef) 8750 << Name << Kind << TND->getUnderlyingType(); 8751 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 8752 Invalid = true; 8753 8754 // Otherwise, diagnose. 8755 } else { 8756 // The tag name clashes with something else in the target scope, 8757 // issue an error and recover by making this tag be anonymous. 8758 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 8759 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8760 Name = 0; 8761 Invalid = true; 8762 } 8763 8764 // The existing declaration isn't relevant to us; we're in a 8765 // new scope, so clear out the previous declaration. 8766 Previous.clear(); 8767 } 8768 } 8769 8770 CreateNewDecl: 8771 8772 TagDecl *PrevDecl = 0; 8773 if (Previous.isSingleResult()) 8774 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 8775 8776 // If there is an identifier, use the location of the identifier as the 8777 // location of the decl, otherwise use the location of the struct/union 8778 // keyword. 8779 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 8780 8781 // Otherwise, create a new declaration. If there is a previous 8782 // declaration of the same entity, the two will be linked via 8783 // PrevDecl. 8784 TagDecl *New; 8785 8786 bool IsForwardReference = false; 8787 if (Kind == TTK_Enum) { 8788 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 8789 // enum X { A, B, C } D; D should chain to X. 8790 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 8791 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 8792 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 8793 // If this is an undefined enum, warn. 8794 if (TUK != TUK_Definition && !Invalid) { 8795 TagDecl *Def; 8796 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) { 8797 // C++0x: 7.2p2: opaque-enum-declaration. 8798 // Conflicts are diagnosed above. Do nothing. 8799 } 8800 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 8801 Diag(Loc, diag::ext_forward_ref_enum_def) 8802 << New; 8803 Diag(Def->getLocation(), diag::note_previous_definition); 8804 } else { 8805 unsigned DiagID = diag::ext_forward_ref_enum; 8806 if (getLangOpts().MicrosoftMode) 8807 DiagID = diag::ext_ms_forward_ref_enum; 8808 else if (getLangOpts().CPlusPlus) 8809 DiagID = diag::err_forward_ref_enum; 8810 Diag(Loc, DiagID); 8811 8812 // If this is a forward-declared reference to an enumeration, make a 8813 // note of it; we won't actually be introducing the declaration into 8814 // the declaration context. 8815 if (TUK == TUK_Reference) 8816 IsForwardReference = true; 8817 } 8818 } 8819 8820 if (EnumUnderlying) { 8821 EnumDecl *ED = cast<EnumDecl>(New); 8822 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 8823 ED->setIntegerTypeSourceInfo(TI); 8824 else 8825 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 8826 ED->setPromotionType(ED->getIntegerType()); 8827 } 8828 8829 } else { 8830 // struct/union/class 8831 8832 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 8833 // struct X { int A; } D; D should chain to X. 8834 if (getLangOpts().CPlusPlus) { 8835 // FIXME: Look for a way to use RecordDecl for simple structs. 8836 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 8837 cast_or_null<CXXRecordDecl>(PrevDecl)); 8838 8839 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 8840 StdBadAlloc = cast<CXXRecordDecl>(New); 8841 } else 8842 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 8843 cast_or_null<RecordDecl>(PrevDecl)); 8844 } 8845 8846 // Maybe add qualifier info. 8847 if (SS.isNotEmpty()) { 8848 if (SS.isSet()) { 8849 // If this is either a declaration or a definition, check the 8850 // nested-name-specifier against the current context. We don't do this 8851 // for explicit specializations, because they have similar checking 8852 // (with more specific diagnostics) in the call to 8853 // CheckMemberSpecialization, below. 8854 if (!isExplicitSpecialization && 8855 (TUK == TUK_Definition || TUK == TUK_Declaration) && 8856 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 8857 Invalid = true; 8858 8859 New->setQualifierInfo(SS.getWithLocInContext(Context)); 8860 if (TemplateParameterLists.size() > 0) { 8861 New->setTemplateParameterListsInfo(Context, 8862 TemplateParameterLists.size(), 8863 (TemplateParameterList**) TemplateParameterLists.release()); 8864 } 8865 } 8866 else 8867 Invalid = true; 8868 } 8869 8870 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 8871 // Add alignment attributes if necessary; these attributes are checked when 8872 // the ASTContext lays out the structure. 8873 // 8874 // It is important for implementing the correct semantics that this 8875 // happen here (in act on tag decl). The #pragma pack stack is 8876 // maintained as a result of parser callbacks which can occur at 8877 // many points during the parsing of a struct declaration (because 8878 // the #pragma tokens are effectively skipped over during the 8879 // parsing of the struct). 8880 if (TUK == TUK_Definition) { 8881 AddAlignmentAttributesForRecord(RD); 8882 AddMsStructLayoutForRecord(RD); 8883 } 8884 } 8885 8886 if (ModulePrivateLoc.isValid()) { 8887 if (isExplicitSpecialization) 8888 Diag(New->getLocation(), diag::err_module_private_specialization) 8889 << 2 8890 << FixItHint::CreateRemoval(ModulePrivateLoc); 8891 // __module_private__ does not apply to local classes. However, we only 8892 // diagnose this as an error when the declaration specifiers are 8893 // freestanding. Here, we just ignore the __module_private__. 8894 else if (!SearchDC->isFunctionOrMethod()) 8895 New->setModulePrivate(); 8896 } 8897 8898 // If this is a specialization of a member class (of a class template), 8899 // check the specialization. 8900 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 8901 Invalid = true; 8902 8903 if (Invalid) 8904 New->setInvalidDecl(); 8905 8906 if (Attr) 8907 ProcessDeclAttributeList(S, New, Attr); 8908 8909 // If we're declaring or defining a tag in function prototype scope 8910 // in C, note that this type can only be used within the function. 8911 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 8912 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 8913 8914 // Set the lexical context. If the tag has a C++ scope specifier, the 8915 // lexical context will be different from the semantic context. 8916 New->setLexicalDeclContext(CurContext); 8917 8918 // Mark this as a friend decl if applicable. 8919 // In Microsoft mode, a friend declaration also acts as a forward 8920 // declaration so we always pass true to setObjectOfFriendDecl to make 8921 // the tag name visible. 8922 if (TUK == TUK_Friend) 8923 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 8924 getLangOpts().MicrosoftExt); 8925 8926 // Set the access specifier. 8927 if (!Invalid && SearchDC->isRecord()) 8928 SetMemberAccessSpecifier(New, PrevDecl, AS); 8929 8930 if (TUK == TUK_Definition) 8931 New->startDefinition(); 8932 8933 // If this has an identifier, add it to the scope stack. 8934 if (TUK == TUK_Friend) { 8935 // We might be replacing an existing declaration in the lookup tables; 8936 // if so, borrow its access specifier. 8937 if (PrevDecl) 8938 New->setAccess(PrevDecl->getAccess()); 8939 8940 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 8941 DC->makeDeclVisibleInContext(New); 8942 if (Name) // can be null along some error paths 8943 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 8944 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 8945 } else if (Name) { 8946 S = getNonFieldDeclScope(S); 8947 PushOnScopeChains(New, S, !IsForwardReference); 8948 if (IsForwardReference) 8949 SearchDC->makeDeclVisibleInContext(New); 8950 8951 } else { 8952 CurContext->addDecl(New); 8953 } 8954 8955 // If this is the C FILE type, notify the AST context. 8956 if (IdentifierInfo *II = New->getIdentifier()) 8957 if (!New->isInvalidDecl() && 8958 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 8959 II->isStr("FILE")) 8960 Context.setFILEDecl(New); 8961 8962 // If we were in function prototype scope (and not in C++ mode), add this 8963 // tag to the list of decls to inject into the function definition scope. 8964 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 8965 InFunctionDeclarator && Name) 8966 DeclsInPrototypeScope.push_back(New); 8967 8968 if (PrevDecl) 8969 mergeDeclAttributes(New, PrevDecl); 8970 8971 // If there's a #pragma GCC visibility in scope, set the visibility of this 8972 // record. 8973 AddPushedVisibilityAttribute(New); 8974 8975 OwnedDecl = true; 8976 return New; 8977 } 8978 8979 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 8980 AdjustDeclIfTemplate(TagD); 8981 TagDecl *Tag = cast<TagDecl>(TagD); 8982 8983 // Enter the tag context. 8984 PushDeclContext(S, Tag); 8985 8986 ActOnDocumentableDecl(TagD); 8987 8988 // If there's a #pragma GCC visibility in scope, set the visibility of this 8989 // record. 8990 AddPushedVisibilityAttribute(Tag); 8991 } 8992 8993 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 8994 assert(isa<ObjCContainerDecl>(IDecl) && 8995 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 8996 DeclContext *OCD = cast<DeclContext>(IDecl); 8997 assert(getContainingDC(OCD) == CurContext && 8998 "The next DeclContext should be lexically contained in the current one."); 8999 CurContext = OCD; 9000 return IDecl; 9001 } 9002 9003 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 9004 SourceLocation FinalLoc, 9005 SourceLocation LBraceLoc) { 9006 AdjustDeclIfTemplate(TagD); 9007 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 9008 9009 FieldCollector->StartClass(); 9010 9011 if (!Record->getIdentifier()) 9012 return; 9013 9014 if (FinalLoc.isValid()) 9015 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 9016 9017 // C++ [class]p2: 9018 // [...] The class-name is also inserted into the scope of the 9019 // class itself; this is known as the injected-class-name. For 9020 // purposes of access checking, the injected-class-name is treated 9021 // as if it were a public member name. 9022 CXXRecordDecl *InjectedClassName 9023 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 9024 Record->getLocStart(), Record->getLocation(), 9025 Record->getIdentifier(), 9026 /*PrevDecl=*/0, 9027 /*DelayTypeCreation=*/true); 9028 Context.getTypeDeclType(InjectedClassName, Record); 9029 InjectedClassName->setImplicit(); 9030 InjectedClassName->setAccess(AS_public); 9031 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 9032 InjectedClassName->setDescribedClassTemplate(Template); 9033 PushOnScopeChains(InjectedClassName, S); 9034 assert(InjectedClassName->isInjectedClassName() && 9035 "Broken injected-class-name"); 9036 } 9037 9038 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 9039 SourceLocation RBraceLoc) { 9040 AdjustDeclIfTemplate(TagD); 9041 TagDecl *Tag = cast<TagDecl>(TagD); 9042 Tag->setRBraceLoc(RBraceLoc); 9043 9044 // Make sure we "complete" the definition even it is invalid. 9045 if (Tag->isBeingDefined()) { 9046 assert(Tag->isInvalidDecl() && "We should already have completed it"); 9047 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 9048 RD->completeDefinition(); 9049 } 9050 9051 if (isa<CXXRecordDecl>(Tag)) 9052 FieldCollector->FinishClass(); 9053 9054 // Exit this scope of this tag's definition. 9055 PopDeclContext(); 9056 9057 // Notify the consumer that we've defined a tag. 9058 Consumer.HandleTagDeclDefinition(Tag); 9059 } 9060 9061 void Sema::ActOnObjCContainerFinishDefinition() { 9062 // Exit this scope of this interface definition. 9063 PopDeclContext(); 9064 } 9065 9066 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 9067 assert(DC == CurContext && "Mismatch of container contexts"); 9068 OriginalLexicalContext = DC; 9069 ActOnObjCContainerFinishDefinition(); 9070 } 9071 9072 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 9073 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 9074 OriginalLexicalContext = 0; 9075 } 9076 9077 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 9078 AdjustDeclIfTemplate(TagD); 9079 TagDecl *Tag = cast<TagDecl>(TagD); 9080 Tag->setInvalidDecl(); 9081 9082 // Make sure we "complete" the definition even it is invalid. 9083 if (Tag->isBeingDefined()) { 9084 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 9085 RD->completeDefinition(); 9086 } 9087 9088 // We're undoing ActOnTagStartDefinition here, not 9089 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 9090 // the FieldCollector. 9091 9092 PopDeclContext(); 9093 } 9094 9095 // Note that FieldName may be null for anonymous bitfields. 9096 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 9097 IdentifierInfo *FieldName, 9098 QualType FieldTy, Expr *BitWidth, 9099 bool *ZeroWidth) { 9100 // Default to true; that shouldn't confuse checks for emptiness 9101 if (ZeroWidth) 9102 *ZeroWidth = true; 9103 9104 // C99 6.7.2.1p4 - verify the field type. 9105 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 9106 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 9107 // Handle incomplete types with specific error. 9108 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 9109 return ExprError(); 9110 if (FieldName) 9111 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 9112 << FieldName << FieldTy << BitWidth->getSourceRange(); 9113 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 9114 << FieldTy << BitWidth->getSourceRange(); 9115 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 9116 UPPC_BitFieldWidth)) 9117 return ExprError(); 9118 9119 // If the bit-width is type- or value-dependent, don't try to check 9120 // it now. 9121 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 9122 return Owned(BitWidth); 9123 9124 llvm::APSInt Value; 9125 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 9126 if (ICE.isInvalid()) 9127 return ICE; 9128 BitWidth = ICE.take(); 9129 9130 if (Value != 0 && ZeroWidth) 9131 *ZeroWidth = false; 9132 9133 // Zero-width bitfield is ok for anonymous field. 9134 if (Value == 0 && FieldName) 9135 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 9136 9137 if (Value.isSigned() && Value.isNegative()) { 9138 if (FieldName) 9139 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 9140 << FieldName << Value.toString(10); 9141 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 9142 << Value.toString(10); 9143 } 9144 9145 if (!FieldTy->isDependentType()) { 9146 uint64_t TypeSize = Context.getTypeSize(FieldTy); 9147 if (Value.getZExtValue() > TypeSize) { 9148 if (!getLangOpts().CPlusPlus) { 9149 if (FieldName) 9150 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 9151 << FieldName << (unsigned)Value.getZExtValue() 9152 << (unsigned)TypeSize; 9153 9154 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 9155 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 9156 } 9157 9158 if (FieldName) 9159 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 9160 << FieldName << (unsigned)Value.getZExtValue() 9161 << (unsigned)TypeSize; 9162 else 9163 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 9164 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 9165 } 9166 } 9167 9168 return Owned(BitWidth); 9169 } 9170 9171 /// ActOnField - Each field of a C struct/union is passed into this in order 9172 /// to create a FieldDecl object for it. 9173 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 9174 Declarator &D, Expr *BitfieldWidth) { 9175 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 9176 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 9177 /*InitStyle=*/ICIS_NoInit, AS_public); 9178 return Res; 9179 } 9180 9181 /// HandleField - Analyze a field of a C struct or a C++ data member. 9182 /// 9183 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 9184 SourceLocation DeclStart, 9185 Declarator &D, Expr *BitWidth, 9186 InClassInitStyle InitStyle, 9187 AccessSpecifier AS) { 9188 IdentifierInfo *II = D.getIdentifier(); 9189 SourceLocation Loc = DeclStart; 9190 if (II) Loc = D.getIdentifierLoc(); 9191 9192 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9193 QualType T = TInfo->getType(); 9194 if (getLangOpts().CPlusPlus) { 9195 CheckExtraCXXDefaultArguments(D); 9196 9197 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9198 UPPC_DataMemberType)) { 9199 D.setInvalidType(); 9200 T = Context.IntTy; 9201 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 9202 } 9203 } 9204 9205 DiagnoseFunctionSpecifiers(D); 9206 9207 if (D.getDeclSpec().isThreadSpecified()) 9208 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 9209 if (D.getDeclSpec().isConstexprSpecified()) 9210 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 9211 << 2; 9212 9213 // Check to see if this name was declared as a member previously 9214 NamedDecl *PrevDecl = 0; 9215 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 9216 LookupName(Previous, S); 9217 switch (Previous.getResultKind()) { 9218 case LookupResult::Found: 9219 case LookupResult::FoundUnresolvedValue: 9220 PrevDecl = Previous.getAsSingle<NamedDecl>(); 9221 break; 9222 9223 case LookupResult::FoundOverloaded: 9224 PrevDecl = Previous.getRepresentativeDecl(); 9225 break; 9226 9227 case LookupResult::NotFound: 9228 case LookupResult::NotFoundInCurrentInstantiation: 9229 case LookupResult::Ambiguous: 9230 break; 9231 } 9232 Previous.suppressDiagnostics(); 9233 9234 if (PrevDecl && PrevDecl->isTemplateParameter()) { 9235 // Maybe we will complain about the shadowed template parameter. 9236 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9237 // Just pretend that we didn't see the previous declaration. 9238 PrevDecl = 0; 9239 } 9240 9241 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 9242 PrevDecl = 0; 9243 9244 bool Mutable 9245 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 9246 SourceLocation TSSL = D.getLocStart(); 9247 FieldDecl *NewFD 9248 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 9249 TSSL, AS, PrevDecl, &D); 9250 9251 if (NewFD->isInvalidDecl()) 9252 Record->setInvalidDecl(); 9253 9254 if (D.getDeclSpec().isModulePrivateSpecified()) 9255 NewFD->setModulePrivate(); 9256 9257 if (NewFD->isInvalidDecl() && PrevDecl) { 9258 // Don't introduce NewFD into scope; there's already something 9259 // with the same name in the same scope. 9260 } else if (II) { 9261 PushOnScopeChains(NewFD, S); 9262 } else 9263 Record->addDecl(NewFD); 9264 9265 return NewFD; 9266 } 9267 9268 /// \brief Build a new FieldDecl and check its well-formedness. 9269 /// 9270 /// This routine builds a new FieldDecl given the fields name, type, 9271 /// record, etc. \p PrevDecl should refer to any previous declaration 9272 /// with the same name and in the same scope as the field to be 9273 /// created. 9274 /// 9275 /// \returns a new FieldDecl. 9276 /// 9277 /// \todo The Declarator argument is a hack. It will be removed once 9278 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 9279 TypeSourceInfo *TInfo, 9280 RecordDecl *Record, SourceLocation Loc, 9281 bool Mutable, Expr *BitWidth, 9282 InClassInitStyle InitStyle, 9283 SourceLocation TSSL, 9284 AccessSpecifier AS, NamedDecl *PrevDecl, 9285 Declarator *D) { 9286 IdentifierInfo *II = Name.getAsIdentifierInfo(); 9287 bool InvalidDecl = false; 9288 if (D) InvalidDecl = D->isInvalidType(); 9289 9290 // If we receive a broken type, recover by assuming 'int' and 9291 // marking this declaration as invalid. 9292 if (T.isNull()) { 9293 InvalidDecl = true; 9294 T = Context.IntTy; 9295 } 9296 9297 QualType EltTy = Context.getBaseElementType(T); 9298 if (!EltTy->isDependentType()) { 9299 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 9300 // Fields of incomplete type force their record to be invalid. 9301 Record->setInvalidDecl(); 9302 InvalidDecl = true; 9303 } else { 9304 NamedDecl *Def; 9305 EltTy->isIncompleteType(&Def); 9306 if (Def && Def->isInvalidDecl()) { 9307 Record->setInvalidDecl(); 9308 InvalidDecl = true; 9309 } 9310 } 9311 } 9312 9313 // C99 6.7.2.1p8: A member of a structure or union may have any type other 9314 // than a variably modified type. 9315 if (!InvalidDecl && T->isVariablyModifiedType()) { 9316 bool SizeIsNegative; 9317 llvm::APSInt Oversized; 9318 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 9319 SizeIsNegative, 9320 Oversized); 9321 if (!FixedTy.isNull()) { 9322 Diag(Loc, diag::warn_illegal_constant_array_size); 9323 T = FixedTy; 9324 } else { 9325 if (SizeIsNegative) 9326 Diag(Loc, diag::err_typecheck_negative_array_size); 9327 else if (Oversized.getBoolValue()) 9328 Diag(Loc, diag::err_array_too_large) 9329 << Oversized.toString(10); 9330 else 9331 Diag(Loc, diag::err_typecheck_field_variable_size); 9332 InvalidDecl = true; 9333 } 9334 } 9335 9336 // Fields can not have abstract class types 9337 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 9338 diag::err_abstract_type_in_decl, 9339 AbstractFieldType)) 9340 InvalidDecl = true; 9341 9342 bool ZeroWidth = false; 9343 // If this is declared as a bit-field, check the bit-field. 9344 if (!InvalidDecl && BitWidth) { 9345 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take(); 9346 if (!BitWidth) { 9347 InvalidDecl = true; 9348 BitWidth = 0; 9349 ZeroWidth = false; 9350 } 9351 } 9352 9353 // Check that 'mutable' is consistent with the type of the declaration. 9354 if (!InvalidDecl && Mutable) { 9355 unsigned DiagID = 0; 9356 if (T->isReferenceType()) 9357 DiagID = diag::err_mutable_reference; 9358 else if (T.isConstQualified()) 9359 DiagID = diag::err_mutable_const; 9360 9361 if (DiagID) { 9362 SourceLocation ErrLoc = Loc; 9363 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 9364 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 9365 Diag(ErrLoc, DiagID); 9366 Mutable = false; 9367 InvalidDecl = true; 9368 } 9369 } 9370 9371 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 9372 BitWidth, Mutable, InitStyle); 9373 if (InvalidDecl) 9374 NewFD->setInvalidDecl(); 9375 9376 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 9377 Diag(Loc, diag::err_duplicate_member) << II; 9378 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9379 NewFD->setInvalidDecl(); 9380 } 9381 9382 if (!InvalidDecl && getLangOpts().CPlusPlus) { 9383 if (Record->isUnion()) { 9384 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 9385 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 9386 if (RDecl->getDefinition()) { 9387 // C++ [class.union]p1: An object of a class with a non-trivial 9388 // constructor, a non-trivial copy constructor, a non-trivial 9389 // destructor, or a non-trivial copy assignment operator 9390 // cannot be a member of a union, nor can an array of such 9391 // objects. 9392 if (CheckNontrivialField(NewFD)) 9393 NewFD->setInvalidDecl(); 9394 } 9395 } 9396 9397 // C++ [class.union]p1: If a union contains a member of reference type, 9398 // the program is ill-formed. 9399 if (EltTy->isReferenceType()) { 9400 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 9401 << NewFD->getDeclName() << EltTy; 9402 NewFD->setInvalidDecl(); 9403 } 9404 } 9405 } 9406 9407 // FIXME: We need to pass in the attributes given an AST 9408 // representation, not a parser representation. 9409 if (D) 9410 // FIXME: What to pass instead of TUScope? 9411 ProcessDeclAttributes(TUScope, NewFD, *D); 9412 9413 // In auto-retain/release, infer strong retension for fields of 9414 // retainable type. 9415 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 9416 NewFD->setInvalidDecl(); 9417 9418 if (T.isObjCGCWeak()) 9419 Diag(Loc, diag::warn_attribute_weak_on_field); 9420 9421 NewFD->setAccess(AS); 9422 return NewFD; 9423 } 9424 9425 bool Sema::CheckNontrivialField(FieldDecl *FD) { 9426 assert(FD); 9427 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 9428 9429 if (FD->isInvalidDecl()) 9430 return true; 9431 9432 QualType EltTy = Context.getBaseElementType(FD->getType()); 9433 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 9434 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 9435 if (RDecl->getDefinition()) { 9436 // We check for copy constructors before constructors 9437 // because otherwise we'll never get complaints about 9438 // copy constructors. 9439 9440 CXXSpecialMember member = CXXInvalid; 9441 if (!RDecl->hasTrivialCopyConstructor()) 9442 member = CXXCopyConstructor; 9443 else if (!RDecl->hasTrivialDefaultConstructor()) 9444 member = CXXDefaultConstructor; 9445 else if (!RDecl->hasTrivialCopyAssignment()) 9446 member = CXXCopyAssignment; 9447 else if (!RDecl->hasTrivialDestructor()) 9448 member = CXXDestructor; 9449 9450 if (member != CXXInvalid) { 9451 if (!getLangOpts().CPlusPlus0x && 9452 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 9453 // Objective-C++ ARC: it is an error to have a non-trivial field of 9454 // a union. However, system headers in Objective-C programs 9455 // occasionally have Objective-C lifetime objects within unions, 9456 // and rather than cause the program to fail, we make those 9457 // members unavailable. 9458 SourceLocation Loc = FD->getLocation(); 9459 if (getSourceManager().isInSystemHeader(Loc)) { 9460 if (!FD->hasAttr<UnavailableAttr>()) 9461 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 9462 "this system field has retaining ownership")); 9463 return false; 9464 } 9465 } 9466 9467 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ? 9468 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 9469 diag::err_illegal_union_or_anon_struct_member) 9470 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 9471 DiagnoseNontrivial(RT, member); 9472 return !getLangOpts().CPlusPlus0x; 9473 } 9474 } 9475 } 9476 9477 return false; 9478 } 9479 9480 /// If the given constructor is user-provided, produce a diagnostic explaining 9481 /// that it makes the class non-trivial. 9482 static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT, 9483 CXXConstructorDecl *CD, 9484 Sema::CXXSpecialMember CSM) { 9485 if (!CD->isUserProvided()) 9486 return false; 9487 9488 SourceLocation CtorLoc = CD->getLocation(); 9489 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM; 9490 return true; 9491 } 9492 9493 /// DiagnoseNontrivial - Given that a class has a non-trivial 9494 /// special member, figure out why. 9495 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 9496 QualType QT(T, 0U); 9497 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 9498 9499 // Check whether the member was user-declared. 9500 switch (member) { 9501 case CXXInvalid: 9502 break; 9503 9504 case CXXDefaultConstructor: 9505 if (RD->hasUserDeclaredConstructor()) { 9506 typedef CXXRecordDecl::ctor_iterator ctor_iter; 9507 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI) 9508 if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member)) 9509 return; 9510 9511 // No user-provided constructors; look for constructor templates. 9512 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 9513 tmpl_iter; 9514 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); 9515 TI != TE; ++TI) { 9516 CXXConstructorDecl *CD = 9517 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()); 9518 if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member)) 9519 return; 9520 } 9521 } 9522 break; 9523 9524 case CXXCopyConstructor: 9525 if (RD->hasUserDeclaredCopyConstructor()) { 9526 SourceLocation CtorLoc = 9527 RD->getCopyConstructor(0)->getLocation(); 9528 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 9529 return; 9530 } 9531 break; 9532 9533 case CXXMoveConstructor: 9534 if (RD->hasUserDeclaredMoveConstructor()) { 9535 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation(); 9536 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 9537 return; 9538 } 9539 break; 9540 9541 case CXXCopyAssignment: 9542 if (RD->hasUserDeclaredCopyAssignment()) { 9543 SourceLocation AssignLoc = 9544 RD->getCopyAssignmentOperator(0)->getLocation(); 9545 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 9546 return; 9547 } 9548 break; 9549 9550 case CXXMoveAssignment: 9551 if (RD->hasUserDeclaredMoveAssignment()) { 9552 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation(); 9553 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 9554 return; 9555 } 9556 break; 9557 9558 case CXXDestructor: 9559 if (RD->hasUserDeclaredDestructor()) { 9560 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 9561 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 9562 return; 9563 } 9564 break; 9565 } 9566 9567 typedef CXXRecordDecl::base_class_iterator base_iter; 9568 9569 // Virtual bases and members inhibit trivial copying/construction, 9570 // but not trivial destruction. 9571 if (member != CXXDestructor) { 9572 // Check for virtual bases. vbases includes indirect virtual bases, 9573 // so we just iterate through the direct bases. 9574 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 9575 if (bi->isVirtual()) { 9576 SourceLocation BaseLoc = bi->getLocStart(); 9577 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 9578 return; 9579 } 9580 9581 // Check for virtual methods. 9582 typedef CXXRecordDecl::method_iterator meth_iter; 9583 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 9584 ++mi) { 9585 if (mi->isVirtual()) { 9586 SourceLocation MLoc = mi->getLocStart(); 9587 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 9588 return; 9589 } 9590 } 9591 } 9592 9593 bool (CXXRecordDecl::*hasTrivial)() const; 9594 switch (member) { 9595 case CXXDefaultConstructor: 9596 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break; 9597 case CXXCopyConstructor: 9598 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 9599 case CXXCopyAssignment: 9600 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 9601 case CXXDestructor: 9602 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 9603 default: 9604 llvm_unreachable("unexpected special member"); 9605 } 9606 9607 // Check for nontrivial bases (and recurse). 9608 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 9609 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 9610 assert(BaseRT && "Don't know how to handle dependent bases"); 9611 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 9612 if (!(BaseRecTy->*hasTrivial)()) { 9613 SourceLocation BaseLoc = bi->getLocStart(); 9614 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 9615 DiagnoseNontrivial(BaseRT, member); 9616 return; 9617 } 9618 } 9619 9620 // Check for nontrivial members (and recurse). 9621 typedef RecordDecl::field_iterator field_iter; 9622 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 9623 ++fi) { 9624 QualType EltTy = Context.getBaseElementType(fi->getType()); 9625 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 9626 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 9627 9628 if (!(EltRD->*hasTrivial)()) { 9629 SourceLocation FLoc = fi->getLocation(); 9630 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 9631 DiagnoseNontrivial(EltRT, member); 9632 return; 9633 } 9634 } 9635 9636 if (EltTy->isObjCLifetimeType()) { 9637 switch (EltTy.getObjCLifetime()) { 9638 case Qualifiers::OCL_None: 9639 case Qualifiers::OCL_ExplicitNone: 9640 break; 9641 9642 case Qualifiers::OCL_Autoreleasing: 9643 case Qualifiers::OCL_Weak: 9644 case Qualifiers::OCL_Strong: 9645 Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership) 9646 << QT << EltTy.getObjCLifetime(); 9647 return; 9648 } 9649 } 9650 } 9651 9652 llvm_unreachable("found no explanation for non-trivial member"); 9653 } 9654 9655 /// TranslateIvarVisibility - Translate visibility from a token ID to an 9656 /// AST enum value. 9657 static ObjCIvarDecl::AccessControl 9658 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 9659 switch (ivarVisibility) { 9660 default: llvm_unreachable("Unknown visitibility kind"); 9661 case tok::objc_private: return ObjCIvarDecl::Private; 9662 case tok::objc_public: return ObjCIvarDecl::Public; 9663 case tok::objc_protected: return ObjCIvarDecl::Protected; 9664 case tok::objc_package: return ObjCIvarDecl::Package; 9665 } 9666 } 9667 9668 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 9669 /// in order to create an IvarDecl object for it. 9670 Decl *Sema::ActOnIvar(Scope *S, 9671 SourceLocation DeclStart, 9672 Declarator &D, Expr *BitfieldWidth, 9673 tok::ObjCKeywordKind Visibility) { 9674 9675 IdentifierInfo *II = D.getIdentifier(); 9676 Expr *BitWidth = (Expr*)BitfieldWidth; 9677 SourceLocation Loc = DeclStart; 9678 if (II) Loc = D.getIdentifierLoc(); 9679 9680 // FIXME: Unnamed fields can be handled in various different ways, for 9681 // example, unnamed unions inject all members into the struct namespace! 9682 9683 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9684 QualType T = TInfo->getType(); 9685 9686 if (BitWidth) { 9687 // 6.7.2.1p3, 6.7.2.1p4 9688 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take(); 9689 if (!BitWidth) 9690 D.setInvalidType(); 9691 } else { 9692 // Not a bitfield. 9693 9694 // validate II. 9695 9696 } 9697 if (T->isReferenceType()) { 9698 Diag(Loc, diag::err_ivar_reference_type); 9699 D.setInvalidType(); 9700 } 9701 // C99 6.7.2.1p8: A member of a structure or union may have any type other 9702 // than a variably modified type. 9703 else if (T->isVariablyModifiedType()) { 9704 Diag(Loc, diag::err_typecheck_ivar_variable_size); 9705 D.setInvalidType(); 9706 } 9707 9708 // Get the visibility (access control) for this ivar. 9709 ObjCIvarDecl::AccessControl ac = 9710 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 9711 : ObjCIvarDecl::None; 9712 // Must set ivar's DeclContext to its enclosing interface. 9713 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 9714 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 9715 return 0; 9716 ObjCContainerDecl *EnclosingContext; 9717 if (ObjCImplementationDecl *IMPDecl = 9718 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 9719 if (LangOpts.ObjCRuntime.isFragile()) { 9720 // Case of ivar declared in an implementation. Context is that of its class. 9721 EnclosingContext = IMPDecl->getClassInterface(); 9722 assert(EnclosingContext && "Implementation has no class interface!"); 9723 } 9724 else 9725 EnclosingContext = EnclosingDecl; 9726 } else { 9727 if (ObjCCategoryDecl *CDecl = 9728 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 9729 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 9730 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 9731 return 0; 9732 } 9733 } 9734 EnclosingContext = EnclosingDecl; 9735 } 9736 9737 // Construct the decl. 9738 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 9739 DeclStart, Loc, II, T, 9740 TInfo, ac, (Expr *)BitfieldWidth); 9741 9742 if (II) { 9743 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 9744 ForRedeclaration); 9745 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 9746 && !isa<TagDecl>(PrevDecl)) { 9747 Diag(Loc, diag::err_duplicate_member) << II; 9748 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9749 NewID->setInvalidDecl(); 9750 } 9751 } 9752 9753 // Process attributes attached to the ivar. 9754 ProcessDeclAttributes(S, NewID, D); 9755 9756 if (D.isInvalidType()) 9757 NewID->setInvalidDecl(); 9758 9759 // In ARC, infer 'retaining' for ivars of retainable type. 9760 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 9761 NewID->setInvalidDecl(); 9762 9763 if (D.getDeclSpec().isModulePrivateSpecified()) 9764 NewID->setModulePrivate(); 9765 9766 if (II) { 9767 // FIXME: When interfaces are DeclContexts, we'll need to add 9768 // these to the interface. 9769 S->AddDecl(NewID); 9770 IdResolver.AddDecl(NewID); 9771 } 9772 9773 if (LangOpts.ObjCRuntime.isNonFragile() && 9774 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 9775 Diag(Loc, diag::warn_ivars_in_interface); 9776 9777 return NewID; 9778 } 9779 9780 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 9781 /// class and class extensions. For every class @interface and class 9782 /// extension @interface, if the last ivar is a bitfield of any type, 9783 /// then add an implicit `char :0` ivar to the end of that interface. 9784 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 9785 SmallVectorImpl<Decl *> &AllIvarDecls) { 9786 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 9787 return; 9788 9789 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 9790 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 9791 9792 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 9793 return; 9794 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 9795 if (!ID) { 9796 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 9797 if (!CD->IsClassExtension()) 9798 return; 9799 } 9800 // No need to add this to end of @implementation. 9801 else 9802 return; 9803 } 9804 // All conditions are met. Add a new bitfield to the tail end of ivars. 9805 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 9806 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 9807 9808 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 9809 DeclLoc, DeclLoc, 0, 9810 Context.CharTy, 9811 Context.getTrivialTypeSourceInfo(Context.CharTy, 9812 DeclLoc), 9813 ObjCIvarDecl::Private, BW, 9814 true); 9815 AllIvarDecls.push_back(Ivar); 9816 } 9817 9818 void Sema::ActOnFields(Scope* S, 9819 SourceLocation RecLoc, Decl *EnclosingDecl, 9820 llvm::ArrayRef<Decl *> Fields, 9821 SourceLocation LBrac, SourceLocation RBrac, 9822 AttributeList *Attr) { 9823 assert(EnclosingDecl && "missing record or interface decl"); 9824 9825 // If this is an Objective-C @implementation or category and we have 9826 // new fields here we should reset the layout of the interface since 9827 // it will now change. 9828 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 9829 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 9830 switch (DC->getKind()) { 9831 default: break; 9832 case Decl::ObjCCategory: 9833 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 9834 break; 9835 case Decl::ObjCImplementation: 9836 Context. 9837 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 9838 break; 9839 } 9840 } 9841 9842 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 9843 9844 // Start counting up the number of named members; make sure to include 9845 // members of anonymous structs and unions in the total. 9846 unsigned NumNamedMembers = 0; 9847 if (Record) { 9848 for (RecordDecl::decl_iterator i = Record->decls_begin(), 9849 e = Record->decls_end(); i != e; i++) { 9850 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 9851 if (IFD->getDeclName()) 9852 ++NumNamedMembers; 9853 } 9854 } 9855 9856 // Verify that all the fields are okay. 9857 SmallVector<FieldDecl*, 32> RecFields; 9858 9859 bool ARCErrReported = false; 9860 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 9861 i != end; ++i) { 9862 FieldDecl *FD = cast<FieldDecl>(*i); 9863 9864 // Get the type for the field. 9865 const Type *FDTy = FD->getType().getTypePtr(); 9866 9867 if (!FD->isAnonymousStructOrUnion()) { 9868 // Remember all fields written by the user. 9869 RecFields.push_back(FD); 9870 } 9871 9872 // If the field is already invalid for some reason, don't emit more 9873 // diagnostics about it. 9874 if (FD->isInvalidDecl()) { 9875 EnclosingDecl->setInvalidDecl(); 9876 continue; 9877 } 9878 9879 // C99 6.7.2.1p2: 9880 // A structure or union shall not contain a member with 9881 // incomplete or function type (hence, a structure shall not 9882 // contain an instance of itself, but may contain a pointer to 9883 // an instance of itself), except that the last member of a 9884 // structure with more than one named member may have incomplete 9885 // array type; such a structure (and any union containing, 9886 // possibly recursively, a member that is such a structure) 9887 // shall not be a member of a structure or an element of an 9888 // array. 9889 if (FDTy->isFunctionType()) { 9890 // Field declared as a function. 9891 Diag(FD->getLocation(), diag::err_field_declared_as_function) 9892 << FD->getDeclName(); 9893 FD->setInvalidDecl(); 9894 EnclosingDecl->setInvalidDecl(); 9895 continue; 9896 } else if (FDTy->isIncompleteArrayType() && Record && 9897 ((i + 1 == Fields.end() && !Record->isUnion()) || 9898 ((getLangOpts().MicrosoftExt || 9899 getLangOpts().CPlusPlus) && 9900 (i + 1 == Fields.end() || Record->isUnion())))) { 9901 // Flexible array member. 9902 // Microsoft and g++ is more permissive regarding flexible array. 9903 // It will accept flexible array in union and also 9904 // as the sole element of a struct/class. 9905 if (getLangOpts().MicrosoftExt) { 9906 if (Record->isUnion()) 9907 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 9908 << FD->getDeclName(); 9909 else if (Fields.size() == 1) 9910 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 9911 << FD->getDeclName() << Record->getTagKind(); 9912 } else if (getLangOpts().CPlusPlus) { 9913 if (Record->isUnion()) 9914 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 9915 << FD->getDeclName(); 9916 else if (Fields.size() == 1) 9917 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 9918 << FD->getDeclName() << Record->getTagKind(); 9919 } else if (!getLangOpts().C99) { 9920 if (Record->isUnion()) 9921 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 9922 << FD->getDeclName(); 9923 else 9924 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 9925 << FD->getDeclName() << Record->getTagKind(); 9926 } else if (NumNamedMembers < 1) { 9927 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 9928 << FD->getDeclName(); 9929 FD->setInvalidDecl(); 9930 EnclosingDecl->setInvalidDecl(); 9931 continue; 9932 } 9933 if (!FD->getType()->isDependentType() && 9934 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 9935 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 9936 << FD->getDeclName() << FD->getType(); 9937 FD->setInvalidDecl(); 9938 EnclosingDecl->setInvalidDecl(); 9939 continue; 9940 } 9941 // Okay, we have a legal flexible array member at the end of the struct. 9942 if (Record) 9943 Record->setHasFlexibleArrayMember(true); 9944 } else if (!FDTy->isDependentType() && 9945 RequireCompleteType(FD->getLocation(), FD->getType(), 9946 diag::err_field_incomplete)) { 9947 // Incomplete type 9948 FD->setInvalidDecl(); 9949 EnclosingDecl->setInvalidDecl(); 9950 continue; 9951 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 9952 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 9953 // If this is a member of a union, then entire union becomes "flexible". 9954 if (Record && Record->isUnion()) { 9955 Record->setHasFlexibleArrayMember(true); 9956 } else { 9957 // If this is a struct/class and this is not the last element, reject 9958 // it. Note that GCC supports variable sized arrays in the middle of 9959 // structures. 9960 if (i + 1 != Fields.end()) 9961 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 9962 << FD->getDeclName() << FD->getType(); 9963 else { 9964 // We support flexible arrays at the end of structs in 9965 // other structs as an extension. 9966 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 9967 << FD->getDeclName(); 9968 if (Record) 9969 Record->setHasFlexibleArrayMember(true); 9970 } 9971 } 9972 } 9973 if (isa<ObjCContainerDecl>(EnclosingDecl) && 9974 RequireNonAbstractType(FD->getLocation(), FD->getType(), 9975 diag::err_abstract_type_in_decl, 9976 AbstractIvarType)) { 9977 // Ivars can not have abstract class types 9978 FD->setInvalidDecl(); 9979 } 9980 if (Record && FDTTy->getDecl()->hasObjectMember()) 9981 Record->setHasObjectMember(true); 9982 } else if (FDTy->isObjCObjectType()) { 9983 /// A field cannot be an Objective-c object 9984 Diag(FD->getLocation(), diag::err_statically_allocated_object) 9985 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 9986 QualType T = Context.getObjCObjectPointerType(FD->getType()); 9987 FD->setType(T); 9988 } else if (!getLangOpts().CPlusPlus) { 9989 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) { 9990 // It's an error in ARC if a field has lifetime. 9991 // We don't want to report this in a system header, though, 9992 // so we just make the field unavailable. 9993 // FIXME: that's really not sufficient; we need to make the type 9994 // itself invalid to, say, initialize or copy. 9995 QualType T = FD->getType(); 9996 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 9997 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 9998 SourceLocation loc = FD->getLocation(); 9999 if (getSourceManager().isInSystemHeader(loc)) { 10000 if (!FD->hasAttr<UnavailableAttr>()) { 10001 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 10002 "this system field has retaining ownership")); 10003 } 10004 } else { 10005 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct) 10006 << T->isBlockPointerType(); 10007 } 10008 ARCErrReported = true; 10009 } 10010 } 10011 else if (getLangOpts().ObjC1 && 10012 getLangOpts().getGC() != LangOptions::NonGC && 10013 Record && !Record->hasObjectMember()) { 10014 if (FD->getType()->isObjCObjectPointerType() || 10015 FD->getType().isObjCGCStrong()) 10016 Record->setHasObjectMember(true); 10017 else if (Context.getAsArrayType(FD->getType())) { 10018 QualType BaseType = Context.getBaseElementType(FD->getType()); 10019 if (BaseType->isRecordType() && 10020 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 10021 Record->setHasObjectMember(true); 10022 else if (BaseType->isObjCObjectPointerType() || 10023 BaseType.isObjCGCStrong()) 10024 Record->setHasObjectMember(true); 10025 } 10026 } 10027 } 10028 // Keep track of the number of named members. 10029 if (FD->getIdentifier()) 10030 ++NumNamedMembers; 10031 } 10032 10033 // Okay, we successfully defined 'Record'. 10034 if (Record) { 10035 bool Completed = false; 10036 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 10037 if (!CXXRecord->isInvalidDecl()) { 10038 // Set access bits correctly on the directly-declared conversions. 10039 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions(); 10040 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 10041 I != E; ++I) 10042 Convs->setAccess(I, (*I)->getAccess()); 10043 10044 if (!CXXRecord->isDependentType()) { 10045 // Objective-C Automatic Reference Counting: 10046 // If a class has a non-static data member of Objective-C pointer 10047 // type (or array thereof), it is a non-POD type and its 10048 // default constructor (if any), copy constructor, copy assignment 10049 // operator, and destructor are non-trivial. 10050 // 10051 // This rule is also handled by CXXRecordDecl::completeDefinition(). 10052 // However, here we check whether this particular class is only 10053 // non-POD because of the presence of an Objective-C pointer member. 10054 // If so, objects of this type cannot be shared between code compiled 10055 // with ARC and code compiled with manual retain/release. 10056 if (getLangOpts().ObjCAutoRefCount && 10057 CXXRecord->hasObjectMember() && 10058 CXXRecord->getLinkage() == ExternalLinkage) { 10059 if (CXXRecord->isPOD()) { 10060 Diag(CXXRecord->getLocation(), 10061 diag::warn_arc_non_pod_class_with_object_member) 10062 << CXXRecord; 10063 } else { 10064 // FIXME: Fix-Its would be nice here, but finding a good location 10065 // for them is going to be tricky. 10066 if (CXXRecord->hasTrivialCopyConstructor()) 10067 Diag(CXXRecord->getLocation(), 10068 diag::warn_arc_trivial_member_function_with_object_member) 10069 << CXXRecord << 0; 10070 if (CXXRecord->hasTrivialCopyAssignment()) 10071 Diag(CXXRecord->getLocation(), 10072 diag::warn_arc_trivial_member_function_with_object_member) 10073 << CXXRecord << 1; 10074 if (CXXRecord->hasTrivialDestructor()) 10075 Diag(CXXRecord->getLocation(), 10076 diag::warn_arc_trivial_member_function_with_object_member) 10077 << CXXRecord << 2; 10078 } 10079 } 10080 10081 // Adjust user-defined destructor exception spec. 10082 if (getLangOpts().CPlusPlus0x && 10083 CXXRecord->hasUserDeclaredDestructor()) 10084 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 10085 10086 // Add any implicitly-declared members to this class. 10087 AddImplicitlyDeclaredMembersToClass(CXXRecord); 10088 10089 // If we have virtual base classes, we may end up finding multiple 10090 // final overriders for a given virtual function. Check for this 10091 // problem now. 10092 if (CXXRecord->getNumVBases()) { 10093 CXXFinalOverriderMap FinalOverriders; 10094 CXXRecord->getFinalOverriders(FinalOverriders); 10095 10096 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 10097 MEnd = FinalOverriders.end(); 10098 M != MEnd; ++M) { 10099 for (OverridingMethods::iterator SO = M->second.begin(), 10100 SOEnd = M->second.end(); 10101 SO != SOEnd; ++SO) { 10102 assert(SO->second.size() > 0 && 10103 "Virtual function without overridding functions?"); 10104 if (SO->second.size() == 1) 10105 continue; 10106 10107 // C++ [class.virtual]p2: 10108 // In a derived class, if a virtual member function of a base 10109 // class subobject has more than one final overrider the 10110 // program is ill-formed. 10111 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 10112 << (NamedDecl *)M->first << Record; 10113 Diag(M->first->getLocation(), 10114 diag::note_overridden_virtual_function); 10115 for (OverridingMethods::overriding_iterator 10116 OM = SO->second.begin(), 10117 OMEnd = SO->second.end(); 10118 OM != OMEnd; ++OM) 10119 Diag(OM->Method->getLocation(), diag::note_final_overrider) 10120 << (NamedDecl *)M->first << OM->Method->getParent(); 10121 10122 Record->setInvalidDecl(); 10123 } 10124 } 10125 CXXRecord->completeDefinition(&FinalOverriders); 10126 Completed = true; 10127 } 10128 } 10129 } 10130 } 10131 10132 if (!Completed) 10133 Record->completeDefinition(); 10134 10135 } else { 10136 ObjCIvarDecl **ClsFields = 10137 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 10138 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 10139 ID->setEndOfDefinitionLoc(RBrac); 10140 // Add ivar's to class's DeclContext. 10141 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 10142 ClsFields[i]->setLexicalDeclContext(ID); 10143 ID->addDecl(ClsFields[i]); 10144 } 10145 // Must enforce the rule that ivars in the base classes may not be 10146 // duplicates. 10147 if (ID->getSuperClass()) 10148 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 10149 } else if (ObjCImplementationDecl *IMPDecl = 10150 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10151 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 10152 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 10153 // Ivar declared in @implementation never belongs to the implementation. 10154 // Only it is in implementation's lexical context. 10155 ClsFields[I]->setLexicalDeclContext(IMPDecl); 10156 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 10157 IMPDecl->setIvarLBraceLoc(LBrac); 10158 IMPDecl->setIvarRBraceLoc(RBrac); 10159 } else if (ObjCCategoryDecl *CDecl = 10160 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 10161 // case of ivars in class extension; all other cases have been 10162 // reported as errors elsewhere. 10163 // FIXME. Class extension does not have a LocEnd field. 10164 // CDecl->setLocEnd(RBrac); 10165 // Add ivar's to class extension's DeclContext. 10166 // Diagnose redeclaration of private ivars. 10167 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 10168 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 10169 if (IDecl) { 10170 if (const ObjCIvarDecl *ClsIvar = 10171 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 10172 Diag(ClsFields[i]->getLocation(), 10173 diag::err_duplicate_ivar_declaration); 10174 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 10175 continue; 10176 } 10177 for (const ObjCCategoryDecl *ClsExtDecl = 10178 IDecl->getFirstClassExtension(); 10179 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) { 10180 if (const ObjCIvarDecl *ClsExtIvar = 10181 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 10182 Diag(ClsFields[i]->getLocation(), 10183 diag::err_duplicate_ivar_declaration); 10184 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 10185 continue; 10186 } 10187 } 10188 } 10189 ClsFields[i]->setLexicalDeclContext(CDecl); 10190 CDecl->addDecl(ClsFields[i]); 10191 } 10192 CDecl->setIvarLBraceLoc(LBrac); 10193 CDecl->setIvarRBraceLoc(RBrac); 10194 } 10195 } 10196 10197 if (Attr) 10198 ProcessDeclAttributeList(S, Record, Attr); 10199 } 10200 10201 /// \brief Determine whether the given integral value is representable within 10202 /// the given type T. 10203 static bool isRepresentableIntegerValue(ASTContext &Context, 10204 llvm::APSInt &Value, 10205 QualType T) { 10206 assert(T->isIntegralType(Context) && "Integral type required!"); 10207 unsigned BitWidth = Context.getIntWidth(T); 10208 10209 if (Value.isUnsigned() || Value.isNonNegative()) { 10210 if (T->isSignedIntegerOrEnumerationType()) 10211 --BitWidth; 10212 return Value.getActiveBits() <= BitWidth; 10213 } 10214 return Value.getMinSignedBits() <= BitWidth; 10215 } 10216 10217 // \brief Given an integral type, return the next larger integral type 10218 // (or a NULL type of no such type exists). 10219 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 10220 // FIXME: Int128/UInt128 support, which also needs to be introduced into 10221 // enum checking below. 10222 assert(T->isIntegralType(Context) && "Integral type required!"); 10223 const unsigned NumTypes = 4; 10224 QualType SignedIntegralTypes[NumTypes] = { 10225 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 10226 }; 10227 QualType UnsignedIntegralTypes[NumTypes] = { 10228 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 10229 Context.UnsignedLongLongTy 10230 }; 10231 10232 unsigned BitWidth = Context.getTypeSize(T); 10233 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 10234 : UnsignedIntegralTypes; 10235 for (unsigned I = 0; I != NumTypes; ++I) 10236 if (Context.getTypeSize(Types[I]) > BitWidth) 10237 return Types[I]; 10238 10239 return QualType(); 10240 } 10241 10242 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 10243 EnumConstantDecl *LastEnumConst, 10244 SourceLocation IdLoc, 10245 IdentifierInfo *Id, 10246 Expr *Val) { 10247 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 10248 llvm::APSInt EnumVal(IntWidth); 10249 QualType EltTy; 10250 10251 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 10252 Val = 0; 10253 10254 if (Val) 10255 Val = DefaultLvalueConversion(Val).take(); 10256 10257 if (Val) { 10258 if (Enum->isDependentType() || Val->isTypeDependent()) 10259 EltTy = Context.DependentTy; 10260 else { 10261 SourceLocation ExpLoc; 10262 if (getLangOpts().CPlusPlus0x && Enum->isFixed() && 10263 !getLangOpts().MicrosoftMode) { 10264 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 10265 // constant-expression in the enumerator-definition shall be a converted 10266 // constant expression of the underlying type. 10267 EltTy = Enum->getIntegerType(); 10268 ExprResult Converted = 10269 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 10270 CCEK_Enumerator); 10271 if (Converted.isInvalid()) 10272 Val = 0; 10273 else 10274 Val = Converted.take(); 10275 } else if (!Val->isValueDependent() && 10276 !(Val = VerifyIntegerConstantExpression(Val, 10277 &EnumVal).take())) { 10278 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 10279 } else { 10280 if (Enum->isFixed()) { 10281 EltTy = Enum->getIntegerType(); 10282 10283 // In Obj-C and Microsoft mode, require the enumeration value to be 10284 // representable in the underlying type of the enumeration. In C++11, 10285 // we perform a non-narrowing conversion as part of converted constant 10286 // expression checking. 10287 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 10288 if (getLangOpts().MicrosoftMode) { 10289 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 10290 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 10291 } else 10292 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 10293 } else 10294 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 10295 } else if (getLangOpts().CPlusPlus) { 10296 // C++11 [dcl.enum]p5: 10297 // If the underlying type is not fixed, the type of each enumerator 10298 // is the type of its initializing value: 10299 // - If an initializer is specified for an enumerator, the 10300 // initializing value has the same type as the expression. 10301 EltTy = Val->getType(); 10302 } else { 10303 // C99 6.7.2.2p2: 10304 // The expression that defines the value of an enumeration constant 10305 // shall be an integer constant expression that has a value 10306 // representable as an int. 10307 10308 // Complain if the value is not representable in an int. 10309 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 10310 Diag(IdLoc, diag::ext_enum_value_not_int) 10311 << EnumVal.toString(10) << Val->getSourceRange() 10312 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 10313 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 10314 // Force the type of the expression to 'int'. 10315 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 10316 } 10317 EltTy = Val->getType(); 10318 } 10319 } 10320 } 10321 } 10322 10323 if (!Val) { 10324 if (Enum->isDependentType()) 10325 EltTy = Context.DependentTy; 10326 else if (!LastEnumConst) { 10327 // C++0x [dcl.enum]p5: 10328 // If the underlying type is not fixed, the type of each enumerator 10329 // is the type of its initializing value: 10330 // - If no initializer is specified for the first enumerator, the 10331 // initializing value has an unspecified integral type. 10332 // 10333 // GCC uses 'int' for its unspecified integral type, as does 10334 // C99 6.7.2.2p3. 10335 if (Enum->isFixed()) { 10336 EltTy = Enum->getIntegerType(); 10337 } 10338 else { 10339 EltTy = Context.IntTy; 10340 } 10341 } else { 10342 // Assign the last value + 1. 10343 EnumVal = LastEnumConst->getInitVal(); 10344 ++EnumVal; 10345 EltTy = LastEnumConst->getType(); 10346 10347 // Check for overflow on increment. 10348 if (EnumVal < LastEnumConst->getInitVal()) { 10349 // C++0x [dcl.enum]p5: 10350 // If the underlying type is not fixed, the type of each enumerator 10351 // is the type of its initializing value: 10352 // 10353 // - Otherwise the type of the initializing value is the same as 10354 // the type of the initializing value of the preceding enumerator 10355 // unless the incremented value is not representable in that type, 10356 // in which case the type is an unspecified integral type 10357 // sufficient to contain the incremented value. If no such type 10358 // exists, the program is ill-formed. 10359 QualType T = getNextLargerIntegralType(Context, EltTy); 10360 if (T.isNull() || Enum->isFixed()) { 10361 // There is no integral type larger enough to represent this 10362 // value. Complain, then allow the value to wrap around. 10363 EnumVal = LastEnumConst->getInitVal(); 10364 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 10365 ++EnumVal; 10366 if (Enum->isFixed()) 10367 // When the underlying type is fixed, this is ill-formed. 10368 Diag(IdLoc, diag::err_enumerator_wrapped) 10369 << EnumVal.toString(10) 10370 << EltTy; 10371 else 10372 Diag(IdLoc, diag::warn_enumerator_too_large) 10373 << EnumVal.toString(10); 10374 } else { 10375 EltTy = T; 10376 } 10377 10378 // Retrieve the last enumerator's value, extent that type to the 10379 // type that is supposed to be large enough to represent the incremented 10380 // value, then increment. 10381 EnumVal = LastEnumConst->getInitVal(); 10382 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 10383 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 10384 ++EnumVal; 10385 10386 // If we're not in C++, diagnose the overflow of enumerator values, 10387 // which in C99 means that the enumerator value is not representable in 10388 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 10389 // permits enumerator values that are representable in some larger 10390 // integral type. 10391 if (!getLangOpts().CPlusPlus && !T.isNull()) 10392 Diag(IdLoc, diag::warn_enum_value_overflow); 10393 } else if (!getLangOpts().CPlusPlus && 10394 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 10395 // Enforce C99 6.7.2.2p2 even when we compute the next value. 10396 Diag(IdLoc, diag::ext_enum_value_not_int) 10397 << EnumVal.toString(10) << 1; 10398 } 10399 } 10400 } 10401 10402 if (!EltTy->isDependentType()) { 10403 // Make the enumerator value match the signedness and size of the 10404 // enumerator's type. 10405 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 10406 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 10407 } 10408 10409 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 10410 Val, EnumVal); 10411 } 10412 10413 10414 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 10415 SourceLocation IdLoc, IdentifierInfo *Id, 10416 AttributeList *Attr, 10417 SourceLocation EqualLoc, Expr *Val) { 10418 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 10419 EnumConstantDecl *LastEnumConst = 10420 cast_or_null<EnumConstantDecl>(lastEnumConst); 10421 10422 // The scope passed in may not be a decl scope. Zip up the scope tree until 10423 // we find one that is. 10424 S = getNonFieldDeclScope(S); 10425 10426 // Verify that there isn't already something declared with this name in this 10427 // scope. 10428 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 10429 ForRedeclaration); 10430 if (PrevDecl && PrevDecl->isTemplateParameter()) { 10431 // Maybe we will complain about the shadowed template parameter. 10432 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 10433 // Just pretend that we didn't see the previous declaration. 10434 PrevDecl = 0; 10435 } 10436 10437 if (PrevDecl) { 10438 // When in C++, we may get a TagDecl with the same name; in this case the 10439 // enum constant will 'hide' the tag. 10440 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 10441 "Received TagDecl when not in C++!"); 10442 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 10443 if (isa<EnumConstantDecl>(PrevDecl)) 10444 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 10445 else 10446 Diag(IdLoc, diag::err_redefinition) << Id; 10447 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10448 return 0; 10449 } 10450 } 10451 10452 // C++ [class.mem]p15: 10453 // If T is the name of a class, then each of the following shall have a name 10454 // different from T: 10455 // - every enumerator of every member of class T that is an unscoped 10456 // enumerated type 10457 if (CXXRecordDecl *Record 10458 = dyn_cast<CXXRecordDecl>( 10459 TheEnumDecl->getDeclContext()->getRedeclContext())) 10460 if (!TheEnumDecl->isScoped() && 10461 Record->getIdentifier() && Record->getIdentifier() == Id) 10462 Diag(IdLoc, diag::err_member_name_of_class) << Id; 10463 10464 EnumConstantDecl *New = 10465 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 10466 10467 if (New) { 10468 // Process attributes. 10469 if (Attr) ProcessDeclAttributeList(S, New, Attr); 10470 10471 // Register this decl in the current scope stack. 10472 New->setAccess(TheEnumDecl->getAccess()); 10473 PushOnScopeChains(New, S); 10474 } 10475 10476 ActOnDocumentableDecl(New); 10477 10478 return New; 10479 } 10480 10481 // Emits a warning if every element in the enum is the same value and if 10482 // every element is initialized with a integer or boolean literal. 10483 static void CheckForUniqueEnumValues(Sema &S, Decl **Elements, 10484 unsigned NumElements, EnumDecl *Enum, 10485 QualType EnumType) { 10486 if (S.Diags.getDiagnosticLevel(diag::warn_identical_enum_values, 10487 Enum->getLocation()) == 10488 DiagnosticsEngine::Ignored) 10489 return; 10490 10491 if (NumElements < 2) 10492 return; 10493 10494 if (!Enum->getIdentifier()) 10495 return; 10496 10497 llvm::APSInt FirstVal; 10498 10499 for (unsigned i = 0; i != NumElements; ++i) { 10500 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 10501 if (!ECD) 10502 return; 10503 10504 Expr *InitExpr = ECD->getInitExpr(); 10505 if (!InitExpr) 10506 return; 10507 InitExpr = InitExpr->IgnoreImpCasts(); 10508 if (!isa<IntegerLiteral>(InitExpr) && !isa<CXXBoolLiteralExpr>(InitExpr)) 10509 return; 10510 10511 if (i == 0) { 10512 FirstVal = ECD->getInitVal(); 10513 continue; 10514 } 10515 10516 if (!llvm::APSInt::isSameValue(FirstVal, ECD->getInitVal())) 10517 return; 10518 } 10519 10520 S.Diag(Enum->getLocation(), diag::warn_identical_enum_values) 10521 << EnumType << FirstVal.toString(10) 10522 << Enum->getSourceRange(); 10523 10524 EnumConstantDecl *Last = cast<EnumConstantDecl>(Elements[NumElements - 1]), 10525 *Next = cast<EnumConstantDecl>(Elements[NumElements - 2]); 10526 10527 S.Diag(Last->getLocation(), diag::note_identical_enum_values) 10528 << FixItHint::CreateReplacement(Last->getInitExpr()->getSourceRange(), 10529 Next->getName()); 10530 } 10531 10532 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 10533 SourceLocation RBraceLoc, Decl *EnumDeclX, 10534 Decl **Elements, unsigned NumElements, 10535 Scope *S, AttributeList *Attr) { 10536 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 10537 QualType EnumType = Context.getTypeDeclType(Enum); 10538 10539 if (Attr) 10540 ProcessDeclAttributeList(S, Enum, Attr); 10541 10542 if (Enum->isDependentType()) { 10543 for (unsigned i = 0; i != NumElements; ++i) { 10544 EnumConstantDecl *ECD = 10545 cast_or_null<EnumConstantDecl>(Elements[i]); 10546 if (!ECD) continue; 10547 10548 ECD->setType(EnumType); 10549 } 10550 10551 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 10552 return; 10553 } 10554 10555 // TODO: If the result value doesn't fit in an int, it must be a long or long 10556 // long value. ISO C does not support this, but GCC does as an extension, 10557 // emit a warning. 10558 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 10559 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 10560 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 10561 10562 // Verify that all the values are okay, compute the size of the values, and 10563 // reverse the list. 10564 unsigned NumNegativeBits = 0; 10565 unsigned NumPositiveBits = 0; 10566 10567 // Keep track of whether all elements have type int. 10568 bool AllElementsInt = true; 10569 10570 for (unsigned i = 0; i != NumElements; ++i) { 10571 EnumConstantDecl *ECD = 10572 cast_or_null<EnumConstantDecl>(Elements[i]); 10573 if (!ECD) continue; // Already issued a diagnostic. 10574 10575 const llvm::APSInt &InitVal = ECD->getInitVal(); 10576 10577 // Keep track of the size of positive and negative values. 10578 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 10579 NumPositiveBits = std::max(NumPositiveBits, 10580 (unsigned)InitVal.getActiveBits()); 10581 else 10582 NumNegativeBits = std::max(NumNegativeBits, 10583 (unsigned)InitVal.getMinSignedBits()); 10584 10585 // Keep track of whether every enum element has type int (very commmon). 10586 if (AllElementsInt) 10587 AllElementsInt = ECD->getType() == Context.IntTy; 10588 } 10589 10590 // Figure out the type that should be used for this enum. 10591 QualType BestType; 10592 unsigned BestWidth; 10593 10594 // C++0x N3000 [conv.prom]p3: 10595 // An rvalue of an unscoped enumeration type whose underlying 10596 // type is not fixed can be converted to an rvalue of the first 10597 // of the following types that can represent all the values of 10598 // the enumeration: int, unsigned int, long int, unsigned long 10599 // int, long long int, or unsigned long long int. 10600 // C99 6.4.4.3p2: 10601 // An identifier declared as an enumeration constant has type int. 10602 // The C99 rule is modified by a gcc extension 10603 QualType BestPromotionType; 10604 10605 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 10606 // -fshort-enums is the equivalent to specifying the packed attribute on all 10607 // enum definitions. 10608 if (LangOpts.ShortEnums) 10609 Packed = true; 10610 10611 if (Enum->isFixed()) { 10612 BestType = Enum->getIntegerType(); 10613 if (BestType->isPromotableIntegerType()) 10614 BestPromotionType = Context.getPromotedIntegerType(BestType); 10615 else 10616 BestPromotionType = BestType; 10617 // We don't need to set BestWidth, because BestType is going to be the type 10618 // of the enumerators, but we do anyway because otherwise some compilers 10619 // warn that it might be used uninitialized. 10620 BestWidth = CharWidth; 10621 } 10622 else if (NumNegativeBits) { 10623 // If there is a negative value, figure out the smallest integer type (of 10624 // int/long/longlong) that fits. 10625 // If it's packed, check also if it fits a char or a short. 10626 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 10627 BestType = Context.SignedCharTy; 10628 BestWidth = CharWidth; 10629 } else if (Packed && NumNegativeBits <= ShortWidth && 10630 NumPositiveBits < ShortWidth) { 10631 BestType = Context.ShortTy; 10632 BestWidth = ShortWidth; 10633 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 10634 BestType = Context.IntTy; 10635 BestWidth = IntWidth; 10636 } else { 10637 BestWidth = Context.getTargetInfo().getLongWidth(); 10638 10639 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 10640 BestType = Context.LongTy; 10641 } else { 10642 BestWidth = Context.getTargetInfo().getLongLongWidth(); 10643 10644 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 10645 Diag(Enum->getLocation(), diag::warn_enum_too_large); 10646 BestType = Context.LongLongTy; 10647 } 10648 } 10649 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 10650 } else { 10651 // If there is no negative value, figure out the smallest type that fits 10652 // all of the enumerator values. 10653 // If it's packed, check also if it fits a char or a short. 10654 if (Packed && NumPositiveBits <= CharWidth) { 10655 BestType = Context.UnsignedCharTy; 10656 BestPromotionType = Context.IntTy; 10657 BestWidth = CharWidth; 10658 } else if (Packed && NumPositiveBits <= ShortWidth) { 10659 BestType = Context.UnsignedShortTy; 10660 BestPromotionType = Context.IntTy; 10661 BestWidth = ShortWidth; 10662 } else if (NumPositiveBits <= IntWidth) { 10663 BestType = Context.UnsignedIntTy; 10664 BestWidth = IntWidth; 10665 BestPromotionType 10666 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10667 ? Context.UnsignedIntTy : Context.IntTy; 10668 } else if (NumPositiveBits <= 10669 (BestWidth = Context.getTargetInfo().getLongWidth())) { 10670 BestType = Context.UnsignedLongTy; 10671 BestPromotionType 10672 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10673 ? Context.UnsignedLongTy : Context.LongTy; 10674 } else { 10675 BestWidth = Context.getTargetInfo().getLongLongWidth(); 10676 assert(NumPositiveBits <= BestWidth && 10677 "How could an initializer get larger than ULL?"); 10678 BestType = Context.UnsignedLongLongTy; 10679 BestPromotionType 10680 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10681 ? Context.UnsignedLongLongTy : Context.LongLongTy; 10682 } 10683 } 10684 10685 // Loop over all of the enumerator constants, changing their types to match 10686 // the type of the enum if needed. 10687 for (unsigned i = 0; i != NumElements; ++i) { 10688 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 10689 if (!ECD) continue; // Already issued a diagnostic. 10690 10691 // Standard C says the enumerators have int type, but we allow, as an 10692 // extension, the enumerators to be larger than int size. If each 10693 // enumerator value fits in an int, type it as an int, otherwise type it the 10694 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 10695 // that X has type 'int', not 'unsigned'. 10696 10697 // Determine whether the value fits into an int. 10698 llvm::APSInt InitVal = ECD->getInitVal(); 10699 10700 // If it fits into an integer type, force it. Otherwise force it to match 10701 // the enum decl type. 10702 QualType NewTy; 10703 unsigned NewWidth; 10704 bool NewSign; 10705 if (!getLangOpts().CPlusPlus && 10706 !Enum->isFixed() && 10707 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 10708 NewTy = Context.IntTy; 10709 NewWidth = IntWidth; 10710 NewSign = true; 10711 } else if (ECD->getType() == BestType) { 10712 // Already the right type! 10713 if (getLangOpts().CPlusPlus) 10714 // C++ [dcl.enum]p4: Following the closing brace of an 10715 // enum-specifier, each enumerator has the type of its 10716 // enumeration. 10717 ECD->setType(EnumType); 10718 continue; 10719 } else { 10720 NewTy = BestType; 10721 NewWidth = BestWidth; 10722 NewSign = BestType->isSignedIntegerOrEnumerationType(); 10723 } 10724 10725 // Adjust the APSInt value. 10726 InitVal = InitVal.extOrTrunc(NewWidth); 10727 InitVal.setIsSigned(NewSign); 10728 ECD->setInitVal(InitVal); 10729 10730 // Adjust the Expr initializer and type. 10731 if (ECD->getInitExpr() && 10732 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 10733 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 10734 CK_IntegralCast, 10735 ECD->getInitExpr(), 10736 /*base paths*/ 0, 10737 VK_RValue)); 10738 if (getLangOpts().CPlusPlus) 10739 // C++ [dcl.enum]p4: Following the closing brace of an 10740 // enum-specifier, each enumerator has the type of its 10741 // enumeration. 10742 ECD->setType(EnumType); 10743 else 10744 ECD->setType(NewTy); 10745 } 10746 10747 Enum->completeDefinition(BestType, BestPromotionType, 10748 NumPositiveBits, NumNegativeBits); 10749 10750 // If we're declaring a function, ensure this decl isn't forgotten about - 10751 // it needs to go into the function scope. 10752 if (InFunctionDeclarator) 10753 DeclsInPrototypeScope.push_back(Enum); 10754 10755 CheckForUniqueEnumValues(*this, Elements, NumElements, Enum, EnumType); 10756 } 10757 10758 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 10759 SourceLocation StartLoc, 10760 SourceLocation EndLoc) { 10761 StringLiteral *AsmString = cast<StringLiteral>(expr); 10762 10763 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 10764 AsmString, StartLoc, 10765 EndLoc); 10766 CurContext->addDecl(New); 10767 return New; 10768 } 10769 10770 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 10771 SourceLocation ImportLoc, 10772 ModuleIdPath Path) { 10773 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 10774 Module::AllVisible, 10775 /*IsIncludeDirective=*/false); 10776 if (!Mod) 10777 return true; 10778 10779 llvm::SmallVector<SourceLocation, 2> IdentifierLocs; 10780 Module *ModCheck = Mod; 10781 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 10782 // If we've run out of module parents, just drop the remaining identifiers. 10783 // We need the length to be consistent. 10784 if (!ModCheck) 10785 break; 10786 ModCheck = ModCheck->Parent; 10787 10788 IdentifierLocs.push_back(Path[I].second); 10789 } 10790 10791 ImportDecl *Import = ImportDecl::Create(Context, 10792 Context.getTranslationUnitDecl(), 10793 AtLoc.isValid()? AtLoc : ImportLoc, 10794 Mod, IdentifierLocs); 10795 Context.getTranslationUnitDecl()->addDecl(Import); 10796 return Import; 10797 } 10798 10799 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 10800 IdentifierInfo* AliasName, 10801 SourceLocation PragmaLoc, 10802 SourceLocation NameLoc, 10803 SourceLocation AliasNameLoc) { 10804 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 10805 LookupOrdinaryName); 10806 AsmLabelAttr *Attr = 10807 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 10808 10809 if (PrevDecl) 10810 PrevDecl->addAttr(Attr); 10811 else 10812 (void)ExtnameUndeclaredIdentifiers.insert( 10813 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 10814 } 10815 10816 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 10817 SourceLocation PragmaLoc, 10818 SourceLocation NameLoc) { 10819 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 10820 10821 if (PrevDecl) { 10822 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 10823 } else { 10824 (void)WeakUndeclaredIdentifiers.insert( 10825 std::pair<IdentifierInfo*,WeakInfo> 10826 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 10827 } 10828 } 10829 10830 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 10831 IdentifierInfo* AliasName, 10832 SourceLocation PragmaLoc, 10833 SourceLocation NameLoc, 10834 SourceLocation AliasNameLoc) { 10835 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 10836 LookupOrdinaryName); 10837 WeakInfo W = WeakInfo(Name, NameLoc); 10838 10839 if (PrevDecl) { 10840 if (!PrevDecl->hasAttr<AliasAttr>()) 10841 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 10842 DeclApplyPragmaWeak(TUScope, ND, W); 10843 } else { 10844 (void)WeakUndeclaredIdentifiers.insert( 10845 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 10846 } 10847 } 10848 10849 Decl *Sema::getObjCDeclContext() const { 10850 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 10851 } 10852 10853 AvailabilityResult Sema::getCurContextAvailability() const { 10854 const Decl *D = cast<Decl>(getCurLexicalContext()); 10855 // A category implicitly has the availability of the interface. 10856 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 10857 D = CatD->getClassInterface(); 10858 10859 return D->getAvailability(); 10860 } 10861