SemaDecl.cpp revision cb8f951deacd251d9b3a73dc65f341477e039de1
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/APValue.h" 22#include "clang/AST/ASTConsumer.h" 23#include "clang/AST/ASTContext.h" 24#include "clang/AST/CXXInheritance.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/Triple.h" 44#include <algorithm> 45#include <cstring> 46#include <functional> 47using namespace clang; 48using namespace sema; 49 50Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 51 if (OwnedType) { 52 Decl *Group[2] = { OwnedType, Ptr }; 53 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 54 } 55 56 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 57} 58 59/// \brief If the identifier refers to a type name within this scope, 60/// return the declaration of that type. 61/// 62/// This routine performs ordinary name lookup of the identifier II 63/// within the given scope, with optional C++ scope specifier SS, to 64/// determine whether the name refers to a type. If so, returns an 65/// opaque pointer (actually a QualType) corresponding to that 66/// type. Otherwise, returns NULL. 67/// 68/// If name lookup results in an ambiguity, this routine will complain 69/// and then return NULL. 70ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 71 Scope *S, CXXScopeSpec *SS, 72 bool isClassName, bool HasTrailingDot, 73 ParsedType ObjectTypePtr, 74 bool WantNontrivialTypeSourceInfo, 75 IdentifierInfo **CorrectedII) { 76 // Determine where we will perform name lookup. 77 DeclContext *LookupCtx = 0; 78 if (ObjectTypePtr) { 79 QualType ObjectType = ObjectTypePtr.get(); 80 if (ObjectType->isRecordType()) 81 LookupCtx = computeDeclContext(ObjectType); 82 } else if (SS && SS->isNotEmpty()) { 83 LookupCtx = computeDeclContext(*SS, false); 84 85 if (!LookupCtx) { 86 if (isDependentScopeSpecifier(*SS)) { 87 // C++ [temp.res]p3: 88 // A qualified-id that refers to a type and in which the 89 // nested-name-specifier depends on a template-parameter (14.6.2) 90 // shall be prefixed by the keyword typename to indicate that the 91 // qualified-id denotes a type, forming an 92 // elaborated-type-specifier (7.1.5.3). 93 // 94 // We therefore do not perform any name lookup if the result would 95 // refer to a member of an unknown specialization. 96 if (!isClassName) 97 return ParsedType(); 98 99 // We know from the grammar that this name refers to a type, 100 // so build a dependent node to describe the type. 101 if (WantNontrivialTypeSourceInfo) 102 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 103 104 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 105 QualType T = 106 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 107 II, NameLoc); 108 109 return ParsedType::make(T); 110 } 111 112 return ParsedType(); 113 } 114 115 if (!LookupCtx->isDependentContext() && 116 RequireCompleteDeclContext(*SS, LookupCtx)) 117 return ParsedType(); 118 } 119 120 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 121 // lookup for class-names. 122 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 123 LookupOrdinaryName; 124 LookupResult Result(*this, &II, NameLoc, Kind); 125 if (LookupCtx) { 126 // Perform "qualified" name lookup into the declaration context we 127 // computed, which is either the type of the base of a member access 128 // expression or the declaration context associated with a prior 129 // nested-name-specifier. 130 LookupQualifiedName(Result, LookupCtx); 131 132 if (ObjectTypePtr && Result.empty()) { 133 // C++ [basic.lookup.classref]p3: 134 // If the unqualified-id is ~type-name, the type-name is looked up 135 // in the context of the entire postfix-expression. If the type T of 136 // the object expression is of a class type C, the type-name is also 137 // looked up in the scope of class C. At least one of the lookups shall 138 // find a name that refers to (possibly cv-qualified) T. 139 LookupName(Result, S); 140 } 141 } else { 142 // Perform unqualified name lookup. 143 LookupName(Result, S); 144 } 145 146 NamedDecl *IIDecl = 0; 147 switch (Result.getResultKind()) { 148 case LookupResult::NotFound: 149 case LookupResult::NotFoundInCurrentInstantiation: 150 if (CorrectedII) { 151 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 152 Kind, S, SS, 0, false, 153 Sema::CTC_Type); 154 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 155 TemplateTy Template; 156 bool MemberOfUnknownSpecialization; 157 UnqualifiedId TemplateName; 158 TemplateName.setIdentifier(NewII, NameLoc); 159 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 160 CXXScopeSpec NewSS, *NewSSPtr = SS; 161 if (SS && NNS) { 162 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 163 NewSSPtr = &NewSS; 164 } 165 if (Correction && (NNS || NewII != &II) && 166 // Ignore a correction to a template type as the to-be-corrected 167 // identifier is not a template (typo correction for template names 168 // is handled elsewhere). 169 !(getLangOptions().CPlusPlus && NewSSPtr && 170 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 171 false, Template, MemberOfUnknownSpecialization))) { 172 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 173 isClassName, HasTrailingDot, ObjectTypePtr, 174 WantNontrivialTypeSourceInfo); 175 if (Ty) { 176 std::string CorrectedStr(Correction.getAsString(getLangOptions())); 177 std::string CorrectedQuotedStr( 178 Correction.getQuoted(getLangOptions())); 179 Diag(NameLoc, diag::err_unknown_typename_suggest) 180 << Result.getLookupName() << CorrectedQuotedStr 181 << FixItHint::CreateReplacement(SourceRange(NameLoc), 182 CorrectedStr); 183 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl()) 184 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 185 << CorrectedQuotedStr; 186 187 if (SS && NNS) 188 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 189 *CorrectedII = NewII; 190 return Ty; 191 } 192 } 193 } 194 // If typo correction failed or was not performed, fall through 195 case LookupResult::FoundOverloaded: 196 case LookupResult::FoundUnresolvedValue: 197 Result.suppressDiagnostics(); 198 return ParsedType(); 199 200 case LookupResult::Ambiguous: 201 // Recover from type-hiding ambiguities by hiding the type. We'll 202 // do the lookup again when looking for an object, and we can 203 // diagnose the error then. If we don't do this, then the error 204 // about hiding the type will be immediately followed by an error 205 // that only makes sense if the identifier was treated like a type. 206 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 207 Result.suppressDiagnostics(); 208 return ParsedType(); 209 } 210 211 // Look to see if we have a type anywhere in the list of results. 212 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 213 Res != ResEnd; ++Res) { 214 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 215 if (!IIDecl || 216 (*Res)->getLocation().getRawEncoding() < 217 IIDecl->getLocation().getRawEncoding()) 218 IIDecl = *Res; 219 } 220 } 221 222 if (!IIDecl) { 223 // None of the entities we found is a type, so there is no way 224 // to even assume that the result is a type. In this case, don't 225 // complain about the ambiguity. The parser will either try to 226 // perform this lookup again (e.g., as an object name), which 227 // will produce the ambiguity, or will complain that it expected 228 // a type name. 229 Result.suppressDiagnostics(); 230 return ParsedType(); 231 } 232 233 // We found a type within the ambiguous lookup; diagnose the 234 // ambiguity and then return that type. This might be the right 235 // answer, or it might not be, but it suppresses any attempt to 236 // perform the name lookup again. 237 break; 238 239 case LookupResult::Found: 240 IIDecl = Result.getFoundDecl(); 241 break; 242 } 243 244 assert(IIDecl && "Didn't find decl"); 245 246 QualType T; 247 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 248 DiagnoseUseOfDecl(IIDecl, NameLoc); 249 250 if (T.isNull()) 251 T = Context.getTypeDeclType(TD); 252 253 if (SS && SS->isNotEmpty()) { 254 if (WantNontrivialTypeSourceInfo) { 255 // Construct a type with type-source information. 256 TypeLocBuilder Builder; 257 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 258 259 T = getElaboratedType(ETK_None, *SS, T); 260 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 261 ElabTL.setKeywordLoc(SourceLocation()); 262 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 263 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 264 } else { 265 T = getElaboratedType(ETK_None, *SS, T); 266 } 267 } 268 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 269 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 270 if (!HasTrailingDot) 271 T = Context.getObjCInterfaceType(IDecl); 272 } 273 274 if (T.isNull()) { 275 // If it's not plausibly a type, suppress diagnostics. 276 Result.suppressDiagnostics(); 277 return ParsedType(); 278 } 279 return ParsedType::make(T); 280} 281 282/// isTagName() - This method is called *for error recovery purposes only* 283/// to determine if the specified name is a valid tag name ("struct foo"). If 284/// so, this returns the TST for the tag corresponding to it (TST_enum, 285/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 286/// where the user forgot to specify the tag. 287DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 288 // Do a tag name lookup in this scope. 289 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 290 LookupName(R, S, false); 291 R.suppressDiagnostics(); 292 if (R.getResultKind() == LookupResult::Found) 293 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 294 switch (TD->getTagKind()) { 295 default: return DeclSpec::TST_unspecified; 296 case TTK_Struct: return DeclSpec::TST_struct; 297 case TTK_Union: return DeclSpec::TST_union; 298 case TTK_Class: return DeclSpec::TST_class; 299 case TTK_Enum: return DeclSpec::TST_enum; 300 } 301 } 302 303 return DeclSpec::TST_unspecified; 304} 305 306/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 307/// if a CXXScopeSpec's type is equal to the type of one of the base classes 308/// then downgrade the missing typename error to a warning. 309/// This is needed for MSVC compatibility; Example: 310/// @code 311/// template<class T> class A { 312/// public: 313/// typedef int TYPE; 314/// }; 315/// template<class T> class B : public A<T> { 316/// public: 317/// A<T>::TYPE a; // no typename required because A<T> is a base class. 318/// }; 319/// @endcode 320bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 321 if (CurContext->isRecord()) { 322 const Type *Ty = SS->getScopeRep()->getAsType(); 323 324 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 325 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 326 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 327 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 328 return true; 329 return S->isFunctionPrototypeScope(); 330 } 331 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 332} 333 334bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 335 SourceLocation IILoc, 336 Scope *S, 337 CXXScopeSpec *SS, 338 ParsedType &SuggestedType) { 339 // We don't have anything to suggest (yet). 340 SuggestedType = ParsedType(); 341 342 // There may have been a typo in the name of the type. Look up typo 343 // results, in case we have something that we can suggest. 344 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc), 345 LookupOrdinaryName, S, SS, NULL, 346 false, CTC_Type)) { 347 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 348 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 349 350 if (Corrected.isKeyword()) { 351 // We corrected to a keyword. 352 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it. 353 Diag(IILoc, diag::err_unknown_typename_suggest) 354 << &II << CorrectedQuotedStr; 355 return true; 356 } else { 357 NamedDecl *Result = Corrected.getCorrectionDecl(); 358 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) && 359 !Result->isInvalidDecl()) { 360 // We found a similarly-named type or interface; suggest that. 361 if (!SS || !SS->isSet()) 362 Diag(IILoc, diag::err_unknown_typename_suggest) 363 << &II << CorrectedQuotedStr 364 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 365 else if (DeclContext *DC = computeDeclContext(*SS, false)) 366 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 367 << &II << DC << CorrectedQuotedStr << SS->getRange() 368 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 369 else 370 llvm_unreachable("could not have corrected a typo here"); 371 372 Diag(Result->getLocation(), diag::note_previous_decl) 373 << CorrectedQuotedStr; 374 375 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 376 false, false, ParsedType(), 377 /*NonTrivialTypeSourceInfo=*/true); 378 return true; 379 } 380 } 381 } 382 383 if (getLangOptions().CPlusPlus) { 384 // See if II is a class template that the user forgot to pass arguments to. 385 UnqualifiedId Name; 386 Name.setIdentifier(&II, IILoc); 387 CXXScopeSpec EmptySS; 388 TemplateTy TemplateResult; 389 bool MemberOfUnknownSpecialization; 390 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 391 Name, ParsedType(), true, TemplateResult, 392 MemberOfUnknownSpecialization) == TNK_Type_template) { 393 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 394 Diag(IILoc, diag::err_template_missing_args) << TplName; 395 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 396 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 397 << TplDecl->getTemplateParameters()->getSourceRange(); 398 } 399 return true; 400 } 401 } 402 403 // FIXME: Should we move the logic that tries to recover from a missing tag 404 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 405 406 if (!SS || (!SS->isSet() && !SS->isInvalid())) 407 Diag(IILoc, diag::err_unknown_typename) << &II; 408 else if (DeclContext *DC = computeDeclContext(*SS, false)) 409 Diag(IILoc, diag::err_typename_nested_not_found) 410 << &II << DC << SS->getRange(); 411 else if (isDependentScopeSpecifier(*SS)) { 412 unsigned DiagID = diag::err_typename_missing; 413 if (getLangOptions().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 414 DiagID = diag::warn_typename_missing; 415 416 Diag(SS->getRange().getBegin(), DiagID) 417 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName() 418 << SourceRange(SS->getRange().getBegin(), IILoc) 419 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 420 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc) 421 .get(); 422 } else { 423 assert(SS && SS->isInvalid() && 424 "Invalid scope specifier has already been diagnosed"); 425 } 426 427 return true; 428} 429 430/// \brief Determine whether the given result set contains either a type name 431/// or 432static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 433 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus && 434 NextToken.is(tok::less); 435 436 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 437 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 438 return true; 439 440 if (CheckTemplate && isa<TemplateDecl>(*I)) 441 return true; 442 } 443 444 return false; 445} 446 447Sema::NameClassification Sema::ClassifyName(Scope *S, 448 CXXScopeSpec &SS, 449 IdentifierInfo *&Name, 450 SourceLocation NameLoc, 451 const Token &NextToken) { 452 DeclarationNameInfo NameInfo(Name, NameLoc); 453 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 454 455 if (NextToken.is(tok::coloncolon)) { 456 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 457 QualType(), false, SS, 0, false); 458 459 } 460 461 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 462 LookupParsedName(Result, S, &SS, !CurMethod); 463 464 // Perform lookup for Objective-C instance variables (including automatically 465 // synthesized instance variables), if we're in an Objective-C method. 466 // FIXME: This lookup really, really needs to be folded in to the normal 467 // unqualified lookup mechanism. 468 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 469 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 470 if (E.get() || E.isInvalid()) 471 return E; 472 } 473 474 bool SecondTry = false; 475 bool IsFilteredTemplateName = false; 476 477Corrected: 478 switch (Result.getResultKind()) { 479 case LookupResult::NotFound: 480 // If an unqualified-id is followed by a '(', then we have a function 481 // call. 482 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 483 // In C++, this is an ADL-only call. 484 // FIXME: Reference? 485 if (getLangOptions().CPlusPlus) 486 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 487 488 // C90 6.3.2.2: 489 // If the expression that precedes the parenthesized argument list in a 490 // function call consists solely of an identifier, and if no 491 // declaration is visible for this identifier, the identifier is 492 // implicitly declared exactly as if, in the innermost block containing 493 // the function call, the declaration 494 // 495 // extern int identifier (); 496 // 497 // appeared. 498 // 499 // We also allow this in C99 as an extension. 500 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 501 Result.addDecl(D); 502 Result.resolveKind(); 503 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 504 } 505 } 506 507 // In C, we first see whether there is a tag type by the same name, in 508 // which case it's likely that the user just forget to write "enum", 509 // "struct", or "union". 510 if (!getLangOptions().CPlusPlus && !SecondTry) { 511 Result.clear(LookupTagName); 512 LookupParsedName(Result, S, &SS); 513 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) { 514 const char *TagName = 0; 515 const char *FixItTagName = 0; 516 switch (Tag->getTagKind()) { 517 case TTK_Class: 518 TagName = "class"; 519 FixItTagName = "class "; 520 break; 521 522 case TTK_Enum: 523 TagName = "enum"; 524 FixItTagName = "enum "; 525 break; 526 527 case TTK_Struct: 528 TagName = "struct"; 529 FixItTagName = "struct "; 530 break; 531 532 case TTK_Union: 533 TagName = "union"; 534 FixItTagName = "union "; 535 break; 536 } 537 538 Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 539 << Name << TagName << getLangOptions().CPlusPlus 540 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 541 break; 542 } 543 544 Result.clear(LookupOrdinaryName); 545 } 546 547 // Perform typo correction to determine if there is another name that is 548 // close to this name. 549 if (!SecondTry) { 550 SecondTry = true; 551 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 552 Result.getLookupKind(), S, 553 &SS)) { 554 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 555 unsigned QualifiedDiag = diag::err_no_member_suggest; 556 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 557 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 558 559 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 560 NamedDecl *UnderlyingFirstDecl 561 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 562 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 563 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 564 UnqualifiedDiag = diag::err_no_template_suggest; 565 QualifiedDiag = diag::err_no_member_template_suggest; 566 } else if (UnderlyingFirstDecl && 567 (isa<TypeDecl>(UnderlyingFirstDecl) || 568 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 569 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 570 UnqualifiedDiag = diag::err_unknown_typename_suggest; 571 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 572 } 573 574 if (SS.isEmpty()) 575 Diag(NameLoc, UnqualifiedDiag) 576 << Name << CorrectedQuotedStr 577 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 578 else 579 Diag(NameLoc, QualifiedDiag) 580 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 581 << SS.getRange() 582 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 583 584 // Update the name, so that the caller has the new name. 585 Name = Corrected.getCorrectionAsIdentifierInfo(); 586 587 // Also update the LookupResult... 588 // FIXME: This should probably go away at some point 589 Result.clear(); 590 Result.setLookupName(Corrected.getCorrection()); 591 if (FirstDecl) Result.addDecl(FirstDecl); 592 593 // Typo correction corrected to a keyword. 594 if (Corrected.isKeyword()) 595 return Corrected.getCorrectionAsIdentifierInfo(); 596 597 if (FirstDecl) 598 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 599 << CorrectedQuotedStr; 600 601 // If we found an Objective-C instance variable, let 602 // LookupInObjCMethod build the appropriate expression to 603 // reference the ivar. 604 // FIXME: This is a gross hack. 605 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 606 Result.clear(); 607 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 608 return move(E); 609 } 610 611 goto Corrected; 612 } 613 } 614 615 // We failed to correct; just fall through and let the parser deal with it. 616 Result.suppressDiagnostics(); 617 return NameClassification::Unknown(); 618 619 case LookupResult::NotFoundInCurrentInstantiation: 620 // We performed name lookup into the current instantiation, and there were 621 // dependent bases, so we treat this result the same way as any other 622 // dependent nested-name-specifier. 623 624 // C++ [temp.res]p2: 625 // A name used in a template declaration or definition and that is 626 // dependent on a template-parameter is assumed not to name a type 627 // unless the applicable name lookup finds a type name or the name is 628 // qualified by the keyword typename. 629 // 630 // FIXME: If the next token is '<', we might want to ask the parser to 631 // perform some heroics to see if we actually have a 632 // template-argument-list, which would indicate a missing 'template' 633 // keyword here. 634 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0); 635 636 case LookupResult::Found: 637 case LookupResult::FoundOverloaded: 638 case LookupResult::FoundUnresolvedValue: 639 break; 640 641 case LookupResult::Ambiguous: 642 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 643 hasAnyAcceptableTemplateNames(Result)) { 644 // C++ [temp.local]p3: 645 // A lookup that finds an injected-class-name (10.2) can result in an 646 // ambiguity in certain cases (for example, if it is found in more than 647 // one base class). If all of the injected-class-names that are found 648 // refer to specializations of the same class template, and if the name 649 // is followed by a template-argument-list, the reference refers to the 650 // class template itself and not a specialization thereof, and is not 651 // ambiguous. 652 // 653 // This filtering can make an ambiguous result into an unambiguous one, 654 // so try again after filtering out template names. 655 FilterAcceptableTemplateNames(Result); 656 if (!Result.isAmbiguous()) { 657 IsFilteredTemplateName = true; 658 break; 659 } 660 } 661 662 // Diagnose the ambiguity and return an error. 663 return NameClassification::Error(); 664 } 665 666 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 667 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 668 // C++ [temp.names]p3: 669 // After name lookup (3.4) finds that a name is a template-name or that 670 // an operator-function-id or a literal- operator-id refers to a set of 671 // overloaded functions any member of which is a function template if 672 // this is followed by a <, the < is always taken as the delimiter of a 673 // template-argument-list and never as the less-than operator. 674 if (!IsFilteredTemplateName) 675 FilterAcceptableTemplateNames(Result); 676 677 if (!Result.empty()) { 678 bool IsFunctionTemplate; 679 TemplateName Template; 680 if (Result.end() - Result.begin() > 1) { 681 IsFunctionTemplate = true; 682 Template = Context.getOverloadedTemplateName(Result.begin(), 683 Result.end()); 684 } else { 685 TemplateDecl *TD 686 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 687 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 688 689 if (SS.isSet() && !SS.isInvalid()) 690 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 691 /*TemplateKeyword=*/false, 692 TD); 693 else 694 Template = TemplateName(TD); 695 } 696 697 if (IsFunctionTemplate) { 698 // Function templates always go through overload resolution, at which 699 // point we'll perform the various checks (e.g., accessibility) we need 700 // to based on which function we selected. 701 Result.suppressDiagnostics(); 702 703 return NameClassification::FunctionTemplate(Template); 704 } 705 706 return NameClassification::TypeTemplate(Template); 707 } 708 } 709 710 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 711 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 712 DiagnoseUseOfDecl(Type, NameLoc); 713 QualType T = Context.getTypeDeclType(Type); 714 return ParsedType::make(T); 715 } 716 717 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 718 if (!Class) { 719 // FIXME: It's unfortunate that we don't have a Type node for handling this. 720 if (ObjCCompatibleAliasDecl *Alias 721 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 722 Class = Alias->getClassInterface(); 723 } 724 725 if (Class) { 726 DiagnoseUseOfDecl(Class, NameLoc); 727 728 if (NextToken.is(tok::period)) { 729 // Interface. <something> is parsed as a property reference expression. 730 // Just return "unknown" as a fall-through for now. 731 Result.suppressDiagnostics(); 732 return NameClassification::Unknown(); 733 } 734 735 QualType T = Context.getObjCInterfaceType(Class); 736 return ParsedType::make(T); 737 } 738 739 if (!Result.empty() && (*Result.begin())->isCXXClassMember()) 740 return BuildPossibleImplicitMemberExpr(SS, Result, 0); 741 742 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 743 return BuildDeclarationNameExpr(SS, Result, ADL); 744} 745 746// Determines the context to return to after temporarily entering a 747// context. This depends in an unnecessarily complicated way on the 748// exact ordering of callbacks from the parser. 749DeclContext *Sema::getContainingDC(DeclContext *DC) { 750 751 // Functions defined inline within classes aren't parsed until we've 752 // finished parsing the top-level class, so the top-level class is 753 // the context we'll need to return to. 754 if (isa<FunctionDecl>(DC)) { 755 DC = DC->getLexicalParent(); 756 757 // A function not defined within a class will always return to its 758 // lexical context. 759 if (!isa<CXXRecordDecl>(DC)) 760 return DC; 761 762 // A C++ inline method/friend is parsed *after* the topmost class 763 // it was declared in is fully parsed ("complete"); the topmost 764 // class is the context we need to return to. 765 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 766 DC = RD; 767 768 // Return the declaration context of the topmost class the inline method is 769 // declared in. 770 return DC; 771 } 772 773 return DC->getLexicalParent(); 774} 775 776void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 777 assert(getContainingDC(DC) == CurContext && 778 "The next DeclContext should be lexically contained in the current one."); 779 CurContext = DC; 780 S->setEntity(DC); 781} 782 783void Sema::PopDeclContext() { 784 assert(CurContext && "DeclContext imbalance!"); 785 786 CurContext = getContainingDC(CurContext); 787 assert(CurContext && "Popped translation unit!"); 788} 789 790/// EnterDeclaratorContext - Used when we must lookup names in the context 791/// of a declarator's nested name specifier. 792/// 793void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 794 // C++0x [basic.lookup.unqual]p13: 795 // A name used in the definition of a static data member of class 796 // X (after the qualified-id of the static member) is looked up as 797 // if the name was used in a member function of X. 798 // C++0x [basic.lookup.unqual]p14: 799 // If a variable member of a namespace is defined outside of the 800 // scope of its namespace then any name used in the definition of 801 // the variable member (after the declarator-id) is looked up as 802 // if the definition of the variable member occurred in its 803 // namespace. 804 // Both of these imply that we should push a scope whose context 805 // is the semantic context of the declaration. We can't use 806 // PushDeclContext here because that context is not necessarily 807 // lexically contained in the current context. Fortunately, 808 // the containing scope should have the appropriate information. 809 810 assert(!S->getEntity() && "scope already has entity"); 811 812#ifndef NDEBUG 813 Scope *Ancestor = S->getParent(); 814 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 815 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 816#endif 817 818 CurContext = DC; 819 S->setEntity(DC); 820} 821 822void Sema::ExitDeclaratorContext(Scope *S) { 823 assert(S->getEntity() == CurContext && "Context imbalance!"); 824 825 // Switch back to the lexical context. The safety of this is 826 // enforced by an assert in EnterDeclaratorContext. 827 Scope *Ancestor = S->getParent(); 828 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 829 CurContext = (DeclContext*) Ancestor->getEntity(); 830 831 // We don't need to do anything with the scope, which is going to 832 // disappear. 833} 834 835 836void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 837 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 838 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 839 // We assume that the caller has already called 840 // ActOnReenterTemplateScope 841 FD = TFD->getTemplatedDecl(); 842 } 843 if (!FD) 844 return; 845 846 PushDeclContext(S, FD); 847 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 848 ParmVarDecl *Param = FD->getParamDecl(P); 849 // If the parameter has an identifier, then add it to the scope 850 if (Param->getIdentifier()) { 851 S->AddDecl(Param); 852 IdResolver.AddDecl(Param); 853 } 854 } 855} 856 857 858/// \brief Determine whether we allow overloading of the function 859/// PrevDecl with another declaration. 860/// 861/// This routine determines whether overloading is possible, not 862/// whether some new function is actually an overload. It will return 863/// true in C++ (where we can always provide overloads) or, as an 864/// extension, in C when the previous function is already an 865/// overloaded function declaration or has the "overloadable" 866/// attribute. 867static bool AllowOverloadingOfFunction(LookupResult &Previous, 868 ASTContext &Context) { 869 if (Context.getLangOptions().CPlusPlus) 870 return true; 871 872 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 873 return true; 874 875 return (Previous.getResultKind() == LookupResult::Found 876 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 877} 878 879/// Add this decl to the scope shadowed decl chains. 880void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 881 // Move up the scope chain until we find the nearest enclosing 882 // non-transparent context. The declaration will be introduced into this 883 // scope. 884 while (S->getEntity() && 885 ((DeclContext *)S->getEntity())->isTransparentContext()) 886 S = S->getParent(); 887 888 // Add scoped declarations into their context, so that they can be 889 // found later. Declarations without a context won't be inserted 890 // into any context. 891 if (AddToContext) 892 CurContext->addDecl(D); 893 894 // Out-of-line definitions shouldn't be pushed into scope in C++. 895 // Out-of-line variable and function definitions shouldn't even in C. 896 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 897 D->isOutOfLine() && 898 !D->getDeclContext()->getRedeclContext()->Equals( 899 D->getLexicalDeclContext()->getRedeclContext())) 900 return; 901 902 // Template instantiations should also not be pushed into scope. 903 if (isa<FunctionDecl>(D) && 904 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 905 return; 906 907 // If this replaces anything in the current scope, 908 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 909 IEnd = IdResolver.end(); 910 for (; I != IEnd; ++I) { 911 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 912 S->RemoveDecl(*I); 913 IdResolver.RemoveDecl(*I); 914 915 // Should only need to replace one decl. 916 break; 917 } 918 } 919 920 S->AddDecl(D); 921 922 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 923 // Implicitly-generated labels may end up getting generated in an order that 924 // isn't strictly lexical, which breaks name lookup. Be careful to insert 925 // the label at the appropriate place in the identifier chain. 926 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 927 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 928 if (IDC == CurContext) { 929 if (!S->isDeclScope(*I)) 930 continue; 931 } else if (IDC->Encloses(CurContext)) 932 break; 933 } 934 935 IdResolver.InsertDeclAfter(I, D); 936 } else { 937 IdResolver.AddDecl(D); 938 } 939} 940 941bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 942 bool ExplicitInstantiationOrSpecialization) { 943 return IdResolver.isDeclInScope(D, Ctx, Context, S, 944 ExplicitInstantiationOrSpecialization); 945} 946 947Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 948 DeclContext *TargetDC = DC->getPrimaryContext(); 949 do { 950 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 951 if (ScopeDC->getPrimaryContext() == TargetDC) 952 return S; 953 } while ((S = S->getParent())); 954 955 return 0; 956} 957 958static bool isOutOfScopePreviousDeclaration(NamedDecl *, 959 DeclContext*, 960 ASTContext&); 961 962/// Filters out lookup results that don't fall within the given scope 963/// as determined by isDeclInScope. 964void Sema::FilterLookupForScope(LookupResult &R, 965 DeclContext *Ctx, Scope *S, 966 bool ConsiderLinkage, 967 bool ExplicitInstantiationOrSpecialization) { 968 LookupResult::Filter F = R.makeFilter(); 969 while (F.hasNext()) { 970 NamedDecl *D = F.next(); 971 972 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 973 continue; 974 975 if (ConsiderLinkage && 976 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 977 continue; 978 979 F.erase(); 980 } 981 982 F.done(); 983} 984 985static bool isUsingDecl(NamedDecl *D) { 986 return isa<UsingShadowDecl>(D) || 987 isa<UnresolvedUsingTypenameDecl>(D) || 988 isa<UnresolvedUsingValueDecl>(D); 989} 990 991/// Removes using shadow declarations from the lookup results. 992static void RemoveUsingDecls(LookupResult &R) { 993 LookupResult::Filter F = R.makeFilter(); 994 while (F.hasNext()) 995 if (isUsingDecl(F.next())) 996 F.erase(); 997 998 F.done(); 999} 1000 1001/// \brief Check for this common pattern: 1002/// @code 1003/// class S { 1004/// S(const S&); // DO NOT IMPLEMENT 1005/// void operator=(const S&); // DO NOT IMPLEMENT 1006/// }; 1007/// @endcode 1008static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1009 // FIXME: Should check for private access too but access is set after we get 1010 // the decl here. 1011 if (D->doesThisDeclarationHaveABody()) 1012 return false; 1013 1014 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1015 return CD->isCopyConstructor(); 1016 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1017 return Method->isCopyAssignmentOperator(); 1018 return false; 1019} 1020 1021bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1022 assert(D); 1023 1024 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1025 return false; 1026 1027 // Ignore class templates. 1028 if (D->getDeclContext()->isDependentContext() || 1029 D->getLexicalDeclContext()->isDependentContext()) 1030 return false; 1031 1032 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1033 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1034 return false; 1035 1036 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1037 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1038 return false; 1039 } else { 1040 // 'static inline' functions are used in headers; don't warn. 1041 if (FD->getStorageClass() == SC_Static && 1042 FD->isInlineSpecified()) 1043 return false; 1044 } 1045 1046 if (FD->doesThisDeclarationHaveABody() && 1047 Context.DeclMustBeEmitted(FD)) 1048 return false; 1049 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1050 if (!VD->isFileVarDecl() || 1051 VD->getType().isConstant(Context) || 1052 Context.DeclMustBeEmitted(VD)) 1053 return false; 1054 1055 if (VD->isStaticDataMember() && 1056 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1057 return false; 1058 1059 } else { 1060 return false; 1061 } 1062 1063 // Only warn for unused decls internal to the translation unit. 1064 if (D->getLinkage() == ExternalLinkage) 1065 return false; 1066 1067 return true; 1068} 1069 1070void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1071 if (!D) 1072 return; 1073 1074 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1075 const FunctionDecl *First = FD->getFirstDeclaration(); 1076 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1077 return; // First should already be in the vector. 1078 } 1079 1080 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1081 const VarDecl *First = VD->getFirstDeclaration(); 1082 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1083 return; // First should already be in the vector. 1084 } 1085 1086 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1087 UnusedFileScopedDecls.push_back(D); 1088 } 1089 1090static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1091 if (D->isInvalidDecl()) 1092 return false; 1093 1094 if (D->isUsed() || D->hasAttr<UnusedAttr>()) 1095 return false; 1096 1097 if (isa<LabelDecl>(D)) 1098 return true; 1099 1100 // White-list anything that isn't a local variable. 1101 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1102 !D->getDeclContext()->isFunctionOrMethod()) 1103 return false; 1104 1105 // Types of valid local variables should be complete, so this should succeed. 1106 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1107 1108 // White-list anything with an __attribute__((unused)) type. 1109 QualType Ty = VD->getType(); 1110 1111 // Only look at the outermost level of typedef. 1112 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 1113 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1114 return false; 1115 } 1116 1117 // If we failed to complete the type for some reason, or if the type is 1118 // dependent, don't diagnose the variable. 1119 if (Ty->isIncompleteType() || Ty->isDependentType()) 1120 return false; 1121 1122 if (const TagType *TT = Ty->getAs<TagType>()) { 1123 const TagDecl *Tag = TT->getDecl(); 1124 if (Tag->hasAttr<UnusedAttr>()) 1125 return false; 1126 1127 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1128 // FIXME: Checking for the presence of a user-declared constructor 1129 // isn't completely accurate; we'd prefer to check that the initializer 1130 // has no side effects. 1131 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor()) 1132 return false; 1133 } 1134 } 1135 1136 // TODO: __attribute__((unused)) templates? 1137 } 1138 1139 return true; 1140} 1141 1142static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1143 FixItHint &Hint) { 1144 if (isa<LabelDecl>(D)) { 1145 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1146 tok::colon, Ctx.getSourceManager(), Ctx.getLangOptions(), true); 1147 if (AfterColon.isInvalid()) 1148 return; 1149 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1150 getCharRange(D->getLocStart(), AfterColon)); 1151 } 1152 return; 1153} 1154 1155/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1156/// unless they are marked attr(unused). 1157void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1158 FixItHint Hint; 1159 if (!ShouldDiagnoseUnusedDecl(D)) 1160 return; 1161 1162 GenerateFixForUnusedDecl(D, Context, Hint); 1163 1164 unsigned DiagID; 1165 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1166 DiagID = diag::warn_unused_exception_param; 1167 else if (isa<LabelDecl>(D)) 1168 DiagID = diag::warn_unused_label; 1169 else 1170 DiagID = diag::warn_unused_variable; 1171 1172 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1173} 1174 1175static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1176 // Verify that we have no forward references left. If so, there was a goto 1177 // or address of a label taken, but no definition of it. Label fwd 1178 // definitions are indicated with a null substmt. 1179 if (L->getStmt() == 0) 1180 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1181} 1182 1183void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1184 if (S->decl_empty()) return; 1185 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1186 "Scope shouldn't contain decls!"); 1187 1188 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1189 I != E; ++I) { 1190 Decl *TmpD = (*I); 1191 assert(TmpD && "This decl didn't get pushed??"); 1192 1193 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1194 NamedDecl *D = cast<NamedDecl>(TmpD); 1195 1196 if (!D->getDeclName()) continue; 1197 1198 // Diagnose unused variables in this scope. 1199 if (!S->hasErrorOccurred()) 1200 DiagnoseUnusedDecl(D); 1201 1202 // If this was a forward reference to a label, verify it was defined. 1203 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1204 CheckPoppedLabel(LD, *this); 1205 1206 // Remove this name from our lexical scope. 1207 IdResolver.RemoveDecl(D); 1208 } 1209} 1210 1211/// \brief Look for an Objective-C class in the translation unit. 1212/// 1213/// \param Id The name of the Objective-C class we're looking for. If 1214/// typo-correction fixes this name, the Id will be updated 1215/// to the fixed name. 1216/// 1217/// \param IdLoc The location of the name in the translation unit. 1218/// 1219/// \param TypoCorrection If true, this routine will attempt typo correction 1220/// if there is no class with the given name. 1221/// 1222/// \returns The declaration of the named Objective-C class, or NULL if the 1223/// class could not be found. 1224ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1225 SourceLocation IdLoc, 1226 bool DoTypoCorrection) { 1227 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1228 // creation from this context. 1229 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1230 1231 if (!IDecl && DoTypoCorrection) { 1232 // Perform typo correction at the given location, but only if we 1233 // find an Objective-C class name. 1234 TypoCorrection C; 1235 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1236 TUScope, NULL, NULL, false, CTC_NoKeywords)) && 1237 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) { 1238 Diag(IdLoc, diag::err_undef_interface_suggest) 1239 << Id << IDecl->getDeclName() 1240 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1241 Diag(IDecl->getLocation(), diag::note_previous_decl) 1242 << IDecl->getDeclName(); 1243 1244 Id = IDecl->getIdentifier(); 1245 } 1246 } 1247 1248 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1249} 1250 1251/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1252/// from S, where a non-field would be declared. This routine copes 1253/// with the difference between C and C++ scoping rules in structs and 1254/// unions. For example, the following code is well-formed in C but 1255/// ill-formed in C++: 1256/// @code 1257/// struct S6 { 1258/// enum { BAR } e; 1259/// }; 1260/// 1261/// void test_S6() { 1262/// struct S6 a; 1263/// a.e = BAR; 1264/// } 1265/// @endcode 1266/// For the declaration of BAR, this routine will return a different 1267/// scope. The scope S will be the scope of the unnamed enumeration 1268/// within S6. In C++, this routine will return the scope associated 1269/// with S6, because the enumeration's scope is a transparent 1270/// context but structures can contain non-field names. In C, this 1271/// routine will return the translation unit scope, since the 1272/// enumeration's scope is a transparent context and structures cannot 1273/// contain non-field names. 1274Scope *Sema::getNonFieldDeclScope(Scope *S) { 1275 while (((S->getFlags() & Scope::DeclScope) == 0) || 1276 (S->getEntity() && 1277 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1278 (S->isClassScope() && !getLangOptions().CPlusPlus)) 1279 S = S->getParent(); 1280 return S; 1281} 1282 1283/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1284/// file scope. lazily create a decl for it. ForRedeclaration is true 1285/// if we're creating this built-in in anticipation of redeclaring the 1286/// built-in. 1287NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1288 Scope *S, bool ForRedeclaration, 1289 SourceLocation Loc) { 1290 Builtin::ID BID = (Builtin::ID)bid; 1291 1292 ASTContext::GetBuiltinTypeError Error; 1293 QualType R = Context.GetBuiltinType(BID, Error); 1294 switch (Error) { 1295 case ASTContext::GE_None: 1296 // Okay 1297 break; 1298 1299 case ASTContext::GE_Missing_stdio: 1300 if (ForRedeclaration) 1301 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1302 << Context.BuiltinInfo.GetName(BID); 1303 return 0; 1304 1305 case ASTContext::GE_Missing_setjmp: 1306 if (ForRedeclaration) 1307 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1308 << Context.BuiltinInfo.GetName(BID); 1309 return 0; 1310 } 1311 1312 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1313 Diag(Loc, diag::ext_implicit_lib_function_decl) 1314 << Context.BuiltinInfo.GetName(BID) 1315 << R; 1316 if (Context.BuiltinInfo.getHeaderName(BID) && 1317 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1318 != DiagnosticsEngine::Ignored) 1319 Diag(Loc, diag::note_please_include_header) 1320 << Context.BuiltinInfo.getHeaderName(BID) 1321 << Context.BuiltinInfo.GetName(BID); 1322 } 1323 1324 FunctionDecl *New = FunctionDecl::Create(Context, 1325 Context.getTranslationUnitDecl(), 1326 Loc, Loc, II, R, /*TInfo=*/0, 1327 SC_Extern, 1328 SC_None, false, 1329 /*hasPrototype=*/true); 1330 New->setImplicit(); 1331 1332 // Create Decl objects for each parameter, adding them to the 1333 // FunctionDecl. 1334 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1335 SmallVector<ParmVarDecl*, 16> Params; 1336 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1337 ParmVarDecl *parm = 1338 ParmVarDecl::Create(Context, New, SourceLocation(), 1339 SourceLocation(), 0, 1340 FT->getArgType(i), /*TInfo=*/0, 1341 SC_None, SC_None, 0); 1342 parm->setScopeInfo(0, i); 1343 Params.push_back(parm); 1344 } 1345 New->setParams(Params); 1346 } 1347 1348 AddKnownFunctionAttributes(New); 1349 1350 // TUScope is the translation-unit scope to insert this function into. 1351 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1352 // relate Scopes to DeclContexts, and probably eliminate CurContext 1353 // entirely, but we're not there yet. 1354 DeclContext *SavedContext = CurContext; 1355 CurContext = Context.getTranslationUnitDecl(); 1356 PushOnScopeChains(New, TUScope); 1357 CurContext = SavedContext; 1358 return New; 1359} 1360 1361/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1362/// same name and scope as a previous declaration 'Old'. Figure out 1363/// how to resolve this situation, merging decls or emitting 1364/// diagnostics as appropriate. If there was an error, set New to be invalid. 1365/// 1366void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1367 // If the new decl is known invalid already, don't bother doing any 1368 // merging checks. 1369 if (New->isInvalidDecl()) return; 1370 1371 // Allow multiple definitions for ObjC built-in typedefs. 1372 // FIXME: Verify the underlying types are equivalent! 1373 if (getLangOptions().ObjC1) { 1374 const IdentifierInfo *TypeID = New->getIdentifier(); 1375 switch (TypeID->getLength()) { 1376 default: break; 1377 case 2: 1378 if (!TypeID->isStr("id")) 1379 break; 1380 Context.setObjCIdRedefinitionType(New->getUnderlyingType()); 1381 // Install the built-in type for 'id', ignoring the current definition. 1382 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1383 return; 1384 case 5: 1385 if (!TypeID->isStr("Class")) 1386 break; 1387 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1388 // Install the built-in type for 'Class', ignoring the current definition. 1389 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1390 return; 1391 case 3: 1392 if (!TypeID->isStr("SEL")) 1393 break; 1394 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1395 // Install the built-in type for 'SEL', ignoring the current definition. 1396 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1397 return; 1398 } 1399 // Fall through - the typedef name was not a builtin type. 1400 } 1401 1402 // Verify the old decl was also a type. 1403 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1404 if (!Old) { 1405 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1406 << New->getDeclName(); 1407 1408 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1409 if (OldD->getLocation().isValid()) 1410 Diag(OldD->getLocation(), diag::note_previous_definition); 1411 1412 return New->setInvalidDecl(); 1413 } 1414 1415 // If the old declaration is invalid, just give up here. 1416 if (Old->isInvalidDecl()) 1417 return New->setInvalidDecl(); 1418 1419 // Determine the "old" type we'll use for checking and diagnostics. 1420 QualType OldType; 1421 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1422 OldType = OldTypedef->getUnderlyingType(); 1423 else 1424 OldType = Context.getTypeDeclType(Old); 1425 1426 // If the typedef types are not identical, reject them in all languages and 1427 // with any extensions enabled. 1428 1429 if (OldType != New->getUnderlyingType() && 1430 Context.getCanonicalType(OldType) != 1431 Context.getCanonicalType(New->getUnderlyingType())) { 1432 int Kind = 0; 1433 if (isa<TypeAliasDecl>(Old)) 1434 Kind = 1; 1435 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1436 << Kind << New->getUnderlyingType() << OldType; 1437 if (Old->getLocation().isValid()) 1438 Diag(Old->getLocation(), diag::note_previous_definition); 1439 return New->setInvalidDecl(); 1440 } 1441 1442 // The types match. Link up the redeclaration chain if the old 1443 // declaration was a typedef. 1444 // FIXME: this is a potential source of weirdness if the type 1445 // spellings don't match exactly. 1446 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1447 New->setPreviousDeclaration(Typedef); 1448 1449 // __module_private__ is propagated to later declarations. 1450 if (Old->isModulePrivate()) 1451 New->setModulePrivate(); 1452 else if (New->isModulePrivate()) 1453 diagnoseModulePrivateRedeclaration(New, Old); 1454 1455 if (getLangOptions().MicrosoftExt) 1456 return; 1457 1458 if (getLangOptions().CPlusPlus) { 1459 // C++ [dcl.typedef]p2: 1460 // In a given non-class scope, a typedef specifier can be used to 1461 // redefine the name of any type declared in that scope to refer 1462 // to the type to which it already refers. 1463 if (!isa<CXXRecordDecl>(CurContext)) 1464 return; 1465 1466 // C++0x [dcl.typedef]p4: 1467 // In a given class scope, a typedef specifier can be used to redefine 1468 // any class-name declared in that scope that is not also a typedef-name 1469 // to refer to the type to which it already refers. 1470 // 1471 // This wording came in via DR424, which was a correction to the 1472 // wording in DR56, which accidentally banned code like: 1473 // 1474 // struct S { 1475 // typedef struct A { } A; 1476 // }; 1477 // 1478 // in the C++03 standard. We implement the C++0x semantics, which 1479 // allow the above but disallow 1480 // 1481 // struct S { 1482 // typedef int I; 1483 // typedef int I; 1484 // }; 1485 // 1486 // since that was the intent of DR56. 1487 if (!isa<TypedefNameDecl>(Old)) 1488 return; 1489 1490 Diag(New->getLocation(), diag::err_redefinition) 1491 << New->getDeclName(); 1492 Diag(Old->getLocation(), diag::note_previous_definition); 1493 return New->setInvalidDecl(); 1494 } 1495 1496 // If we have a redefinition of a typedef in C, emit a warning. This warning 1497 // is normally mapped to an error, but can be controlled with 1498 // -Wtypedef-redefinition. If either the original or the redefinition is 1499 // in a system header, don't emit this for compatibility with GCC. 1500 if (getDiagnostics().getSuppressSystemWarnings() && 1501 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1502 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1503 return; 1504 1505 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1506 << New->getDeclName(); 1507 Diag(Old->getLocation(), diag::note_previous_definition); 1508 return; 1509} 1510 1511/// DeclhasAttr - returns true if decl Declaration already has the target 1512/// attribute. 1513static bool 1514DeclHasAttr(const Decl *D, const Attr *A) { 1515 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1516 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1517 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1518 if ((*i)->getKind() == A->getKind()) { 1519 if (Ann) { 1520 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1521 return true; 1522 continue; 1523 } 1524 // FIXME: Don't hardcode this check 1525 if (OA && isa<OwnershipAttr>(*i)) 1526 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1527 return true; 1528 } 1529 1530 return false; 1531} 1532 1533/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 1534static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl, 1535 ASTContext &C, bool mergeDeprecation = true) { 1536 if (!oldDecl->hasAttrs()) 1537 return; 1538 1539 bool foundAny = newDecl->hasAttrs(); 1540 1541 // Ensure that any moving of objects within the allocated map is done before 1542 // we process them. 1543 if (!foundAny) newDecl->setAttrs(AttrVec()); 1544 1545 for (specific_attr_iterator<InheritableAttr> 1546 i = oldDecl->specific_attr_begin<InheritableAttr>(), 1547 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) { 1548 // Ignore deprecated/unavailable/availability attributes if requested. 1549 if (!mergeDeprecation && 1550 (isa<DeprecatedAttr>(*i) || 1551 isa<UnavailableAttr>(*i) || 1552 isa<AvailabilityAttr>(*i))) 1553 continue; 1554 1555 if (!DeclHasAttr(newDecl, *i)) { 1556 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C)); 1557 newAttr->setInherited(true); 1558 newDecl->addAttr(newAttr); 1559 foundAny = true; 1560 } 1561 } 1562 1563 if (!foundAny) newDecl->dropAttrs(); 1564} 1565 1566/// mergeParamDeclAttributes - Copy attributes from the old parameter 1567/// to the new one. 1568static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 1569 const ParmVarDecl *oldDecl, 1570 ASTContext &C) { 1571 if (!oldDecl->hasAttrs()) 1572 return; 1573 1574 bool foundAny = newDecl->hasAttrs(); 1575 1576 // Ensure that any moving of objects within the allocated map is 1577 // done before we process them. 1578 if (!foundAny) newDecl->setAttrs(AttrVec()); 1579 1580 for (specific_attr_iterator<InheritableParamAttr> 1581 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 1582 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 1583 if (!DeclHasAttr(newDecl, *i)) { 1584 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 1585 newAttr->setInherited(true); 1586 newDecl->addAttr(newAttr); 1587 foundAny = true; 1588 } 1589 } 1590 1591 if (!foundAny) newDecl->dropAttrs(); 1592} 1593 1594namespace { 1595 1596/// Used in MergeFunctionDecl to keep track of function parameters in 1597/// C. 1598struct GNUCompatibleParamWarning { 1599 ParmVarDecl *OldParm; 1600 ParmVarDecl *NewParm; 1601 QualType PromotedType; 1602}; 1603 1604} 1605 1606/// getSpecialMember - get the special member enum for a method. 1607Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1608 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1609 if (Ctor->isDefaultConstructor()) 1610 return Sema::CXXDefaultConstructor; 1611 1612 if (Ctor->isCopyConstructor()) 1613 return Sema::CXXCopyConstructor; 1614 1615 if (Ctor->isMoveConstructor()) 1616 return Sema::CXXMoveConstructor; 1617 } else if (isa<CXXDestructorDecl>(MD)) { 1618 return Sema::CXXDestructor; 1619 } else if (MD->isCopyAssignmentOperator()) { 1620 return Sema::CXXCopyAssignment; 1621 } else if (MD->isMoveAssignmentOperator()) { 1622 return Sema::CXXMoveAssignment; 1623 } 1624 1625 return Sema::CXXInvalid; 1626} 1627 1628/// canRedefineFunction - checks if a function can be redefined. Currently, 1629/// only extern inline functions can be redefined, and even then only in 1630/// GNU89 mode. 1631static bool canRedefineFunction(const FunctionDecl *FD, 1632 const LangOptions& LangOpts) { 1633 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 1634 !LangOpts.CPlusPlus && 1635 FD->isInlineSpecified() && 1636 FD->getStorageClass() == SC_Extern); 1637} 1638 1639/// MergeFunctionDecl - We just parsed a function 'New' from 1640/// declarator D which has the same name and scope as a previous 1641/// declaration 'Old'. Figure out how to resolve this situation, 1642/// merging decls or emitting diagnostics as appropriate. 1643/// 1644/// In C++, New and Old must be declarations that are not 1645/// overloaded. Use IsOverload to determine whether New and Old are 1646/// overloaded, and to select the Old declaration that New should be 1647/// merged with. 1648/// 1649/// Returns true if there was an error, false otherwise. 1650bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 1651 // Verify the old decl was also a function. 1652 FunctionDecl *Old = 0; 1653 if (FunctionTemplateDecl *OldFunctionTemplate 1654 = dyn_cast<FunctionTemplateDecl>(OldD)) 1655 Old = OldFunctionTemplate->getTemplatedDecl(); 1656 else 1657 Old = dyn_cast<FunctionDecl>(OldD); 1658 if (!Old) { 1659 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 1660 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 1661 Diag(Shadow->getTargetDecl()->getLocation(), 1662 diag::note_using_decl_target); 1663 Diag(Shadow->getUsingDecl()->getLocation(), 1664 diag::note_using_decl) << 0; 1665 return true; 1666 } 1667 1668 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1669 << New->getDeclName(); 1670 Diag(OldD->getLocation(), diag::note_previous_definition); 1671 return true; 1672 } 1673 1674 // Determine whether the previous declaration was a definition, 1675 // implicit declaration, or a declaration. 1676 diag::kind PrevDiag; 1677 if (Old->isThisDeclarationADefinition()) 1678 PrevDiag = diag::note_previous_definition; 1679 else if (Old->isImplicit()) 1680 PrevDiag = diag::note_previous_implicit_declaration; 1681 else 1682 PrevDiag = diag::note_previous_declaration; 1683 1684 QualType OldQType = Context.getCanonicalType(Old->getType()); 1685 QualType NewQType = Context.getCanonicalType(New->getType()); 1686 1687 // Don't complain about this if we're in GNU89 mode and the old function 1688 // is an extern inline function. 1689 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 1690 New->getStorageClass() == SC_Static && 1691 Old->getStorageClass() != SC_Static && 1692 !canRedefineFunction(Old, getLangOptions())) { 1693 if (getLangOptions().MicrosoftExt) { 1694 Diag(New->getLocation(), diag::warn_static_non_static) << New; 1695 Diag(Old->getLocation(), PrevDiag); 1696 } else { 1697 Diag(New->getLocation(), diag::err_static_non_static) << New; 1698 Diag(Old->getLocation(), PrevDiag); 1699 return true; 1700 } 1701 } 1702 1703 // If a function is first declared with a calling convention, but is 1704 // later declared or defined without one, the second decl assumes the 1705 // calling convention of the first. 1706 // 1707 // For the new decl, we have to look at the NON-canonical type to tell the 1708 // difference between a function that really doesn't have a calling 1709 // convention and one that is declared cdecl. That's because in 1710 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 1711 // because it is the default calling convention. 1712 // 1713 // Note also that we DO NOT return at this point, because we still have 1714 // other tests to run. 1715 const FunctionType *OldType = cast<FunctionType>(OldQType); 1716 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 1717 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 1718 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 1719 bool RequiresAdjustment = false; 1720 if (OldTypeInfo.getCC() != CC_Default && 1721 NewTypeInfo.getCC() == CC_Default) { 1722 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 1723 RequiresAdjustment = true; 1724 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 1725 NewTypeInfo.getCC())) { 1726 // Calling conventions really aren't compatible, so complain. 1727 Diag(New->getLocation(), diag::err_cconv_change) 1728 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 1729 << (OldTypeInfo.getCC() == CC_Default) 1730 << (OldTypeInfo.getCC() == CC_Default ? "" : 1731 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 1732 Diag(Old->getLocation(), diag::note_previous_declaration); 1733 return true; 1734 } 1735 1736 // FIXME: diagnose the other way around? 1737 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 1738 NewTypeInfo = NewTypeInfo.withNoReturn(true); 1739 RequiresAdjustment = true; 1740 } 1741 1742 // Merge regparm attribute. 1743 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 1744 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 1745 if (NewTypeInfo.getHasRegParm()) { 1746 Diag(New->getLocation(), diag::err_regparm_mismatch) 1747 << NewType->getRegParmType() 1748 << OldType->getRegParmType(); 1749 Diag(Old->getLocation(), diag::note_previous_declaration); 1750 return true; 1751 } 1752 1753 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 1754 RequiresAdjustment = true; 1755 } 1756 1757 // Merge ns_returns_retained attribute. 1758 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 1759 if (NewTypeInfo.getProducesResult()) { 1760 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 1761 Diag(Old->getLocation(), diag::note_previous_declaration); 1762 return true; 1763 } 1764 1765 NewTypeInfo = NewTypeInfo.withProducesResult(true); 1766 RequiresAdjustment = true; 1767 } 1768 1769 if (RequiresAdjustment) { 1770 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 1771 New->setType(QualType(NewType, 0)); 1772 NewQType = Context.getCanonicalType(New->getType()); 1773 } 1774 1775 if (getLangOptions().CPlusPlus) { 1776 // (C++98 13.1p2): 1777 // Certain function declarations cannot be overloaded: 1778 // -- Function declarations that differ only in the return type 1779 // cannot be overloaded. 1780 QualType OldReturnType = OldType->getResultType(); 1781 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 1782 QualType ResQT; 1783 if (OldReturnType != NewReturnType) { 1784 if (NewReturnType->isObjCObjectPointerType() 1785 && OldReturnType->isObjCObjectPointerType()) 1786 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 1787 if (ResQT.isNull()) { 1788 if (New->isCXXClassMember() && New->isOutOfLine()) 1789 Diag(New->getLocation(), 1790 diag::err_member_def_does_not_match_ret_type) << New; 1791 else 1792 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 1793 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1794 return true; 1795 } 1796 else 1797 NewQType = ResQT; 1798 } 1799 1800 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 1801 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 1802 if (OldMethod && NewMethod) { 1803 // Preserve triviality. 1804 NewMethod->setTrivial(OldMethod->isTrivial()); 1805 1806 // MSVC allows explicit template specialization at class scope: 1807 // 2 CXMethodDecls referring to the same function will be injected. 1808 // We don't want a redeclartion error. 1809 bool IsClassScopeExplicitSpecialization = 1810 OldMethod->isFunctionTemplateSpecialization() && 1811 NewMethod->isFunctionTemplateSpecialization(); 1812 bool isFriend = NewMethod->getFriendObjectKind(); 1813 1814 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 1815 !IsClassScopeExplicitSpecialization) { 1816 // -- Member function declarations with the same name and the 1817 // same parameter types cannot be overloaded if any of them 1818 // is a static member function declaration. 1819 if (OldMethod->isStatic() || NewMethod->isStatic()) { 1820 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 1821 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1822 return true; 1823 } 1824 1825 // C++ [class.mem]p1: 1826 // [...] A member shall not be declared twice in the 1827 // member-specification, except that a nested class or member 1828 // class template can be declared and then later defined. 1829 unsigned NewDiag; 1830 if (isa<CXXConstructorDecl>(OldMethod)) 1831 NewDiag = diag::err_constructor_redeclared; 1832 else if (isa<CXXDestructorDecl>(NewMethod)) 1833 NewDiag = diag::err_destructor_redeclared; 1834 else if (isa<CXXConversionDecl>(NewMethod)) 1835 NewDiag = diag::err_conv_function_redeclared; 1836 else 1837 NewDiag = diag::err_member_redeclared; 1838 1839 Diag(New->getLocation(), NewDiag); 1840 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1841 1842 // Complain if this is an explicit declaration of a special 1843 // member that was initially declared implicitly. 1844 // 1845 // As an exception, it's okay to befriend such methods in order 1846 // to permit the implicit constructor/destructor/operator calls. 1847 } else if (OldMethod->isImplicit()) { 1848 if (isFriend) { 1849 NewMethod->setImplicit(); 1850 } else { 1851 Diag(NewMethod->getLocation(), 1852 diag::err_definition_of_implicitly_declared_member) 1853 << New << getSpecialMember(OldMethod); 1854 return true; 1855 } 1856 } else if (OldMethod->isExplicitlyDefaulted()) { 1857 Diag(NewMethod->getLocation(), 1858 diag::err_definition_of_explicitly_defaulted_member) 1859 << getSpecialMember(OldMethod); 1860 return true; 1861 } 1862 } 1863 1864 // (C++98 8.3.5p3): 1865 // All declarations for a function shall agree exactly in both the 1866 // return type and the parameter-type-list. 1867 // We also want to respect all the extended bits except noreturn. 1868 1869 // noreturn should now match unless the old type info didn't have it. 1870 QualType OldQTypeForComparison = OldQType; 1871 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 1872 assert(OldQType == QualType(OldType, 0)); 1873 const FunctionType *OldTypeForComparison 1874 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 1875 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 1876 assert(OldQTypeForComparison.isCanonical()); 1877 } 1878 1879 if (OldQTypeForComparison == NewQType) 1880 return MergeCompatibleFunctionDecls(New, Old); 1881 1882 // Fall through for conflicting redeclarations and redefinitions. 1883 } 1884 1885 // C: Function types need to be compatible, not identical. This handles 1886 // duplicate function decls like "void f(int); void f(enum X);" properly. 1887 if (!getLangOptions().CPlusPlus && 1888 Context.typesAreCompatible(OldQType, NewQType)) { 1889 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 1890 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 1891 const FunctionProtoType *OldProto = 0; 1892 if (isa<FunctionNoProtoType>(NewFuncType) && 1893 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 1894 // The old declaration provided a function prototype, but the 1895 // new declaration does not. Merge in the prototype. 1896 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 1897 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 1898 OldProto->arg_type_end()); 1899 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 1900 ParamTypes.data(), ParamTypes.size(), 1901 OldProto->getExtProtoInfo()); 1902 New->setType(NewQType); 1903 New->setHasInheritedPrototype(); 1904 1905 // Synthesize a parameter for each argument type. 1906 SmallVector<ParmVarDecl*, 16> Params; 1907 for (FunctionProtoType::arg_type_iterator 1908 ParamType = OldProto->arg_type_begin(), 1909 ParamEnd = OldProto->arg_type_end(); 1910 ParamType != ParamEnd; ++ParamType) { 1911 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 1912 SourceLocation(), 1913 SourceLocation(), 0, 1914 *ParamType, /*TInfo=*/0, 1915 SC_None, SC_None, 1916 0); 1917 Param->setScopeInfo(0, Params.size()); 1918 Param->setImplicit(); 1919 Params.push_back(Param); 1920 } 1921 1922 New->setParams(Params); 1923 } 1924 1925 return MergeCompatibleFunctionDecls(New, Old); 1926 } 1927 1928 // GNU C permits a K&R definition to follow a prototype declaration 1929 // if the declared types of the parameters in the K&R definition 1930 // match the types in the prototype declaration, even when the 1931 // promoted types of the parameters from the K&R definition differ 1932 // from the types in the prototype. GCC then keeps the types from 1933 // the prototype. 1934 // 1935 // If a variadic prototype is followed by a non-variadic K&R definition, 1936 // the K&R definition becomes variadic. This is sort of an edge case, but 1937 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 1938 // C99 6.9.1p8. 1939 if (!getLangOptions().CPlusPlus && 1940 Old->hasPrototype() && !New->hasPrototype() && 1941 New->getType()->getAs<FunctionProtoType>() && 1942 Old->getNumParams() == New->getNumParams()) { 1943 SmallVector<QualType, 16> ArgTypes; 1944 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 1945 const FunctionProtoType *OldProto 1946 = Old->getType()->getAs<FunctionProtoType>(); 1947 const FunctionProtoType *NewProto 1948 = New->getType()->getAs<FunctionProtoType>(); 1949 1950 // Determine whether this is the GNU C extension. 1951 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 1952 NewProto->getResultType()); 1953 bool LooseCompatible = !MergedReturn.isNull(); 1954 for (unsigned Idx = 0, End = Old->getNumParams(); 1955 LooseCompatible && Idx != End; ++Idx) { 1956 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 1957 ParmVarDecl *NewParm = New->getParamDecl(Idx); 1958 if (Context.typesAreCompatible(OldParm->getType(), 1959 NewProto->getArgType(Idx))) { 1960 ArgTypes.push_back(NewParm->getType()); 1961 } else if (Context.typesAreCompatible(OldParm->getType(), 1962 NewParm->getType(), 1963 /*CompareUnqualified=*/true)) { 1964 GNUCompatibleParamWarning Warn 1965 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 1966 Warnings.push_back(Warn); 1967 ArgTypes.push_back(NewParm->getType()); 1968 } else 1969 LooseCompatible = false; 1970 } 1971 1972 if (LooseCompatible) { 1973 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 1974 Diag(Warnings[Warn].NewParm->getLocation(), 1975 diag::ext_param_promoted_not_compatible_with_prototype) 1976 << Warnings[Warn].PromotedType 1977 << Warnings[Warn].OldParm->getType(); 1978 if (Warnings[Warn].OldParm->getLocation().isValid()) 1979 Diag(Warnings[Warn].OldParm->getLocation(), 1980 diag::note_previous_declaration); 1981 } 1982 1983 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 1984 ArgTypes.size(), 1985 OldProto->getExtProtoInfo())); 1986 return MergeCompatibleFunctionDecls(New, Old); 1987 } 1988 1989 // Fall through to diagnose conflicting types. 1990 } 1991 1992 // A function that has already been declared has been redeclared or defined 1993 // with a different type- show appropriate diagnostic 1994 if (unsigned BuiltinID = Old->getBuiltinID()) { 1995 // The user has declared a builtin function with an incompatible 1996 // signature. 1997 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 1998 // The function the user is redeclaring is a library-defined 1999 // function like 'malloc' or 'printf'. Warn about the 2000 // redeclaration, then pretend that we don't know about this 2001 // library built-in. 2002 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2003 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2004 << Old << Old->getType(); 2005 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2006 Old->setInvalidDecl(); 2007 return false; 2008 } 2009 2010 PrevDiag = diag::note_previous_builtin_declaration; 2011 } 2012 2013 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2014 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2015 return true; 2016} 2017 2018/// \brief Completes the merge of two function declarations that are 2019/// known to be compatible. 2020/// 2021/// This routine handles the merging of attributes and other 2022/// properties of function declarations form the old declaration to 2023/// the new declaration, once we know that New is in fact a 2024/// redeclaration of Old. 2025/// 2026/// \returns false 2027bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 2028 // Merge the attributes 2029 mergeDeclAttributes(New, Old, Context); 2030 2031 // Merge the storage class. 2032 if (Old->getStorageClass() != SC_Extern && 2033 Old->getStorageClass() != SC_None) 2034 New->setStorageClass(Old->getStorageClass()); 2035 2036 // Merge "pure" flag. 2037 if (Old->isPure()) 2038 New->setPure(); 2039 2040 // __module_private__ is propagated to later declarations. 2041 if (Old->isModulePrivate()) 2042 New->setModulePrivate(); 2043 else if (New->isModulePrivate()) 2044 diagnoseModulePrivateRedeclaration(New, Old); 2045 2046 // Merge attributes from the parameters. These can mismatch with K&R 2047 // declarations. 2048 if (New->getNumParams() == Old->getNumParams()) 2049 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2050 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2051 Context); 2052 2053 if (getLangOptions().CPlusPlus) 2054 return MergeCXXFunctionDecl(New, Old); 2055 2056 return false; 2057} 2058 2059 2060void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2061 const ObjCMethodDecl *oldMethod) { 2062 // We don't want to merge unavailable and deprecated attributes 2063 // except from interface to implementation. 2064 bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext()); 2065 2066 // Merge the attributes. 2067 mergeDeclAttributes(newMethod, oldMethod, Context, mergeDeprecation); 2068 2069 // Merge attributes from the parameters. 2070 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(); 2071 for (ObjCMethodDecl::param_iterator 2072 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2073 ni != ne; ++ni, ++oi) 2074 mergeParamDeclAttributes(*ni, *oi, Context); 2075 2076 CheckObjCMethodOverride(newMethod, oldMethod, true); 2077} 2078 2079/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2080/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2081/// emitting diagnostics as appropriate. 2082/// 2083/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2084/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't 2085/// check them before the initializer is attached. 2086/// 2087void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 2088 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2089 return; 2090 2091 QualType MergedT; 2092 if (getLangOptions().CPlusPlus) { 2093 AutoType *AT = New->getType()->getContainedAutoType(); 2094 if (AT && !AT->isDeduced()) { 2095 // We don't know what the new type is until the initializer is attached. 2096 return; 2097 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2098 // These could still be something that needs exception specs checked. 2099 return MergeVarDeclExceptionSpecs(New, Old); 2100 } 2101 // C++ [basic.link]p10: 2102 // [...] the types specified by all declarations referring to a given 2103 // object or function shall be identical, except that declarations for an 2104 // array object can specify array types that differ by the presence or 2105 // absence of a major array bound (8.3.4). 2106 else if (Old->getType()->isIncompleteArrayType() && 2107 New->getType()->isArrayType()) { 2108 CanQual<ArrayType> OldArray 2109 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2110 CanQual<ArrayType> NewArray 2111 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2112 if (OldArray->getElementType() == NewArray->getElementType()) 2113 MergedT = New->getType(); 2114 } else if (Old->getType()->isArrayType() && 2115 New->getType()->isIncompleteArrayType()) { 2116 CanQual<ArrayType> OldArray 2117 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2118 CanQual<ArrayType> NewArray 2119 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2120 if (OldArray->getElementType() == NewArray->getElementType()) 2121 MergedT = Old->getType(); 2122 } else if (New->getType()->isObjCObjectPointerType() 2123 && Old->getType()->isObjCObjectPointerType()) { 2124 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2125 Old->getType()); 2126 } 2127 } else { 2128 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2129 } 2130 if (MergedT.isNull()) { 2131 Diag(New->getLocation(), diag::err_redefinition_different_type) 2132 << New->getDeclName(); 2133 Diag(Old->getLocation(), diag::note_previous_definition); 2134 return New->setInvalidDecl(); 2135 } 2136 New->setType(MergedT); 2137} 2138 2139/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2140/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2141/// situation, merging decls or emitting diagnostics as appropriate. 2142/// 2143/// Tentative definition rules (C99 6.9.2p2) are checked by 2144/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2145/// definitions here, since the initializer hasn't been attached. 2146/// 2147void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2148 // If the new decl is already invalid, don't do any other checking. 2149 if (New->isInvalidDecl()) 2150 return; 2151 2152 // Verify the old decl was also a variable. 2153 VarDecl *Old = 0; 2154 if (!Previous.isSingleResult() || 2155 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2156 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2157 << New->getDeclName(); 2158 Diag(Previous.getRepresentativeDecl()->getLocation(), 2159 diag::note_previous_definition); 2160 return New->setInvalidDecl(); 2161 } 2162 2163 // C++ [class.mem]p1: 2164 // A member shall not be declared twice in the member-specification [...] 2165 // 2166 // Here, we need only consider static data members. 2167 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2168 Diag(New->getLocation(), diag::err_duplicate_member) 2169 << New->getIdentifier(); 2170 Diag(Old->getLocation(), diag::note_previous_declaration); 2171 New->setInvalidDecl(); 2172 } 2173 2174 mergeDeclAttributes(New, Old, Context); 2175 // Warn if an already-declared variable is made a weak_import in a subsequent 2176 // declaration 2177 if (New->getAttr<WeakImportAttr>() && 2178 Old->getStorageClass() == SC_None && 2179 !Old->getAttr<WeakImportAttr>()) { 2180 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2181 Diag(Old->getLocation(), diag::note_previous_definition); 2182 // Remove weak_import attribute on new declaration. 2183 New->dropAttr<WeakImportAttr>(); 2184 } 2185 2186 // Merge the types. 2187 MergeVarDeclTypes(New, Old); 2188 if (New->isInvalidDecl()) 2189 return; 2190 2191 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2192 if (New->getStorageClass() == SC_Static && 2193 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2194 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2195 Diag(Old->getLocation(), diag::note_previous_definition); 2196 return New->setInvalidDecl(); 2197 } 2198 // C99 6.2.2p4: 2199 // For an identifier declared with the storage-class specifier 2200 // extern in a scope in which a prior declaration of that 2201 // identifier is visible,23) if the prior declaration specifies 2202 // internal or external linkage, the linkage of the identifier at 2203 // the later declaration is the same as the linkage specified at 2204 // the prior declaration. If no prior declaration is visible, or 2205 // if the prior declaration specifies no linkage, then the 2206 // identifier has external linkage. 2207 if (New->hasExternalStorage() && Old->hasLinkage()) 2208 /* Okay */; 2209 else if (New->getStorageClass() != SC_Static && 2210 Old->getStorageClass() == SC_Static) { 2211 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2212 Diag(Old->getLocation(), diag::note_previous_definition); 2213 return New->setInvalidDecl(); 2214 } 2215 2216 // Check if extern is followed by non-extern and vice-versa. 2217 if (New->hasExternalStorage() && 2218 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2219 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2220 Diag(Old->getLocation(), diag::note_previous_definition); 2221 return New->setInvalidDecl(); 2222 } 2223 if (Old->hasExternalStorage() && 2224 !New->hasLinkage() && New->isLocalVarDecl()) { 2225 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2226 Diag(Old->getLocation(), diag::note_previous_definition); 2227 return New->setInvalidDecl(); 2228 } 2229 2230 // __module_private__ is propagated to later declarations. 2231 if (Old->isModulePrivate()) 2232 New->setModulePrivate(); 2233 else if (New->isModulePrivate()) 2234 diagnoseModulePrivateRedeclaration(New, Old); 2235 2236 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2237 2238 // FIXME: The test for external storage here seems wrong? We still 2239 // need to check for mismatches. 2240 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2241 // Don't complain about out-of-line definitions of static members. 2242 !(Old->getLexicalDeclContext()->isRecord() && 2243 !New->getLexicalDeclContext()->isRecord())) { 2244 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2245 Diag(Old->getLocation(), diag::note_previous_definition); 2246 return New->setInvalidDecl(); 2247 } 2248 2249 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2250 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2251 Diag(Old->getLocation(), diag::note_previous_definition); 2252 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2253 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2254 Diag(Old->getLocation(), diag::note_previous_definition); 2255 } 2256 2257 // C++ doesn't have tentative definitions, so go right ahead and check here. 2258 const VarDecl *Def; 2259 if (getLangOptions().CPlusPlus && 2260 New->isThisDeclarationADefinition() == VarDecl::Definition && 2261 (Def = Old->getDefinition())) { 2262 Diag(New->getLocation(), diag::err_redefinition) 2263 << New->getDeclName(); 2264 Diag(Def->getLocation(), diag::note_previous_definition); 2265 New->setInvalidDecl(); 2266 return; 2267 } 2268 // c99 6.2.2 P4. 2269 // For an identifier declared with the storage-class specifier extern in a 2270 // scope in which a prior declaration of that identifier is visible, if 2271 // the prior declaration specifies internal or external linkage, the linkage 2272 // of the identifier at the later declaration is the same as the linkage 2273 // specified at the prior declaration. 2274 // FIXME. revisit this code. 2275 if (New->hasExternalStorage() && 2276 Old->getLinkage() == InternalLinkage && 2277 New->getDeclContext() == Old->getDeclContext()) 2278 New->setStorageClass(Old->getStorageClass()); 2279 2280 // Keep a chain of previous declarations. 2281 New->setPreviousDeclaration(Old); 2282 2283 // Inherit access appropriately. 2284 New->setAccess(Old->getAccess()); 2285} 2286 2287/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2288/// no declarator (e.g. "struct foo;") is parsed. 2289Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2290 DeclSpec &DS) { 2291 return ParsedFreeStandingDeclSpec(S, AS, DS, 2292 MultiTemplateParamsArg(*this, 0, 0)); 2293} 2294 2295/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2296/// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2297/// parameters to cope with template friend declarations. 2298Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2299 DeclSpec &DS, 2300 MultiTemplateParamsArg TemplateParams) { 2301 Decl *TagD = 0; 2302 TagDecl *Tag = 0; 2303 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2304 DS.getTypeSpecType() == DeclSpec::TST_struct || 2305 DS.getTypeSpecType() == DeclSpec::TST_union || 2306 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2307 TagD = DS.getRepAsDecl(); 2308 2309 if (!TagD) // We probably had an error 2310 return 0; 2311 2312 // Note that the above type specs guarantee that the 2313 // type rep is a Decl, whereas in many of the others 2314 // it's a Type. 2315 Tag = dyn_cast<TagDecl>(TagD); 2316 } 2317 2318 if (Tag) 2319 Tag->setFreeStanding(); 2320 2321 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 2322 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 2323 // or incomplete types shall not be restrict-qualified." 2324 if (TypeQuals & DeclSpec::TQ_restrict) 2325 Diag(DS.getRestrictSpecLoc(), 2326 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 2327 << DS.getSourceRange(); 2328 } 2329 2330 if (DS.isConstexprSpecified()) { 2331 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 2332 // and definitions of functions and variables. 2333 if (Tag) 2334 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 2335 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 2336 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 2337 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3); 2338 else 2339 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 2340 // Don't emit warnings after this error. 2341 return TagD; 2342 } 2343 2344 if (DS.isFriendSpecified()) { 2345 // If we're dealing with a decl but not a TagDecl, assume that 2346 // whatever routines created it handled the friendship aspect. 2347 if (TagD && !Tag) 2348 return 0; 2349 return ActOnFriendTypeDecl(S, DS, TemplateParams); 2350 } 2351 2352 // Track whether we warned about the fact that there aren't any 2353 // declarators. 2354 bool emittedWarning = false; 2355 2356 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 2357 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList()); 2358 2359 if (!Record->getDeclName() && Record->isCompleteDefinition() && 2360 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 2361 if (getLangOptions().CPlusPlus || 2362 Record->getDeclContext()->isRecord()) 2363 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 2364 2365 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2366 << DS.getSourceRange(); 2367 emittedWarning = true; 2368 } 2369 } 2370 2371 // Check for Microsoft C extension: anonymous struct. 2372 if (getLangOptions().MicrosoftExt && !getLangOptions().CPlusPlus && 2373 CurContext->isRecord() && 2374 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 2375 // Handle 2 kinds of anonymous struct: 2376 // struct STRUCT; 2377 // and 2378 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 2379 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 2380 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 2381 (DS.getTypeSpecType() == DeclSpec::TST_typename && 2382 DS.getRepAsType().get()->isStructureType())) { 2383 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct) 2384 << DS.getSourceRange(); 2385 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 2386 } 2387 } 2388 2389 if (getLangOptions().CPlusPlus && 2390 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 2391 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 2392 if (Enum->enumerator_begin() == Enum->enumerator_end() && 2393 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 2394 Diag(Enum->getLocation(), diag::ext_no_declarators) 2395 << DS.getSourceRange(); 2396 emittedWarning = true; 2397 } 2398 2399 // Skip all the checks below if we have a type error. 2400 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 2401 2402 if (!DS.isMissingDeclaratorOk()) { 2403 // Warn about typedefs of enums without names, since this is an 2404 // extension in both Microsoft and GNU. 2405 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 2406 Tag && isa<EnumDecl>(Tag)) { 2407 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 2408 << DS.getSourceRange(); 2409 return Tag; 2410 } 2411 2412 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2413 << DS.getSourceRange(); 2414 emittedWarning = true; 2415 } 2416 2417 // We're going to complain about a bunch of spurious specifiers; 2418 // only do this if we're declaring a tag, because otherwise we 2419 // should be getting diag::ext_no_declarators. 2420 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 2421 return TagD; 2422 2423 // Note that a linkage-specification sets a storage class, but 2424 // 'extern "C" struct foo;' is actually valid and not theoretically 2425 // useless. 2426 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 2427 if (!DS.isExternInLinkageSpec()) 2428 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 2429 << DeclSpec::getSpecifierName(scs); 2430 2431 if (DS.isThreadSpecified()) 2432 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 2433 if (DS.getTypeQualifiers()) { 2434 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2435 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 2436 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2437 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 2438 // Restrict is covered above. 2439 } 2440 if (DS.isInlineSpecified()) 2441 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 2442 if (DS.isVirtualSpecified()) 2443 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 2444 if (DS.isExplicitSpecified()) 2445 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 2446 2447 if (DS.isModulePrivateSpecified() && 2448 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 2449 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 2450 << Tag->getTagKind() 2451 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 2452 2453 // FIXME: Warn on useless attributes 2454 2455 return TagD; 2456} 2457 2458/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec. 2459/// builds a statement for it and returns it so it is evaluated. 2460StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) { 2461 StmtResult R; 2462 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) { 2463 Expr *Exp = DS.getRepAsExpr(); 2464 QualType Ty = Exp->getType(); 2465 if (Ty->isPointerType()) { 2466 do 2467 Ty = Ty->getAs<PointerType>()->getPointeeType(); 2468 while (Ty->isPointerType()); 2469 } 2470 if (Ty->isVariableArrayType()) { 2471 R = ActOnExprStmt(MakeFullExpr(Exp)); 2472 } 2473 } 2474 return R; 2475} 2476 2477/// We are trying to inject an anonymous member into the given scope; 2478/// check if there's an existing declaration that can't be overloaded. 2479/// 2480/// \return true if this is a forbidden redeclaration 2481static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 2482 Scope *S, 2483 DeclContext *Owner, 2484 DeclarationName Name, 2485 SourceLocation NameLoc, 2486 unsigned diagnostic) { 2487 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 2488 Sema::ForRedeclaration); 2489 if (!SemaRef.LookupName(R, S)) return false; 2490 2491 if (R.getAsSingle<TagDecl>()) 2492 return false; 2493 2494 // Pick a representative declaration. 2495 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 2496 assert(PrevDecl && "Expected a non-null Decl"); 2497 2498 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 2499 return false; 2500 2501 SemaRef.Diag(NameLoc, diagnostic) << Name; 2502 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 2503 2504 return true; 2505} 2506 2507/// InjectAnonymousStructOrUnionMembers - Inject the members of the 2508/// anonymous struct or union AnonRecord into the owning context Owner 2509/// and scope S. This routine will be invoked just after we realize 2510/// that an unnamed union or struct is actually an anonymous union or 2511/// struct, e.g., 2512/// 2513/// @code 2514/// union { 2515/// int i; 2516/// float f; 2517/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 2518/// // f into the surrounding scope.x 2519/// @endcode 2520/// 2521/// This routine is recursive, injecting the names of nested anonymous 2522/// structs/unions into the owning context and scope as well. 2523static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 2524 DeclContext *Owner, 2525 RecordDecl *AnonRecord, 2526 AccessSpecifier AS, 2527 SmallVector<NamedDecl*, 2> &Chaining, 2528 bool MSAnonStruct) { 2529 unsigned diagKind 2530 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 2531 : diag::err_anonymous_struct_member_redecl; 2532 2533 bool Invalid = false; 2534 2535 // Look every FieldDecl and IndirectFieldDecl with a name. 2536 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 2537 DEnd = AnonRecord->decls_end(); 2538 D != DEnd; ++D) { 2539 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 2540 cast<NamedDecl>(*D)->getDeclName()) { 2541 ValueDecl *VD = cast<ValueDecl>(*D); 2542 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 2543 VD->getLocation(), diagKind)) { 2544 // C++ [class.union]p2: 2545 // The names of the members of an anonymous union shall be 2546 // distinct from the names of any other entity in the 2547 // scope in which the anonymous union is declared. 2548 Invalid = true; 2549 } else { 2550 // C++ [class.union]p2: 2551 // For the purpose of name lookup, after the anonymous union 2552 // definition, the members of the anonymous union are 2553 // considered to have been defined in the scope in which the 2554 // anonymous union is declared. 2555 unsigned OldChainingSize = Chaining.size(); 2556 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 2557 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 2558 PE = IF->chain_end(); PI != PE; ++PI) 2559 Chaining.push_back(*PI); 2560 else 2561 Chaining.push_back(VD); 2562 2563 assert(Chaining.size() >= 2); 2564 NamedDecl **NamedChain = 2565 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 2566 for (unsigned i = 0; i < Chaining.size(); i++) 2567 NamedChain[i] = Chaining[i]; 2568 2569 IndirectFieldDecl* IndirectField = 2570 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 2571 VD->getIdentifier(), VD->getType(), 2572 NamedChain, Chaining.size()); 2573 2574 IndirectField->setAccess(AS); 2575 IndirectField->setImplicit(); 2576 SemaRef.PushOnScopeChains(IndirectField, S); 2577 2578 // That includes picking up the appropriate access specifier. 2579 if (AS != AS_none) IndirectField->setAccess(AS); 2580 2581 Chaining.resize(OldChainingSize); 2582 } 2583 } 2584 } 2585 2586 return Invalid; 2587} 2588 2589/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 2590/// a VarDecl::StorageClass. Any error reporting is up to the caller: 2591/// illegal input values are mapped to SC_None. 2592static StorageClass 2593StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2594 switch (StorageClassSpec) { 2595 case DeclSpec::SCS_unspecified: return SC_None; 2596 case DeclSpec::SCS_extern: return SC_Extern; 2597 case DeclSpec::SCS_static: return SC_Static; 2598 case DeclSpec::SCS_auto: return SC_Auto; 2599 case DeclSpec::SCS_register: return SC_Register; 2600 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2601 // Illegal SCSs map to None: error reporting is up to the caller. 2602 case DeclSpec::SCS_mutable: // Fall through. 2603 case DeclSpec::SCS_typedef: return SC_None; 2604 } 2605 llvm_unreachable("unknown storage class specifier"); 2606} 2607 2608/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 2609/// a StorageClass. Any error reporting is up to the caller: 2610/// illegal input values are mapped to SC_None. 2611static StorageClass 2612StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2613 switch (StorageClassSpec) { 2614 case DeclSpec::SCS_unspecified: return SC_None; 2615 case DeclSpec::SCS_extern: return SC_Extern; 2616 case DeclSpec::SCS_static: return SC_Static; 2617 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2618 // Illegal SCSs map to None: error reporting is up to the caller. 2619 case DeclSpec::SCS_auto: // Fall through. 2620 case DeclSpec::SCS_mutable: // Fall through. 2621 case DeclSpec::SCS_register: // Fall through. 2622 case DeclSpec::SCS_typedef: return SC_None; 2623 } 2624 llvm_unreachable("unknown storage class specifier"); 2625} 2626 2627/// BuildAnonymousStructOrUnion - Handle the declaration of an 2628/// anonymous structure or union. Anonymous unions are a C++ feature 2629/// (C++ [class.union]) and a GNU C extension; anonymous structures 2630/// are a GNU C and GNU C++ extension. 2631Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2632 AccessSpecifier AS, 2633 RecordDecl *Record) { 2634 DeclContext *Owner = Record->getDeclContext(); 2635 2636 // Diagnose whether this anonymous struct/union is an extension. 2637 if (Record->isUnion() && !getLangOptions().CPlusPlus) 2638 Diag(Record->getLocation(), diag::ext_anonymous_union); 2639 else if (!Record->isUnion()) 2640 Diag(Record->getLocation(), diag::ext_anonymous_struct); 2641 2642 // C and C++ require different kinds of checks for anonymous 2643 // structs/unions. 2644 bool Invalid = false; 2645 if (getLangOptions().CPlusPlus) { 2646 const char* PrevSpec = 0; 2647 unsigned DiagID; 2648 if (Record->isUnion()) { 2649 // C++ [class.union]p6: 2650 // Anonymous unions declared in a named namespace or in the 2651 // global namespace shall be declared static. 2652 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 2653 (isa<TranslationUnitDecl>(Owner) || 2654 (isa<NamespaceDecl>(Owner) && 2655 cast<NamespaceDecl>(Owner)->getDeclName()))) { 2656 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 2657 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 2658 Invalid = true; 2659 2660 // Recover by adding 'static'. 2661 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 2662 PrevSpec, DiagID); 2663 } 2664 // C++ [class.union]p6: 2665 // A storage class is not allowed in a declaration of an 2666 // anonymous union in a class scope. 2667 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 2668 isa<RecordDecl>(Owner)) { 2669 Diag(DS.getStorageClassSpecLoc(), 2670 diag::err_anonymous_union_with_storage_spec) 2671 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 2672 Invalid = true; 2673 2674 // Recover by removing the storage specifier. 2675 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 2676 SourceLocation(), 2677 PrevSpec, DiagID); 2678 } 2679 } 2680 2681 // Ignore const/volatile/restrict qualifiers. 2682 if (DS.getTypeQualifiers()) { 2683 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2684 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2685 << Record->isUnion() << 0 2686 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 2687 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2688 Diag(DS.getVolatileSpecLoc(), 2689 diag::ext_anonymous_struct_union_qualified) 2690 << Record->isUnion() << 1 2691 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 2692 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 2693 Diag(DS.getRestrictSpecLoc(), 2694 diag::ext_anonymous_struct_union_qualified) 2695 << Record->isUnion() << 2 2696 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 2697 2698 DS.ClearTypeQualifiers(); 2699 } 2700 2701 // C++ [class.union]p2: 2702 // The member-specification of an anonymous union shall only 2703 // define non-static data members. [Note: nested types and 2704 // functions cannot be declared within an anonymous union. ] 2705 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 2706 MemEnd = Record->decls_end(); 2707 Mem != MemEnd; ++Mem) { 2708 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 2709 // C++ [class.union]p3: 2710 // An anonymous union shall not have private or protected 2711 // members (clause 11). 2712 assert(FD->getAccess() != AS_none); 2713 if (FD->getAccess() != AS_public) { 2714 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 2715 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 2716 Invalid = true; 2717 } 2718 2719 // C++ [class.union]p1 2720 // An object of a class with a non-trivial constructor, a non-trivial 2721 // copy constructor, a non-trivial destructor, or a non-trivial copy 2722 // assignment operator cannot be a member of a union, nor can an 2723 // array of such objects. 2724 if (CheckNontrivialField(FD)) 2725 Invalid = true; 2726 } else if ((*Mem)->isImplicit()) { 2727 // Any implicit members are fine. 2728 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 2729 // This is a type that showed up in an 2730 // elaborated-type-specifier inside the anonymous struct or 2731 // union, but which actually declares a type outside of the 2732 // anonymous struct or union. It's okay. 2733 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 2734 if (!MemRecord->isAnonymousStructOrUnion() && 2735 MemRecord->getDeclName()) { 2736 // Visual C++ allows type definition in anonymous struct or union. 2737 if (getLangOptions().MicrosoftExt) 2738 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 2739 << (int)Record->isUnion(); 2740 else { 2741 // This is a nested type declaration. 2742 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 2743 << (int)Record->isUnion(); 2744 Invalid = true; 2745 } 2746 } 2747 } else if (isa<AccessSpecDecl>(*Mem)) { 2748 // Any access specifier is fine. 2749 } else { 2750 // We have something that isn't a non-static data 2751 // member. Complain about it. 2752 unsigned DK = diag::err_anonymous_record_bad_member; 2753 if (isa<TypeDecl>(*Mem)) 2754 DK = diag::err_anonymous_record_with_type; 2755 else if (isa<FunctionDecl>(*Mem)) 2756 DK = diag::err_anonymous_record_with_function; 2757 else if (isa<VarDecl>(*Mem)) 2758 DK = diag::err_anonymous_record_with_static; 2759 2760 // Visual C++ allows type definition in anonymous struct or union. 2761 if (getLangOptions().MicrosoftExt && 2762 DK == diag::err_anonymous_record_with_type) 2763 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 2764 << (int)Record->isUnion(); 2765 else { 2766 Diag((*Mem)->getLocation(), DK) 2767 << (int)Record->isUnion(); 2768 Invalid = true; 2769 } 2770 } 2771 } 2772 } 2773 2774 if (!Record->isUnion() && !Owner->isRecord()) { 2775 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 2776 << (int)getLangOptions().CPlusPlus; 2777 Invalid = true; 2778 } 2779 2780 // Mock up a declarator. 2781 Declarator Dc(DS, Declarator::MemberContext); 2782 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2783 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 2784 2785 // Create a declaration for this anonymous struct/union. 2786 NamedDecl *Anon = 0; 2787 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 2788 Anon = FieldDecl::Create(Context, OwningClass, 2789 DS.getSourceRange().getBegin(), 2790 Record->getLocation(), 2791 /*IdentifierInfo=*/0, 2792 Context.getTypeDeclType(Record), 2793 TInfo, 2794 /*BitWidth=*/0, /*Mutable=*/false, 2795 /*HasInit=*/false); 2796 Anon->setAccess(AS); 2797 if (getLangOptions().CPlusPlus) 2798 FieldCollector->Add(cast<FieldDecl>(Anon)); 2799 } else { 2800 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 2801 assert(SCSpec != DeclSpec::SCS_typedef && 2802 "Parser allowed 'typedef' as storage class VarDecl."); 2803 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 2804 if (SCSpec == DeclSpec::SCS_mutable) { 2805 // mutable can only appear on non-static class members, so it's always 2806 // an error here 2807 Diag(Record->getLocation(), diag::err_mutable_nonmember); 2808 Invalid = true; 2809 SC = SC_None; 2810 } 2811 SCSpec = DS.getStorageClassSpecAsWritten(); 2812 VarDecl::StorageClass SCAsWritten 2813 = StorageClassSpecToVarDeclStorageClass(SCSpec); 2814 2815 Anon = VarDecl::Create(Context, Owner, 2816 DS.getSourceRange().getBegin(), 2817 Record->getLocation(), /*IdentifierInfo=*/0, 2818 Context.getTypeDeclType(Record), 2819 TInfo, SC, SCAsWritten); 2820 2821 // Default-initialize the implicit variable. This initialization will be 2822 // trivial in almost all cases, except if a union member has an in-class 2823 // initializer: 2824 // union { int n = 0; }; 2825 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 2826 } 2827 Anon->setImplicit(); 2828 2829 // Add the anonymous struct/union object to the current 2830 // context. We'll be referencing this object when we refer to one of 2831 // its members. 2832 Owner->addDecl(Anon); 2833 2834 // Inject the members of the anonymous struct/union into the owning 2835 // context and into the identifier resolver chain for name lookup 2836 // purposes. 2837 SmallVector<NamedDecl*, 2> Chain; 2838 Chain.push_back(Anon); 2839 2840 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 2841 Chain, false)) 2842 Invalid = true; 2843 2844 // Mark this as an anonymous struct/union type. Note that we do not 2845 // do this until after we have already checked and injected the 2846 // members of this anonymous struct/union type, because otherwise 2847 // the members could be injected twice: once by DeclContext when it 2848 // builds its lookup table, and once by 2849 // InjectAnonymousStructOrUnionMembers. 2850 Record->setAnonymousStructOrUnion(true); 2851 2852 if (Invalid) 2853 Anon->setInvalidDecl(); 2854 2855 return Anon; 2856} 2857 2858/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 2859/// Microsoft C anonymous structure. 2860/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 2861/// Example: 2862/// 2863/// struct A { int a; }; 2864/// struct B { struct A; int b; }; 2865/// 2866/// void foo() { 2867/// B var; 2868/// var.a = 3; 2869/// } 2870/// 2871Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2872 RecordDecl *Record) { 2873 2874 // If there is no Record, get the record via the typedef. 2875 if (!Record) 2876 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 2877 2878 // Mock up a declarator. 2879 Declarator Dc(DS, Declarator::TypeNameContext); 2880 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2881 assert(TInfo && "couldn't build declarator info for anonymous struct"); 2882 2883 // Create a declaration for this anonymous struct. 2884 NamedDecl* Anon = FieldDecl::Create(Context, 2885 cast<RecordDecl>(CurContext), 2886 DS.getSourceRange().getBegin(), 2887 DS.getSourceRange().getBegin(), 2888 /*IdentifierInfo=*/0, 2889 Context.getTypeDeclType(Record), 2890 TInfo, 2891 /*BitWidth=*/0, /*Mutable=*/false, 2892 /*HasInit=*/false); 2893 Anon->setImplicit(); 2894 2895 // Add the anonymous struct object to the current context. 2896 CurContext->addDecl(Anon); 2897 2898 // Inject the members of the anonymous struct into the current 2899 // context and into the identifier resolver chain for name lookup 2900 // purposes. 2901 SmallVector<NamedDecl*, 2> Chain; 2902 Chain.push_back(Anon); 2903 2904 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 2905 Record->getDefinition(), 2906 AS_none, Chain, true)) 2907 Anon->setInvalidDecl(); 2908 2909 return Anon; 2910} 2911 2912/// GetNameForDeclarator - Determine the full declaration name for the 2913/// given Declarator. 2914DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 2915 return GetNameFromUnqualifiedId(D.getName()); 2916} 2917 2918/// \brief Retrieves the declaration name from a parsed unqualified-id. 2919DeclarationNameInfo 2920Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 2921 DeclarationNameInfo NameInfo; 2922 NameInfo.setLoc(Name.StartLocation); 2923 2924 switch (Name.getKind()) { 2925 2926 case UnqualifiedId::IK_ImplicitSelfParam: 2927 case UnqualifiedId::IK_Identifier: 2928 NameInfo.setName(Name.Identifier); 2929 NameInfo.setLoc(Name.StartLocation); 2930 return NameInfo; 2931 2932 case UnqualifiedId::IK_OperatorFunctionId: 2933 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 2934 Name.OperatorFunctionId.Operator)); 2935 NameInfo.setLoc(Name.StartLocation); 2936 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 2937 = Name.OperatorFunctionId.SymbolLocations[0]; 2938 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 2939 = Name.EndLocation.getRawEncoding(); 2940 return NameInfo; 2941 2942 case UnqualifiedId::IK_LiteralOperatorId: 2943 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 2944 Name.Identifier)); 2945 NameInfo.setLoc(Name.StartLocation); 2946 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 2947 return NameInfo; 2948 2949 case UnqualifiedId::IK_ConversionFunctionId: { 2950 TypeSourceInfo *TInfo; 2951 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 2952 if (Ty.isNull()) 2953 return DeclarationNameInfo(); 2954 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 2955 Context.getCanonicalType(Ty))); 2956 NameInfo.setLoc(Name.StartLocation); 2957 NameInfo.setNamedTypeInfo(TInfo); 2958 return NameInfo; 2959 } 2960 2961 case UnqualifiedId::IK_ConstructorName: { 2962 TypeSourceInfo *TInfo; 2963 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 2964 if (Ty.isNull()) 2965 return DeclarationNameInfo(); 2966 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2967 Context.getCanonicalType(Ty))); 2968 NameInfo.setLoc(Name.StartLocation); 2969 NameInfo.setNamedTypeInfo(TInfo); 2970 return NameInfo; 2971 } 2972 2973 case UnqualifiedId::IK_ConstructorTemplateId: { 2974 // In well-formed code, we can only have a constructor 2975 // template-id that refers to the current context, so go there 2976 // to find the actual type being constructed. 2977 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 2978 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 2979 return DeclarationNameInfo(); 2980 2981 // Determine the type of the class being constructed. 2982 QualType CurClassType = Context.getTypeDeclType(CurClass); 2983 2984 // FIXME: Check two things: that the template-id names the same type as 2985 // CurClassType, and that the template-id does not occur when the name 2986 // was qualified. 2987 2988 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2989 Context.getCanonicalType(CurClassType))); 2990 NameInfo.setLoc(Name.StartLocation); 2991 // FIXME: should we retrieve TypeSourceInfo? 2992 NameInfo.setNamedTypeInfo(0); 2993 return NameInfo; 2994 } 2995 2996 case UnqualifiedId::IK_DestructorName: { 2997 TypeSourceInfo *TInfo; 2998 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 2999 if (Ty.isNull()) 3000 return DeclarationNameInfo(); 3001 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3002 Context.getCanonicalType(Ty))); 3003 NameInfo.setLoc(Name.StartLocation); 3004 NameInfo.setNamedTypeInfo(TInfo); 3005 return NameInfo; 3006 } 3007 3008 case UnqualifiedId::IK_TemplateId: { 3009 TemplateName TName = Name.TemplateId->Template.get(); 3010 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3011 return Context.getNameForTemplate(TName, TNameLoc); 3012 } 3013 3014 } // switch (Name.getKind()) 3015 3016 llvm_unreachable("Unknown name kind"); 3017} 3018 3019static QualType getCoreType(QualType Ty) { 3020 do { 3021 if (Ty->isPointerType() || Ty->isReferenceType()) 3022 Ty = Ty->getPointeeType(); 3023 else if (Ty->isArrayType()) 3024 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3025 else 3026 return Ty.withoutLocalFastQualifiers(); 3027 } while (true); 3028} 3029 3030/// hasSimilarParameters - Determine whether the C++ functions Declaration 3031/// and Definition have "nearly" matching parameters. This heuristic is 3032/// used to improve diagnostics in the case where an out-of-line function 3033/// definition doesn't match any declaration within the class or namespace. 3034/// Also sets Params to the list of indices to the parameters that differ 3035/// between the declaration and the definition. If hasSimilarParameters 3036/// returns true and Params is empty, then all of the parameters match. 3037static bool hasSimilarParameters(ASTContext &Context, 3038 FunctionDecl *Declaration, 3039 FunctionDecl *Definition, 3040 llvm::SmallVectorImpl<unsigned> &Params) { 3041 Params.clear(); 3042 if (Declaration->param_size() != Definition->param_size()) 3043 return false; 3044 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3045 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3046 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3047 3048 // The parameter types are identical 3049 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3050 continue; 3051 3052 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3053 QualType DefParamBaseTy = getCoreType(DefParamTy); 3054 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3055 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3056 3057 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3058 (DeclTyName && DeclTyName == DefTyName)) 3059 Params.push_back(Idx); 3060 else // The two parameters aren't even close 3061 return false; 3062 } 3063 3064 return true; 3065} 3066 3067/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3068/// declarator needs to be rebuilt in the current instantiation. 3069/// Any bits of declarator which appear before the name are valid for 3070/// consideration here. That's specifically the type in the decl spec 3071/// and the base type in any member-pointer chunks. 3072static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3073 DeclarationName Name) { 3074 // The types we specifically need to rebuild are: 3075 // - typenames, typeofs, and decltypes 3076 // - types which will become injected class names 3077 // Of course, we also need to rebuild any type referencing such a 3078 // type. It's safest to just say "dependent", but we call out a 3079 // few cases here. 3080 3081 DeclSpec &DS = D.getMutableDeclSpec(); 3082 switch (DS.getTypeSpecType()) { 3083 case DeclSpec::TST_typename: 3084 case DeclSpec::TST_typeofType: 3085 case DeclSpec::TST_decltype: 3086 case DeclSpec::TST_underlyingType: 3087 case DeclSpec::TST_atomic: { 3088 // Grab the type from the parser. 3089 TypeSourceInfo *TSI = 0; 3090 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3091 if (T.isNull() || !T->isDependentType()) break; 3092 3093 // Make sure there's a type source info. This isn't really much 3094 // of a waste; most dependent types should have type source info 3095 // attached already. 3096 if (!TSI) 3097 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3098 3099 // Rebuild the type in the current instantiation. 3100 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3101 if (!TSI) return true; 3102 3103 // Store the new type back in the decl spec. 3104 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3105 DS.UpdateTypeRep(LocType); 3106 break; 3107 } 3108 3109 case DeclSpec::TST_typeofExpr: { 3110 Expr *E = DS.getRepAsExpr(); 3111 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3112 if (Result.isInvalid()) return true; 3113 DS.UpdateExprRep(Result.get()); 3114 break; 3115 } 3116 3117 default: 3118 // Nothing to do for these decl specs. 3119 break; 3120 } 3121 3122 // It doesn't matter what order we do this in. 3123 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3124 DeclaratorChunk &Chunk = D.getTypeObject(I); 3125 3126 // The only type information in the declarator which can come 3127 // before the declaration name is the base type of a member 3128 // pointer. 3129 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3130 continue; 3131 3132 // Rebuild the scope specifier in-place. 3133 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3134 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3135 return true; 3136 } 3137 3138 return false; 3139} 3140 3141Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3142 D.setFunctionDefinition(false); 3143 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this)); 3144} 3145 3146/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3147/// If T is the name of a class, then each of the following shall have a 3148/// name different from T: 3149/// - every static data member of class T; 3150/// - every member function of class T 3151/// - every member of class T that is itself a type; 3152/// \returns true if the declaration name violates these rules. 3153bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3154 DeclarationNameInfo NameInfo) { 3155 DeclarationName Name = NameInfo.getName(); 3156 3157 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3158 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3159 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3160 return true; 3161 } 3162 3163 return false; 3164} 3165 3166Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 3167 MultiTemplateParamsArg TemplateParamLists) { 3168 // TODO: consider using NameInfo for diagnostic. 3169 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3170 DeclarationName Name = NameInfo.getName(); 3171 3172 // All of these full declarators require an identifier. If it doesn't have 3173 // one, the ParsedFreeStandingDeclSpec action should be used. 3174 if (!Name) { 3175 if (!D.isInvalidType()) // Reject this if we think it is valid. 3176 Diag(D.getDeclSpec().getSourceRange().getBegin(), 3177 diag::err_declarator_need_ident) 3178 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 3179 return 0; 3180 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 3181 return 0; 3182 3183 // The scope passed in may not be a decl scope. Zip up the scope tree until 3184 // we find one that is. 3185 while ((S->getFlags() & Scope::DeclScope) == 0 || 3186 (S->getFlags() & Scope::TemplateParamScope) != 0) 3187 S = S->getParent(); 3188 3189 DeclContext *DC = CurContext; 3190 if (D.getCXXScopeSpec().isInvalid()) 3191 D.setInvalidType(); 3192 else if (D.getCXXScopeSpec().isSet()) { 3193 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 3194 UPPC_DeclarationQualifier)) 3195 return 0; 3196 3197 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 3198 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 3199 if (!DC) { 3200 // If we could not compute the declaration context, it's because the 3201 // declaration context is dependent but does not refer to a class, 3202 // class template, or class template partial specialization. Complain 3203 // and return early, to avoid the coming semantic disaster. 3204 Diag(D.getIdentifierLoc(), 3205 diag::err_template_qualified_declarator_no_match) 3206 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 3207 << D.getCXXScopeSpec().getRange(); 3208 return 0; 3209 } 3210 bool IsDependentContext = DC->isDependentContext(); 3211 3212 if (!IsDependentContext && 3213 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 3214 return 0; 3215 3216 if (isa<CXXRecordDecl>(DC)) { 3217 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) { 3218 Diag(D.getIdentifierLoc(), 3219 diag::err_member_def_undefined_record) 3220 << Name << DC << D.getCXXScopeSpec().getRange(); 3221 D.setInvalidType(); 3222 } else if (isa<CXXRecordDecl>(CurContext) && 3223 !D.getDeclSpec().isFriendSpecified()) { 3224 // The user provided a superfluous scope specifier inside a class 3225 // definition: 3226 // 3227 // class X { 3228 // void X::f(); 3229 // }; 3230 if (CurContext->Equals(DC)) 3231 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 3232 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange()); 3233 else 3234 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3235 << Name << D.getCXXScopeSpec().getRange(); 3236 3237 // Pretend that this qualifier was not here. 3238 D.getCXXScopeSpec().clear(); 3239 } 3240 } 3241 3242 // Check whether we need to rebuild the type of the given 3243 // declaration in the current instantiation. 3244 if (EnteringContext && IsDependentContext && 3245 TemplateParamLists.size() != 0) { 3246 ContextRAII SavedContext(*this, DC); 3247 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 3248 D.setInvalidType(); 3249 } 3250 } 3251 3252 if (DiagnoseClassNameShadow(DC, NameInfo)) 3253 // If this is a typedef, we'll end up spewing multiple diagnostics. 3254 // Just return early; it's safer. 3255 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3256 return 0; 3257 3258 NamedDecl *New; 3259 3260 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3261 QualType R = TInfo->getType(); 3262 3263 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 3264 UPPC_DeclarationType)) 3265 D.setInvalidType(); 3266 3267 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 3268 ForRedeclaration); 3269 3270 // See if this is a redefinition of a variable in the same scope. 3271 if (!D.getCXXScopeSpec().isSet()) { 3272 bool IsLinkageLookup = false; 3273 3274 // If the declaration we're planning to build will be a function 3275 // or object with linkage, then look for another declaration with 3276 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 3277 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3278 /* Do nothing*/; 3279 else if (R->isFunctionType()) { 3280 if (CurContext->isFunctionOrMethod() || 3281 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3282 IsLinkageLookup = true; 3283 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 3284 IsLinkageLookup = true; 3285 else if (CurContext->getRedeclContext()->isTranslationUnit() && 3286 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3287 IsLinkageLookup = true; 3288 3289 if (IsLinkageLookup) 3290 Previous.clear(LookupRedeclarationWithLinkage); 3291 3292 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 3293 } else { // Something like "int foo::x;" 3294 LookupQualifiedName(Previous, DC); 3295 3296 // Don't consider using declarations as previous declarations for 3297 // out-of-line members. 3298 RemoveUsingDecls(Previous); 3299 3300 // C++ 7.3.1.2p2: 3301 // Members (including explicit specializations of templates) of a named 3302 // namespace can also be defined outside that namespace by explicit 3303 // qualification of the name being defined, provided that the entity being 3304 // defined was already declared in the namespace and the definition appears 3305 // after the point of declaration in a namespace that encloses the 3306 // declarations namespace. 3307 // 3308 // Note that we only check the context at this point. We don't yet 3309 // have enough information to make sure that PrevDecl is actually 3310 // the declaration we want to match. For example, given: 3311 // 3312 // class X { 3313 // void f(); 3314 // void f(float); 3315 // }; 3316 // 3317 // void X::f(int) { } // ill-formed 3318 // 3319 // In this case, PrevDecl will point to the overload set 3320 // containing the two f's declared in X, but neither of them 3321 // matches. 3322 3323 // First check whether we named the global scope. 3324 if (isa<TranslationUnitDecl>(DC)) { 3325 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 3326 << Name << D.getCXXScopeSpec().getRange(); 3327 } else { 3328 DeclContext *Cur = CurContext; 3329 while (isa<LinkageSpecDecl>(Cur)) 3330 Cur = Cur->getParent(); 3331 if (!Cur->Encloses(DC)) { 3332 // The qualifying scope doesn't enclose the original declaration. 3333 // Emit diagnostic based on current scope. 3334 SourceLocation L = D.getIdentifierLoc(); 3335 SourceRange R = D.getCXXScopeSpec().getRange(); 3336 if (isa<FunctionDecl>(Cur)) 3337 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 3338 else 3339 Diag(L, diag::err_invalid_declarator_scope) 3340 << Name << cast<NamedDecl>(DC) << R; 3341 D.setInvalidType(); 3342 } 3343 } 3344 } 3345 3346 if (Previous.isSingleResult() && 3347 Previous.getFoundDecl()->isTemplateParameter()) { 3348 // Maybe we will complain about the shadowed template parameter. 3349 if (!D.isInvalidType()) 3350 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 3351 Previous.getFoundDecl()); 3352 3353 // Just pretend that we didn't see the previous declaration. 3354 Previous.clear(); 3355 } 3356 3357 // In C++, the previous declaration we find might be a tag type 3358 // (class or enum). In this case, the new declaration will hide the 3359 // tag type. Note that this does does not apply if we're declaring a 3360 // typedef (C++ [dcl.typedef]p4). 3361 if (Previous.isSingleTagDecl() && 3362 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 3363 Previous.clear(); 3364 3365 bool AddToScope = true; 3366 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3367 if (TemplateParamLists.size()) { 3368 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 3369 return 0; 3370 } 3371 3372 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 3373 } else if (R->isFunctionType()) { 3374 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 3375 move(TemplateParamLists), 3376 AddToScope); 3377 } else { 3378 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 3379 move(TemplateParamLists)); 3380 } 3381 3382 if (New == 0) 3383 return 0; 3384 3385 // If this has an identifier and is not an invalid redeclaration or 3386 // function template specialization, add it to the scope stack. 3387 if (New->getDeclName() && AddToScope && 3388 !(D.isRedeclaration() && New->isInvalidDecl())) 3389 PushOnScopeChains(New, S); 3390 3391 return New; 3392} 3393 3394/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 3395/// types into constant array types in certain situations which would otherwise 3396/// be errors (for GCC compatibility). 3397static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3398 ASTContext &Context, 3399 bool &SizeIsNegative, 3400 llvm::APSInt &Oversized) { 3401 // This method tries to turn a variable array into a constant 3402 // array even when the size isn't an ICE. This is necessary 3403 // for compatibility with code that depends on gcc's buggy 3404 // constant expression folding, like struct {char x[(int)(char*)2];} 3405 SizeIsNegative = false; 3406 Oversized = 0; 3407 3408 if (T->isDependentType()) 3409 return QualType(); 3410 3411 QualifierCollector Qs; 3412 const Type *Ty = Qs.strip(T); 3413 3414 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 3415 QualType Pointee = PTy->getPointeeType(); 3416 QualType FixedType = 3417 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 3418 Oversized); 3419 if (FixedType.isNull()) return FixedType; 3420 FixedType = Context.getPointerType(FixedType); 3421 return Qs.apply(Context, FixedType); 3422 } 3423 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 3424 QualType Inner = PTy->getInnerType(); 3425 QualType FixedType = 3426 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 3427 Oversized); 3428 if (FixedType.isNull()) return FixedType; 3429 FixedType = Context.getParenType(FixedType); 3430 return Qs.apply(Context, FixedType); 3431 } 3432 3433 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3434 if (!VLATy) 3435 return QualType(); 3436 // FIXME: We should probably handle this case 3437 if (VLATy->getElementType()->isVariablyModifiedType()) 3438 return QualType(); 3439 3440 Expr::EvalResult EvalResult; 3441 if (!VLATy->getSizeExpr() || 3442 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 3443 !EvalResult.Val.isInt()) 3444 return QualType(); 3445 3446 // Check whether the array size is negative. 3447 llvm::APSInt &Res = EvalResult.Val.getInt(); 3448 if (Res.isSigned() && Res.isNegative()) { 3449 SizeIsNegative = true; 3450 return QualType(); 3451 } 3452 3453 // Check whether the array is too large to be addressed. 3454 unsigned ActiveSizeBits 3455 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 3456 Res); 3457 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 3458 Oversized = Res; 3459 return QualType(); 3460 } 3461 3462 return Context.getConstantArrayType(VLATy->getElementType(), 3463 Res, ArrayType::Normal, 0); 3464} 3465 3466/// \brief Register the given locally-scoped external C declaration so 3467/// that it can be found later for redeclarations 3468void 3469Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 3470 const LookupResult &Previous, 3471 Scope *S) { 3472 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 3473 "Decl is not a locally-scoped decl!"); 3474 // Note that we have a locally-scoped external with this name. 3475 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 3476 3477 if (!Previous.isSingleResult()) 3478 return; 3479 3480 NamedDecl *PrevDecl = Previous.getFoundDecl(); 3481 3482 // If there was a previous declaration of this variable, it may be 3483 // in our identifier chain. Update the identifier chain with the new 3484 // declaration. 3485 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 3486 // The previous declaration was found on the identifer resolver 3487 // chain, so remove it from its scope. 3488 3489 if (S->isDeclScope(PrevDecl)) { 3490 // Special case for redeclarations in the SAME scope. 3491 // Because this declaration is going to be added to the identifier chain 3492 // later, we should temporarily take it OFF the chain. 3493 IdResolver.RemoveDecl(ND); 3494 3495 } else { 3496 // Find the scope for the original declaration. 3497 while (S && !S->isDeclScope(PrevDecl)) 3498 S = S->getParent(); 3499 } 3500 3501 if (S) 3502 S->RemoveDecl(PrevDecl); 3503 } 3504} 3505 3506llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 3507Sema::findLocallyScopedExternalDecl(DeclarationName Name) { 3508 if (ExternalSource) { 3509 // Load locally-scoped external decls from the external source. 3510 SmallVector<NamedDecl *, 4> Decls; 3511 ExternalSource->ReadLocallyScopedExternalDecls(Decls); 3512 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 3513 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3514 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName()); 3515 if (Pos == LocallyScopedExternalDecls.end()) 3516 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I]; 3517 } 3518 } 3519 3520 return LocallyScopedExternalDecls.find(Name); 3521} 3522 3523/// \brief Diagnose function specifiers on a declaration of an identifier that 3524/// does not identify a function. 3525void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 3526 // FIXME: We should probably indicate the identifier in question to avoid 3527 // confusion for constructs like "inline int a(), b;" 3528 if (D.getDeclSpec().isInlineSpecified()) 3529 Diag(D.getDeclSpec().getInlineSpecLoc(), 3530 diag::err_inline_non_function); 3531 3532 if (D.getDeclSpec().isVirtualSpecified()) 3533 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3534 diag::err_virtual_non_function); 3535 3536 if (D.getDeclSpec().isExplicitSpecified()) 3537 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3538 diag::err_explicit_non_function); 3539} 3540 3541NamedDecl* 3542Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 3543 TypeSourceInfo *TInfo, LookupResult &Previous) { 3544 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 3545 if (D.getCXXScopeSpec().isSet()) { 3546 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 3547 << D.getCXXScopeSpec().getRange(); 3548 D.setInvalidType(); 3549 // Pretend we didn't see the scope specifier. 3550 DC = CurContext; 3551 Previous.clear(); 3552 } 3553 3554 if (getLangOptions().CPlusPlus) { 3555 // Check that there are no default arguments (C++ only). 3556 CheckExtraCXXDefaultArguments(D); 3557 } 3558 3559 DiagnoseFunctionSpecifiers(D); 3560 3561 if (D.getDeclSpec().isThreadSpecified()) 3562 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3563 if (D.getDeclSpec().isConstexprSpecified()) 3564 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 3565 << 1; 3566 3567 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 3568 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 3569 << D.getName().getSourceRange(); 3570 return 0; 3571 } 3572 3573 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 3574 if (!NewTD) return 0; 3575 3576 // Handle attributes prior to checking for duplicates in MergeVarDecl 3577 ProcessDeclAttributes(S, NewTD, D); 3578 3579 CheckTypedefForVariablyModifiedType(S, NewTD); 3580 3581 bool Redeclaration = D.isRedeclaration(); 3582 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 3583 D.setRedeclaration(Redeclaration); 3584 return ND; 3585} 3586 3587void 3588Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 3589 // C99 6.7.7p2: If a typedef name specifies a variably modified type 3590 // then it shall have block scope. 3591 // Note that variably modified types must be fixed before merging the decl so 3592 // that redeclarations will match. 3593 QualType T = NewTD->getUnderlyingType(); 3594 if (T->isVariablyModifiedType()) { 3595 getCurFunction()->setHasBranchProtectedScope(); 3596 3597 if (S->getFnParent() == 0) { 3598 bool SizeIsNegative; 3599 llvm::APSInt Oversized; 3600 QualType FixedTy = 3601 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 3602 Oversized); 3603 if (!FixedTy.isNull()) { 3604 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 3605 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 3606 } else { 3607 if (SizeIsNegative) 3608 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 3609 else if (T->isVariableArrayType()) 3610 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 3611 else if (Oversized.getBoolValue()) 3612 Diag(NewTD->getLocation(), diag::err_array_too_large) 3613 << Oversized.toString(10); 3614 else 3615 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 3616 NewTD->setInvalidDecl(); 3617 } 3618 } 3619 } 3620} 3621 3622 3623/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 3624/// declares a typedef-name, either using the 'typedef' type specifier or via 3625/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 3626NamedDecl* 3627Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 3628 LookupResult &Previous, bool &Redeclaration) { 3629 // Merge the decl with the existing one if appropriate. If the decl is 3630 // in an outer scope, it isn't the same thing. 3631 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 3632 /*ExplicitInstantiationOrSpecialization=*/false); 3633 if (!Previous.empty()) { 3634 Redeclaration = true; 3635 MergeTypedefNameDecl(NewTD, Previous); 3636 } 3637 3638 // If this is the C FILE type, notify the AST context. 3639 if (IdentifierInfo *II = NewTD->getIdentifier()) 3640 if (!NewTD->isInvalidDecl() && 3641 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 3642 if (II->isStr("FILE")) 3643 Context.setFILEDecl(NewTD); 3644 else if (II->isStr("jmp_buf")) 3645 Context.setjmp_bufDecl(NewTD); 3646 else if (II->isStr("sigjmp_buf")) 3647 Context.setsigjmp_bufDecl(NewTD); 3648 else if (II->isStr("__builtin_va_list")) 3649 Context.setBuiltinVaListType(Context.getTypedefType(NewTD)); 3650 } 3651 3652 return NewTD; 3653} 3654 3655/// \brief Determines whether the given declaration is an out-of-scope 3656/// previous declaration. 3657/// 3658/// This routine should be invoked when name lookup has found a 3659/// previous declaration (PrevDecl) that is not in the scope where a 3660/// new declaration by the same name is being introduced. If the new 3661/// declaration occurs in a local scope, previous declarations with 3662/// linkage may still be considered previous declarations (C99 3663/// 6.2.2p4-5, C++ [basic.link]p6). 3664/// 3665/// \param PrevDecl the previous declaration found by name 3666/// lookup 3667/// 3668/// \param DC the context in which the new declaration is being 3669/// declared. 3670/// 3671/// \returns true if PrevDecl is an out-of-scope previous declaration 3672/// for a new delcaration with the same name. 3673static bool 3674isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 3675 ASTContext &Context) { 3676 if (!PrevDecl) 3677 return false; 3678 3679 if (!PrevDecl->hasLinkage()) 3680 return false; 3681 3682 if (Context.getLangOptions().CPlusPlus) { 3683 // C++ [basic.link]p6: 3684 // If there is a visible declaration of an entity with linkage 3685 // having the same name and type, ignoring entities declared 3686 // outside the innermost enclosing namespace scope, the block 3687 // scope declaration declares that same entity and receives the 3688 // linkage of the previous declaration. 3689 DeclContext *OuterContext = DC->getRedeclContext(); 3690 if (!OuterContext->isFunctionOrMethod()) 3691 // This rule only applies to block-scope declarations. 3692 return false; 3693 3694 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 3695 if (PrevOuterContext->isRecord()) 3696 // We found a member function: ignore it. 3697 return false; 3698 3699 // Find the innermost enclosing namespace for the new and 3700 // previous declarations. 3701 OuterContext = OuterContext->getEnclosingNamespaceContext(); 3702 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 3703 3704 // The previous declaration is in a different namespace, so it 3705 // isn't the same function. 3706 if (!OuterContext->Equals(PrevOuterContext)) 3707 return false; 3708 } 3709 3710 return true; 3711} 3712 3713static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 3714 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3715 if (!SS.isSet()) return; 3716 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 3717} 3718 3719bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 3720 QualType type = decl->getType(); 3721 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 3722 if (lifetime == Qualifiers::OCL_Autoreleasing) { 3723 // Various kinds of declaration aren't allowed to be __autoreleasing. 3724 unsigned kind = -1U; 3725 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3726 if (var->hasAttr<BlocksAttr>()) 3727 kind = 0; // __block 3728 else if (!var->hasLocalStorage()) 3729 kind = 1; // global 3730 } else if (isa<ObjCIvarDecl>(decl)) { 3731 kind = 3; // ivar 3732 } else if (isa<FieldDecl>(decl)) { 3733 kind = 2; // field 3734 } 3735 3736 if (kind != -1U) { 3737 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 3738 << kind; 3739 } 3740 } else if (lifetime == Qualifiers::OCL_None) { 3741 // Try to infer lifetime. 3742 if (!type->isObjCLifetimeType()) 3743 return false; 3744 3745 lifetime = type->getObjCARCImplicitLifetime(); 3746 type = Context.getLifetimeQualifiedType(type, lifetime); 3747 decl->setType(type); 3748 } 3749 3750 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3751 // Thread-local variables cannot have lifetime. 3752 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 3753 var->isThreadSpecified()) { 3754 Diag(var->getLocation(), diag::err_arc_thread_ownership) 3755 << var->getType(); 3756 return true; 3757 } 3758 } 3759 3760 return false; 3761} 3762 3763NamedDecl* 3764Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 3765 TypeSourceInfo *TInfo, LookupResult &Previous, 3766 MultiTemplateParamsArg TemplateParamLists) { 3767 QualType R = TInfo->getType(); 3768 DeclarationName Name = GetNameForDeclarator(D).getName(); 3769 3770 // Check that there are no default arguments (C++ only). 3771 if (getLangOptions().CPlusPlus) 3772 CheckExtraCXXDefaultArguments(D); 3773 3774 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 3775 assert(SCSpec != DeclSpec::SCS_typedef && 3776 "Parser allowed 'typedef' as storage class VarDecl."); 3777 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3778 if (SCSpec == DeclSpec::SCS_mutable) { 3779 // mutable can only appear on non-static class members, so it's always 3780 // an error here 3781 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 3782 D.setInvalidType(); 3783 SC = SC_None; 3784 } 3785 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 3786 VarDecl::StorageClass SCAsWritten 3787 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3788 3789 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3790 if (!II) { 3791 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 3792 << Name; 3793 return 0; 3794 } 3795 3796 DiagnoseFunctionSpecifiers(D); 3797 3798 if (!DC->isRecord() && S->getFnParent() == 0) { 3799 // C99 6.9p2: The storage-class specifiers auto and register shall not 3800 // appear in the declaration specifiers in an external declaration. 3801 if (SC == SC_Auto || SC == SC_Register) { 3802 3803 // If this is a register variable with an asm label specified, then this 3804 // is a GNU extension. 3805 if (SC == SC_Register && D.getAsmLabel()) 3806 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 3807 else 3808 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 3809 D.setInvalidType(); 3810 } 3811 } 3812 3813 if (getLangOptions().OpenCL) { 3814 // Set up the special work-group-local storage class for variables in the 3815 // OpenCL __local address space. 3816 if (R.getAddressSpace() == LangAS::opencl_local) 3817 SC = SC_OpenCLWorkGroupLocal; 3818 } 3819 3820 bool isExplicitSpecialization = false; 3821 VarDecl *NewVD; 3822 if (!getLangOptions().CPlusPlus) { 3823 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3824 D.getIdentifierLoc(), II, 3825 R, TInfo, SC, SCAsWritten); 3826 3827 if (D.isInvalidType()) 3828 NewVD->setInvalidDecl(); 3829 } else { 3830 if (DC->isRecord() && !CurContext->isRecord()) { 3831 // This is an out-of-line definition of a static data member. 3832 if (SC == SC_Static) { 3833 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3834 diag::err_static_out_of_line) 3835 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3836 } else if (SC == SC_None) 3837 SC = SC_Static; 3838 } 3839 if (SC == SC_Static) { 3840 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 3841 if (RD->isLocalClass()) 3842 Diag(D.getIdentifierLoc(), 3843 diag::err_static_data_member_not_allowed_in_local_class) 3844 << Name << RD->getDeclName(); 3845 3846 // C++ [class.union]p1: If a union contains a static data member, 3847 // the program is ill-formed. 3848 // 3849 // We also disallow static data members in anonymous structs. 3850 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName())) 3851 Diag(D.getIdentifierLoc(), 3852 diag::err_static_data_member_not_allowed_in_union_or_anon_struct) 3853 << Name << RD->isUnion(); 3854 } 3855 } 3856 3857 // Match up the template parameter lists with the scope specifier, then 3858 // determine whether we have a template or a template specialization. 3859 isExplicitSpecialization = false; 3860 bool Invalid = false; 3861 if (TemplateParameterList *TemplateParams 3862 = MatchTemplateParametersToScopeSpecifier( 3863 D.getDeclSpec().getSourceRange().getBegin(), 3864 D.getIdentifierLoc(), 3865 D.getCXXScopeSpec(), 3866 TemplateParamLists.get(), 3867 TemplateParamLists.size(), 3868 /*never a friend*/ false, 3869 isExplicitSpecialization, 3870 Invalid)) { 3871 if (TemplateParams->size() > 0) { 3872 // There is no such thing as a variable template. 3873 Diag(D.getIdentifierLoc(), diag::err_template_variable) 3874 << II 3875 << SourceRange(TemplateParams->getTemplateLoc(), 3876 TemplateParams->getRAngleLoc()); 3877 return 0; 3878 } else { 3879 // There is an extraneous 'template<>' for this variable. Complain 3880 // about it, but allow the declaration of the variable. 3881 Diag(TemplateParams->getTemplateLoc(), 3882 diag::err_template_variable_noparams) 3883 << II 3884 << SourceRange(TemplateParams->getTemplateLoc(), 3885 TemplateParams->getRAngleLoc()); 3886 } 3887 } 3888 3889 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3890 D.getIdentifierLoc(), II, 3891 R, TInfo, SC, SCAsWritten); 3892 3893 // If this decl has an auto type in need of deduction, make a note of the 3894 // Decl so we can diagnose uses of it in its own initializer. 3895 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 3896 R->getContainedAutoType()) 3897 ParsingInitForAutoVars.insert(NewVD); 3898 3899 if (D.isInvalidType() || Invalid) 3900 NewVD->setInvalidDecl(); 3901 3902 SetNestedNameSpecifier(NewVD, D); 3903 3904 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 3905 NewVD->setTemplateParameterListsInfo(Context, 3906 TemplateParamLists.size(), 3907 TemplateParamLists.release()); 3908 } 3909 3910 if (D.getDeclSpec().isConstexprSpecified()) { 3911 // FIXME: once we know whether there's an initializer, apply this to 3912 // static data members too. 3913 if (!NewVD->isStaticDataMember() && 3914 !NewVD->isThisDeclarationADefinition()) { 3915 // 'constexpr' is redundant and ill-formed on a non-defining declaration 3916 // of a variable. Suggest replacing it with 'const' if appropriate. 3917 SourceLocation ConstexprLoc = D.getDeclSpec().getConstexprSpecLoc(); 3918 SourceRange ConstexprRange(ConstexprLoc, ConstexprLoc); 3919 // If the declarator is complex, we need to move the keyword to the 3920 // innermost chunk as we switch it from 'constexpr' to 'const'. 3921 int Kind = DeclaratorChunk::Paren; 3922 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3923 Kind = D.getTypeObject(I).Kind; 3924 if (Kind != DeclaratorChunk::Paren) 3925 break; 3926 } 3927 if ((D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) || 3928 Kind == DeclaratorChunk::Reference) 3929 Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl) 3930 << FixItHint::CreateRemoval(ConstexprRange); 3931 else if (Kind == DeclaratorChunk::Paren) 3932 Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl) 3933 << FixItHint::CreateReplacement(ConstexprRange, "const"); 3934 else 3935 Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl) 3936 << FixItHint::CreateRemoval(ConstexprRange) 3937 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "const "); 3938 } else { 3939 NewVD->setConstexpr(true); 3940 } 3941 } 3942 } 3943 3944 // Set the lexical context. If the declarator has a C++ scope specifier, the 3945 // lexical context will be different from the semantic context. 3946 NewVD->setLexicalDeclContext(CurContext); 3947 3948 if (D.getDeclSpec().isThreadSpecified()) { 3949 if (NewVD->hasLocalStorage()) 3950 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 3951 else if (!Context.getTargetInfo().isTLSSupported()) 3952 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 3953 else 3954 NewVD->setThreadSpecified(true); 3955 } 3956 3957 if (D.getDeclSpec().isModulePrivateSpecified()) { 3958 if (isExplicitSpecialization) 3959 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 3960 << 2 3961 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 3962 else if (NewVD->hasLocalStorage()) 3963 Diag(NewVD->getLocation(), diag::err_module_private_local) 3964 << 0 << NewVD->getDeclName() 3965 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 3966 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 3967 else 3968 NewVD->setModulePrivate(); 3969 } 3970 3971 // Handle attributes prior to checking for duplicates in MergeVarDecl 3972 ProcessDeclAttributes(S, NewVD, D); 3973 3974 // In auto-retain/release, infer strong retension for variables of 3975 // retainable type. 3976 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 3977 NewVD->setInvalidDecl(); 3978 3979 // Handle GNU asm-label extension (encoded as an attribute). 3980 if (Expr *E = (Expr*)D.getAsmLabel()) { 3981 // The parser guarantees this is a string. 3982 StringLiteral *SE = cast<StringLiteral>(E); 3983 StringRef Label = SE->getString(); 3984 if (S->getFnParent() != 0) { 3985 switch (SC) { 3986 case SC_None: 3987 case SC_Auto: 3988 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 3989 break; 3990 case SC_Register: 3991 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 3992 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 3993 break; 3994 case SC_Static: 3995 case SC_Extern: 3996 case SC_PrivateExtern: 3997 case SC_OpenCLWorkGroupLocal: 3998 break; 3999 } 4000 } 4001 4002 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4003 Context, Label)); 4004 } 4005 4006 // Diagnose shadowed variables before filtering for scope. 4007 if (!D.getCXXScopeSpec().isSet()) 4008 CheckShadow(S, NewVD, Previous); 4009 4010 // Don't consider existing declarations that are in a different 4011 // scope and are out-of-semantic-context declarations (if the new 4012 // declaration has linkage). 4013 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 4014 isExplicitSpecialization); 4015 4016 if (!getLangOptions().CPlusPlus) { 4017 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4018 } else { 4019 // Merge the decl with the existing one if appropriate. 4020 if (!Previous.empty()) { 4021 if (Previous.isSingleResult() && 4022 isa<FieldDecl>(Previous.getFoundDecl()) && 4023 D.getCXXScopeSpec().isSet()) { 4024 // The user tried to define a non-static data member 4025 // out-of-line (C++ [dcl.meaning]p1). 4026 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 4027 << D.getCXXScopeSpec().getRange(); 4028 Previous.clear(); 4029 NewVD->setInvalidDecl(); 4030 } 4031 } else if (D.getCXXScopeSpec().isSet()) { 4032 // No previous declaration in the qualifying scope. 4033 Diag(D.getIdentifierLoc(), diag::err_no_member) 4034 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 4035 << D.getCXXScopeSpec().getRange(); 4036 NewVD->setInvalidDecl(); 4037 } 4038 4039 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4040 4041 // This is an explicit specialization of a static data member. Check it. 4042 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 4043 CheckMemberSpecialization(NewVD, Previous)) 4044 NewVD->setInvalidDecl(); 4045 } 4046 4047 // attributes declared post-definition are currently ignored 4048 // FIXME: This should be handled in attribute merging, not 4049 // here. 4050 if (Previous.isSingleResult()) { 4051 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4052 if (Def && (Def = Def->getDefinition()) && 4053 Def != NewVD && D.hasAttributes()) { 4054 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 4055 Diag(Def->getLocation(), diag::note_previous_definition); 4056 } 4057 } 4058 4059 // If this is a locally-scoped extern C variable, update the map of 4060 // such variables. 4061 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 4062 !NewVD->isInvalidDecl()) 4063 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 4064 4065 // If there's a #pragma GCC visibility in scope, and this isn't a class 4066 // member, set the visibility of this variable. 4067 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 4068 AddPushedVisibilityAttribute(NewVD); 4069 4070 MarkUnusedFileScopedDecl(NewVD); 4071 4072 return NewVD; 4073} 4074 4075/// \brief Diagnose variable or built-in function shadowing. Implements 4076/// -Wshadow. 4077/// 4078/// This method is called whenever a VarDecl is added to a "useful" 4079/// scope. 4080/// 4081/// \param S the scope in which the shadowing name is being declared 4082/// \param R the lookup of the name 4083/// 4084void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 4085 // Return if warning is ignored. 4086 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 4087 DiagnosticsEngine::Ignored) 4088 return; 4089 4090 // Don't diagnose declarations at file scope. 4091 if (D->hasGlobalStorage()) 4092 return; 4093 4094 DeclContext *NewDC = D->getDeclContext(); 4095 4096 // Only diagnose if we're shadowing an unambiguous field or variable. 4097 if (R.getResultKind() != LookupResult::Found) 4098 return; 4099 4100 NamedDecl* ShadowedDecl = R.getFoundDecl(); 4101 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 4102 return; 4103 4104 // Fields are not shadowed by variables in C++ static methods. 4105 if (isa<FieldDecl>(ShadowedDecl)) 4106 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 4107 if (MD->isStatic()) 4108 return; 4109 4110 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 4111 if (shadowedVar->isExternC()) { 4112 // For shadowing external vars, make sure that we point to the global 4113 // declaration, not a locally scoped extern declaration. 4114 for (VarDecl::redecl_iterator 4115 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 4116 I != E; ++I) 4117 if (I->isFileVarDecl()) { 4118 ShadowedDecl = *I; 4119 break; 4120 } 4121 } 4122 4123 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 4124 4125 // Only warn about certain kinds of shadowing for class members. 4126 if (NewDC && NewDC->isRecord()) { 4127 // In particular, don't warn about shadowing non-class members. 4128 if (!OldDC->isRecord()) 4129 return; 4130 4131 // TODO: should we warn about static data members shadowing 4132 // static data members from base classes? 4133 4134 // TODO: don't diagnose for inaccessible shadowed members. 4135 // This is hard to do perfectly because we might friend the 4136 // shadowing context, but that's just a false negative. 4137 } 4138 4139 // Determine what kind of declaration we're shadowing. 4140 unsigned Kind; 4141 if (isa<RecordDecl>(OldDC)) { 4142 if (isa<FieldDecl>(ShadowedDecl)) 4143 Kind = 3; // field 4144 else 4145 Kind = 2; // static data member 4146 } else if (OldDC->isFileContext()) 4147 Kind = 1; // global 4148 else 4149 Kind = 0; // local 4150 4151 DeclarationName Name = R.getLookupName(); 4152 4153 // Emit warning and note. 4154 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 4155 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 4156} 4157 4158/// \brief Check -Wshadow without the advantage of a previous lookup. 4159void Sema::CheckShadow(Scope *S, VarDecl *D) { 4160 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 4161 DiagnosticsEngine::Ignored) 4162 return; 4163 4164 LookupResult R(*this, D->getDeclName(), D->getLocation(), 4165 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4166 LookupName(R, S); 4167 CheckShadow(S, D, R); 4168} 4169 4170/// \brief Perform semantic checking on a newly-created variable 4171/// declaration. 4172/// 4173/// This routine performs all of the type-checking required for a 4174/// variable declaration once it has been built. It is used both to 4175/// check variables after they have been parsed and their declarators 4176/// have been translated into a declaration, and to check variables 4177/// that have been instantiated from a template. 4178/// 4179/// Sets NewVD->isInvalidDecl() if an error was encountered. 4180/// 4181/// Returns true if the variable declaration is a redeclaration. 4182bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 4183 LookupResult &Previous) { 4184 // If the decl is already known invalid, don't check it. 4185 if (NewVD->isInvalidDecl()) 4186 return false; 4187 4188 QualType T = NewVD->getType(); 4189 4190 if (T->isObjCObjectType()) { 4191 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 4192 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 4193 T = Context.getObjCObjectPointerType(T); 4194 NewVD->setType(T); 4195 } 4196 4197 // Emit an error if an address space was applied to decl with local storage. 4198 // This includes arrays of objects with address space qualifiers, but not 4199 // automatic variables that point to other address spaces. 4200 // ISO/IEC TR 18037 S5.1.2 4201 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 4202 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 4203 NewVD->setInvalidDecl(); 4204 return false; 4205 } 4206 4207 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 4208 && !NewVD->hasAttr<BlocksAttr>()) { 4209 if (getLangOptions().getGC() != LangOptions::NonGC) 4210 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 4211 else 4212 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 4213 } 4214 4215 bool isVM = T->isVariablyModifiedType(); 4216 if (isVM || NewVD->hasAttr<CleanupAttr>() || 4217 NewVD->hasAttr<BlocksAttr>()) 4218 getCurFunction()->setHasBranchProtectedScope(); 4219 4220 if ((isVM && NewVD->hasLinkage()) || 4221 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 4222 bool SizeIsNegative; 4223 llvm::APSInt Oversized; 4224 QualType FixedTy = 4225 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 4226 Oversized); 4227 4228 if (FixedTy.isNull() && T->isVariableArrayType()) { 4229 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 4230 // FIXME: This won't give the correct result for 4231 // int a[10][n]; 4232 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 4233 4234 if (NewVD->isFileVarDecl()) 4235 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 4236 << SizeRange; 4237 else if (NewVD->getStorageClass() == SC_Static) 4238 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 4239 << SizeRange; 4240 else 4241 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 4242 << SizeRange; 4243 NewVD->setInvalidDecl(); 4244 return false; 4245 } 4246 4247 if (FixedTy.isNull()) { 4248 if (NewVD->isFileVarDecl()) 4249 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 4250 else 4251 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 4252 NewVD->setInvalidDecl(); 4253 return false; 4254 } 4255 4256 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 4257 NewVD->setType(FixedTy); 4258 } 4259 4260 if (Previous.empty() && NewVD->isExternC()) { 4261 // Since we did not find anything by this name and we're declaring 4262 // an extern "C" variable, look for a non-visible extern "C" 4263 // declaration with the same name. 4264 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4265 = findLocallyScopedExternalDecl(NewVD->getDeclName()); 4266 if (Pos != LocallyScopedExternalDecls.end()) 4267 Previous.addDecl(Pos->second); 4268 } 4269 4270 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 4271 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 4272 << T; 4273 NewVD->setInvalidDecl(); 4274 return false; 4275 } 4276 4277 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 4278 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 4279 NewVD->setInvalidDecl(); 4280 return false; 4281 } 4282 4283 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 4284 Diag(NewVD->getLocation(), diag::err_block_on_vm); 4285 NewVD->setInvalidDecl(); 4286 return false; 4287 } 4288 4289 // Function pointers and references cannot have qualified function type, only 4290 // function pointer-to-members can do that. 4291 QualType Pointee; 4292 unsigned PtrOrRef = 0; 4293 if (const PointerType *Ptr = T->getAs<PointerType>()) 4294 Pointee = Ptr->getPointeeType(); 4295 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) { 4296 Pointee = Ref->getPointeeType(); 4297 PtrOrRef = 1; 4298 } 4299 if (!Pointee.isNull() && Pointee->isFunctionProtoType() && 4300 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) { 4301 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer) 4302 << PtrOrRef; 4303 NewVD->setInvalidDecl(); 4304 return false; 4305 } 4306 4307 if (!Previous.empty()) { 4308 MergeVarDecl(NewVD, Previous); 4309 return true; 4310 } 4311 return false; 4312} 4313 4314/// \brief Data used with FindOverriddenMethod 4315struct FindOverriddenMethodData { 4316 Sema *S; 4317 CXXMethodDecl *Method; 4318}; 4319 4320/// \brief Member lookup function that determines whether a given C++ 4321/// method overrides a method in a base class, to be used with 4322/// CXXRecordDecl::lookupInBases(). 4323static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 4324 CXXBasePath &Path, 4325 void *UserData) { 4326 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4327 4328 FindOverriddenMethodData *Data 4329 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 4330 4331 DeclarationName Name = Data->Method->getDeclName(); 4332 4333 // FIXME: Do we care about other names here too? 4334 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4335 // We really want to find the base class destructor here. 4336 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 4337 CanQualType CT = Data->S->Context.getCanonicalType(T); 4338 4339 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 4340 } 4341 4342 for (Path.Decls = BaseRecord->lookup(Name); 4343 Path.Decls.first != Path.Decls.second; 4344 ++Path.Decls.first) { 4345 NamedDecl *D = *Path.Decls.first; 4346 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4347 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 4348 return true; 4349 } 4350 } 4351 4352 return false; 4353} 4354 4355/// AddOverriddenMethods - See if a method overrides any in the base classes, 4356/// and if so, check that it's a valid override and remember it. 4357bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4358 // Look for virtual methods in base classes that this method might override. 4359 CXXBasePaths Paths; 4360 FindOverriddenMethodData Data; 4361 Data.Method = MD; 4362 Data.S = this; 4363 bool AddedAny = false; 4364 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 4365 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 4366 E = Paths.found_decls_end(); I != E; ++I) { 4367 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 4368 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 4369 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 4370 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 4371 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 4372 AddedAny = true; 4373 } 4374 } 4375 } 4376 } 4377 4378 return AddedAny; 4379} 4380 4381namespace { 4382 // Struct for holding all of the extra arguments needed by 4383 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 4384 struct ActOnFDArgs { 4385 Scope *S; 4386 Declarator &D; 4387 MultiTemplateParamsArg TemplateParamLists; 4388 bool AddToScope; 4389 }; 4390} 4391 4392/// \brief Generate diagnostics for an invalid function redeclaration. 4393/// 4394/// This routine handles generating the diagnostic messages for an invalid 4395/// function redeclaration, including finding possible similar declarations 4396/// or performing typo correction if there are no previous declarations with 4397/// the same name. 4398/// 4399/// Returns a NamedDecl iff typo correction was performed and substituting in 4400/// the new declaration name does not cause new errors. 4401static NamedDecl* DiagnoseInvalidRedeclaration( 4402 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 4403 ActOnFDArgs &ExtraArgs) { 4404 NamedDecl *Result = NULL; 4405 DeclarationName Name = NewFD->getDeclName(); 4406 DeclContext *NewDC = NewFD->getDeclContext(); 4407 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 4408 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4409 llvm::SmallVector<unsigned, 1> MismatchedParams; 4410 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches; 4411 TypoCorrection Correction; 4412 bool isFriendDecl = (SemaRef.getLangOptions().CPlusPlus && 4413 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 4414 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 4415 : diag::err_member_def_does_not_match; 4416 4417 NewFD->setInvalidDecl(); 4418 SemaRef.LookupQualifiedName(Prev, NewDC); 4419 assert(!Prev.isAmbiguous() && 4420 "Cannot have an ambiguity in previous-declaration lookup"); 4421 if (!Prev.empty()) { 4422 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 4423 Func != FuncEnd; ++Func) { 4424 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 4425 if (FD && 4426 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 4427 // Add 1 to the index so that 0 can mean the mismatch didn't 4428 // involve a parameter 4429 unsigned ParamNum = 4430 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 4431 NearMatches.push_back(std::make_pair(FD, ParamNum)); 4432 } 4433 } 4434 // If the qualified name lookup yielded nothing, try typo correction 4435 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 4436 Prev.getLookupKind(), 0, 0, NewDC)) && 4437 Correction.getCorrection() != Name) { 4438 // Trap errors. 4439 Sema::SFINAETrap Trap(SemaRef); 4440 4441 // Set up everything for the call to ActOnFunctionDeclarator 4442 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 4443 ExtraArgs.D.getIdentifierLoc()); 4444 Previous.clear(); 4445 Previous.setLookupName(Correction.getCorrection()); 4446 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 4447 CDeclEnd = Correction.end(); 4448 CDecl != CDeclEnd; ++CDecl) { 4449 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 4450 if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD, 4451 MismatchedParams)) { 4452 Previous.addDecl(FD); 4453 } 4454 } 4455 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 4456 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 4457 // pieces need to verify the typo-corrected C++ declaraction and hopefully 4458 // eliminate the need for the parameter pack ExtraArgs. 4459 Result = SemaRef.ActOnFunctionDeclarator(ExtraArgs.S, ExtraArgs.D, 4460 NewFD->getDeclContext(), 4461 NewFD->getTypeSourceInfo(), 4462 Previous, 4463 ExtraArgs.TemplateParamLists, 4464 ExtraArgs.AddToScope); 4465 if (Trap.hasErrorOccurred()) { 4466 // Pretend the typo correction never occurred 4467 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 4468 ExtraArgs.D.getIdentifierLoc()); 4469 ExtraArgs.D.setRedeclaration(wasRedeclaration); 4470 Previous.clear(); 4471 Previous.setLookupName(Name); 4472 Result = NULL; 4473 } else { 4474 for (LookupResult::iterator Func = Previous.begin(), 4475 FuncEnd = Previous.end(); 4476 Func != FuncEnd; ++Func) { 4477 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 4478 NearMatches.push_back(std::make_pair(FD, 0)); 4479 } 4480 } 4481 if (NearMatches.empty()) { 4482 // Ignore the correction if it didn't yield any close FunctionDecl matches 4483 Correction = TypoCorrection(); 4484 } else { 4485 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 4486 : diag::err_member_def_does_not_match_suggest; 4487 } 4488 } 4489 4490 if (Correction) 4491 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 4492 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOptions()) 4493 << FixItHint::CreateReplacement( 4494 NewFD->getLocation(), 4495 Correction.getAsString(SemaRef.getLangOptions())); 4496 else 4497 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 4498 << Name << NewDC << NewFD->getLocation(); 4499 4500 bool NewFDisConst = false; 4501 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 4502 NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const; 4503 4504 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator 4505 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 4506 NearMatch != NearMatchEnd; ++NearMatch) { 4507 FunctionDecl *FD = NearMatch->first; 4508 bool FDisConst = false; 4509 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 4510 FDisConst = MD->getTypeQualifiers() & Qualifiers::Const; 4511 4512 if (unsigned Idx = NearMatch->second) { 4513 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 4514 SemaRef.Diag(FDParam->getTypeSpecStartLoc(), 4515 diag::note_member_def_close_param_match) 4516 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 4517 } else if (Correction) { 4518 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 4519 << Correction.getQuoted(SemaRef.getLangOptions()); 4520 } else if (FDisConst != NewFDisConst) { 4521 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 4522 << NewFDisConst << FD->getSourceRange().getEnd(); 4523 } else 4524 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 4525 } 4526 return Result; 4527} 4528 4529static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 4530 Declarator &D) { 4531 switch (D.getDeclSpec().getStorageClassSpec()) { 4532 default: llvm_unreachable("Unknown storage class!"); 4533 case DeclSpec::SCS_auto: 4534 case DeclSpec::SCS_register: 4535 case DeclSpec::SCS_mutable: 4536 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4537 diag::err_typecheck_sclass_func); 4538 D.setInvalidType(); 4539 break; 4540 case DeclSpec::SCS_unspecified: break; 4541 case DeclSpec::SCS_extern: return SC_Extern; 4542 case DeclSpec::SCS_static: { 4543 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 4544 // C99 6.7.1p5: 4545 // The declaration of an identifier for a function that has 4546 // block scope shall have no explicit storage-class specifier 4547 // other than extern 4548 // See also (C++ [dcl.stc]p4). 4549 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4550 diag::err_static_block_func); 4551 break; 4552 } else 4553 return SC_Static; 4554 } 4555 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4556 } 4557 4558 // No explicit storage class has already been returned 4559 return SC_None; 4560} 4561 4562static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 4563 DeclContext *DC, QualType &R, 4564 TypeSourceInfo *TInfo, 4565 FunctionDecl::StorageClass SC, 4566 bool &IsVirtualOkay) { 4567 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 4568 DeclarationName Name = NameInfo.getName(); 4569 4570 FunctionDecl *NewFD = 0; 4571 bool isInline = D.getDeclSpec().isInlineSpecified(); 4572 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4573 FunctionDecl::StorageClass SCAsWritten 4574 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 4575 4576 if (!SemaRef.getLangOptions().CPlusPlus) { 4577 // Determine whether the function was written with a 4578 // prototype. This true when: 4579 // - there is a prototype in the declarator, or 4580 // - the type R of the function is some kind of typedef or other reference 4581 // to a type name (which eventually refers to a function type). 4582 bool HasPrototype = 4583 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 4584 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 4585 4586 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 4587 D.getSourceRange().getBegin(), NameInfo, R, 4588 TInfo, SC, SCAsWritten, isInline, 4589 HasPrototype); 4590 if (D.isInvalidType()) 4591 NewFD->setInvalidDecl(); 4592 4593 // Set the lexical context. 4594 NewFD->setLexicalDeclContext(SemaRef.CurContext); 4595 4596 return NewFD; 4597 } 4598 4599 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 4600 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 4601 4602 // Check that the return type is not an abstract class type. 4603 // For record types, this is done by the AbstractClassUsageDiagnoser once 4604 // the class has been completely parsed. 4605 if (!DC->isRecord() && 4606 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 4607 R->getAs<FunctionType>()->getResultType(), 4608 diag::err_abstract_type_in_decl, 4609 SemaRef.AbstractReturnType)) 4610 D.setInvalidType(); 4611 4612 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 4613 // This is a C++ constructor declaration. 4614 assert(DC->isRecord() && 4615 "Constructors can only be declared in a member context"); 4616 4617 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 4618 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 4619 D.getSourceRange().getBegin(), NameInfo, 4620 R, TInfo, isExplicit, isInline, 4621 /*isImplicitlyDeclared=*/false, 4622 isConstexpr); 4623 4624 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4625 // This is a C++ destructor declaration. 4626 if (DC->isRecord()) { 4627 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 4628 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 4629 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 4630 SemaRef.Context, Record, 4631 D.getSourceRange().getBegin(), 4632 NameInfo, R, TInfo, isInline, 4633 /*isImplicitlyDeclared=*/false); 4634 4635 // If the class is complete, then we now create the implicit exception 4636 // specification. If the class is incomplete or dependent, we can't do 4637 // it yet. 4638 if (SemaRef.getLangOptions().CPlusPlus0x && !Record->isDependentType() && 4639 Record->getDefinition() && !Record->isBeingDefined() && 4640 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 4641 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 4642 } 4643 4644 IsVirtualOkay = true; 4645 return NewDD; 4646 4647 } else { 4648 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 4649 D.setInvalidType(); 4650 4651 // Create a FunctionDecl to satisfy the function definition parsing 4652 // code path. 4653 return FunctionDecl::Create(SemaRef.Context, DC, 4654 D.getSourceRange().getBegin(), 4655 D.getIdentifierLoc(), Name, R, TInfo, 4656 SC, SCAsWritten, isInline, 4657 /*hasPrototype=*/true, isConstexpr); 4658 } 4659 4660 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 4661 if (!DC->isRecord()) { 4662 SemaRef.Diag(D.getIdentifierLoc(), 4663 diag::err_conv_function_not_member); 4664 return 0; 4665 } 4666 4667 SemaRef.CheckConversionDeclarator(D, R, SC); 4668 IsVirtualOkay = true; 4669 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 4670 D.getSourceRange().getBegin(), NameInfo, 4671 R, TInfo, isInline, isExplicit, 4672 isConstexpr, SourceLocation()); 4673 4674 } else if (DC->isRecord()) { 4675 // If the name of the function is the same as the name of the record, 4676 // then this must be an invalid constructor that has a return type. 4677 // (The parser checks for a return type and makes the declarator a 4678 // constructor if it has no return type). 4679 if (Name.getAsIdentifierInfo() && 4680 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 4681 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 4682 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 4683 << SourceRange(D.getIdentifierLoc()); 4684 return 0; 4685 } 4686 4687 bool isStatic = SC == SC_Static; 4688 4689 // [class.free]p1: 4690 // Any allocation function for a class T is a static member 4691 // (even if not explicitly declared static). 4692 if (Name.getCXXOverloadedOperator() == OO_New || 4693 Name.getCXXOverloadedOperator() == OO_Array_New) 4694 isStatic = true; 4695 4696 // [class.free]p6 Any deallocation function for a class X is a static member 4697 // (even if not explicitly declared static). 4698 if (Name.getCXXOverloadedOperator() == OO_Delete || 4699 Name.getCXXOverloadedOperator() == OO_Array_Delete) 4700 isStatic = true; 4701 4702 IsVirtualOkay = !isStatic; 4703 4704 // This is a C++ method declaration. 4705 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 4706 D.getSourceRange().getBegin(), NameInfo, R, 4707 TInfo, isStatic, SCAsWritten, isInline, 4708 isConstexpr, SourceLocation()); 4709 4710 } else { 4711 // Determine whether the function was written with a 4712 // prototype. This true when: 4713 // - we're in C++ (where every function has a prototype), 4714 return FunctionDecl::Create(SemaRef.Context, DC, 4715 D.getSourceRange().getBegin(), 4716 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 4717 true/*HasPrototype*/, isConstexpr); 4718 } 4719} 4720 4721NamedDecl* 4722Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4723 TypeSourceInfo *TInfo, LookupResult &Previous, 4724 MultiTemplateParamsArg TemplateParamLists, 4725 bool &AddToScope) { 4726 QualType R = TInfo->getType(); 4727 4728 assert(R.getTypePtr()->isFunctionType()); 4729 4730 // TODO: consider using NameInfo for diagnostic. 4731 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4732 DeclarationName Name = NameInfo.getName(); 4733 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 4734 4735 if (D.getDeclSpec().isThreadSpecified()) 4736 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4737 4738 // Do not allow returning a objc interface by-value. 4739 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 4740 Diag(D.getIdentifierLoc(), 4741 diag::err_object_cannot_be_passed_returned_by_value) << 0 4742 << R->getAs<FunctionType>()->getResultType() 4743 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 4744 4745 QualType T = R->getAs<FunctionType>()->getResultType(); 4746 T = Context.getObjCObjectPointerType(T); 4747 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 4748 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4749 R = Context.getFunctionType(T, FPT->arg_type_begin(), 4750 FPT->getNumArgs(), EPI); 4751 } 4752 else if (isa<FunctionNoProtoType>(R)) 4753 R = Context.getFunctionNoProtoType(T); 4754 } 4755 4756 bool isFriend = false; 4757 FunctionTemplateDecl *FunctionTemplate = 0; 4758 bool isExplicitSpecialization = false; 4759 bool isFunctionTemplateSpecialization = false; 4760 bool isDependentClassScopeExplicitSpecialization = false; 4761 bool isVirtualOkay = false; 4762 4763 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 4764 isVirtualOkay); 4765 if (!NewFD) return 0; 4766 4767 if (getLangOptions().CPlusPlus) { 4768 bool isInline = D.getDeclSpec().isInlineSpecified(); 4769 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4770 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 4771 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 4772 isFriend = D.getDeclSpec().isFriendSpecified(); 4773 if (isFriend && !isInline && D.isFunctionDefinition()) { 4774 // C++ [class.friend]p5 4775 // A function can be defined in a friend declaration of a 4776 // class . . . . Such a function is implicitly inline. 4777 NewFD->setImplicitlyInline(); 4778 } 4779 4780 SetNestedNameSpecifier(NewFD, D); 4781 isExplicitSpecialization = false; 4782 isFunctionTemplateSpecialization = false; 4783 if (D.isInvalidType()) 4784 NewFD->setInvalidDecl(); 4785 4786 // Set the lexical context. If the declarator has a C++ 4787 // scope specifier, or is the object of a friend declaration, the 4788 // lexical context will be different from the semantic context. 4789 NewFD->setLexicalDeclContext(CurContext); 4790 4791 // Match up the template parameter lists with the scope specifier, then 4792 // determine whether we have a template or a template specialization. 4793 bool Invalid = false; 4794 if (TemplateParameterList *TemplateParams 4795 = MatchTemplateParametersToScopeSpecifier( 4796 D.getDeclSpec().getSourceRange().getBegin(), 4797 D.getIdentifierLoc(), 4798 D.getCXXScopeSpec(), 4799 TemplateParamLists.get(), 4800 TemplateParamLists.size(), 4801 isFriend, 4802 isExplicitSpecialization, 4803 Invalid)) { 4804 if (TemplateParams->size() > 0) { 4805 // This is a function template 4806 4807 // Check that we can declare a template here. 4808 if (CheckTemplateDeclScope(S, TemplateParams)) 4809 return 0; 4810 4811 // A destructor cannot be a template. 4812 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4813 Diag(NewFD->getLocation(), diag::err_destructor_template); 4814 return 0; 4815 } 4816 4817 // If we're adding a template to a dependent context, we may need to 4818 // rebuilding some of the types used within the template parameter list, 4819 // now that we know what the current instantiation is. 4820 if (DC->isDependentContext()) { 4821 ContextRAII SavedContext(*this, DC); 4822 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 4823 Invalid = true; 4824 } 4825 4826 4827 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 4828 NewFD->getLocation(), 4829 Name, TemplateParams, 4830 NewFD); 4831 FunctionTemplate->setLexicalDeclContext(CurContext); 4832 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 4833 4834 // For source fidelity, store the other template param lists. 4835 if (TemplateParamLists.size() > 1) { 4836 NewFD->setTemplateParameterListsInfo(Context, 4837 TemplateParamLists.size() - 1, 4838 TemplateParamLists.release()); 4839 } 4840 } else { 4841 // This is a function template specialization. 4842 isFunctionTemplateSpecialization = true; 4843 // For source fidelity, store all the template param lists. 4844 NewFD->setTemplateParameterListsInfo(Context, 4845 TemplateParamLists.size(), 4846 TemplateParamLists.release()); 4847 4848 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 4849 if (isFriend) { 4850 // We want to remove the "template<>", found here. 4851 SourceRange RemoveRange = TemplateParams->getSourceRange(); 4852 4853 // If we remove the template<> and the name is not a 4854 // template-id, we're actually silently creating a problem: 4855 // the friend declaration will refer to an untemplated decl, 4856 // and clearly the user wants a template specialization. So 4857 // we need to insert '<>' after the name. 4858 SourceLocation InsertLoc; 4859 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 4860 InsertLoc = D.getName().getSourceRange().getEnd(); 4861 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 4862 } 4863 4864 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 4865 << Name << RemoveRange 4866 << FixItHint::CreateRemoval(RemoveRange) 4867 << FixItHint::CreateInsertion(InsertLoc, "<>"); 4868 } 4869 } 4870 } 4871 else { 4872 // All template param lists were matched against the scope specifier: 4873 // this is NOT (an explicit specialization of) a template. 4874 if (TemplateParamLists.size() > 0) 4875 // For source fidelity, store all the template param lists. 4876 NewFD->setTemplateParameterListsInfo(Context, 4877 TemplateParamLists.size(), 4878 TemplateParamLists.release()); 4879 } 4880 4881 if (Invalid) { 4882 NewFD->setInvalidDecl(); 4883 if (FunctionTemplate) 4884 FunctionTemplate->setInvalidDecl(); 4885 } 4886 4887 // C++ [dcl.fct.spec]p5: 4888 // The virtual specifier shall only be used in declarations of 4889 // nonstatic class member functions that appear within a 4890 // member-specification of a class declaration; see 10.3. 4891 // 4892 if (isVirtual && !NewFD->isInvalidDecl()) { 4893 if (!isVirtualOkay) { 4894 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4895 diag::err_virtual_non_function); 4896 } else if (!CurContext->isRecord()) { 4897 // 'virtual' was specified outside of the class. 4898 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4899 diag::err_virtual_out_of_class) 4900 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4901 } else if (NewFD->getDescribedFunctionTemplate()) { 4902 // C++ [temp.mem]p3: 4903 // A member function template shall not be virtual. 4904 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4905 diag::err_virtual_member_function_template) 4906 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4907 } else { 4908 // Okay: Add virtual to the method. 4909 NewFD->setVirtualAsWritten(true); 4910 } 4911 } 4912 4913 // C++ [dcl.fct.spec]p3: 4914 // The inline specifier shall not appear on a block scope function 4915 // declaration. 4916 if (isInline && !NewFD->isInvalidDecl()) { 4917 if (CurContext->isFunctionOrMethod()) { 4918 // 'inline' is not allowed on block scope function declaration. 4919 Diag(D.getDeclSpec().getInlineSpecLoc(), 4920 diag::err_inline_declaration_block_scope) << Name 4921 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 4922 } 4923 } 4924 4925 // C++ [dcl.fct.spec]p6: 4926 // The explicit specifier shall be used only in the declaration of a 4927 // constructor or conversion function within its class definition; 4928 // see 12.3.1 and 12.3.2. 4929 if (isExplicit && !NewFD->isInvalidDecl()) { 4930 if (!CurContext->isRecord()) { 4931 // 'explicit' was specified outside of the class. 4932 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4933 diag::err_explicit_out_of_class) 4934 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4935 } else if (!isa<CXXConstructorDecl>(NewFD) && 4936 !isa<CXXConversionDecl>(NewFD)) { 4937 // 'explicit' was specified on a function that wasn't a constructor 4938 // or conversion function. 4939 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4940 diag::err_explicit_non_ctor_or_conv_function) 4941 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4942 } 4943 } 4944 4945 if (isConstexpr) { 4946 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors 4947 // are implicitly inline. 4948 NewFD->setImplicitlyInline(); 4949 4950 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to 4951 // be either constructors or to return a literal type. Therefore, 4952 // destructors cannot be declared constexpr. 4953 if (isa<CXXDestructorDecl>(NewFD)) 4954 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 4955 } 4956 4957 // If __module_private__ was specified, mark the function accordingly. 4958 if (D.getDeclSpec().isModulePrivateSpecified()) { 4959 if (isFunctionTemplateSpecialization) { 4960 SourceLocation ModulePrivateLoc 4961 = D.getDeclSpec().getModulePrivateSpecLoc(); 4962 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 4963 << 0 4964 << FixItHint::CreateRemoval(ModulePrivateLoc); 4965 } else { 4966 NewFD->setModulePrivate(); 4967 if (FunctionTemplate) 4968 FunctionTemplate->setModulePrivate(); 4969 } 4970 } 4971 4972 if (isFriend) { 4973 // For now, claim that the objects have no previous declaration. 4974 if (FunctionTemplate) { 4975 FunctionTemplate->setObjectOfFriendDecl(false); 4976 FunctionTemplate->setAccess(AS_public); 4977 } 4978 NewFD->setObjectOfFriendDecl(false); 4979 NewFD->setAccess(AS_public); 4980 } 4981 4982 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 4983 D.isFunctionDefinition()) { 4984 // A method is implicitly inline if it's defined in its class 4985 // definition. 4986 NewFD->setImplicitlyInline(); 4987 } 4988 4989 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 4990 !CurContext->isRecord()) { 4991 // C++ [class.static]p1: 4992 // A data or function member of a class may be declared static 4993 // in a class definition, in which case it is a static member of 4994 // the class. 4995 4996 // Complain about the 'static' specifier if it's on an out-of-line 4997 // member function definition. 4998 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4999 diag::err_static_out_of_line) 5000 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5001 } 5002 } 5003 5004 // Filter out previous declarations that don't match the scope. 5005 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 5006 isExplicitSpecialization || 5007 isFunctionTemplateSpecialization); 5008 5009 // Handle GNU asm-label extension (encoded as an attribute). 5010 if (Expr *E = (Expr*) D.getAsmLabel()) { 5011 // The parser guarantees this is a string. 5012 StringLiteral *SE = cast<StringLiteral>(E); 5013 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 5014 SE->getString())); 5015 } 5016 5017 // Copy the parameter declarations from the declarator D to the function 5018 // declaration NewFD, if they are available. First scavenge them into Params. 5019 SmallVector<ParmVarDecl*, 16> Params; 5020 if (D.isFunctionDeclarator()) { 5021 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5022 5023 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 5024 // function that takes no arguments, not a function that takes a 5025 // single void argument. 5026 // We let through "const void" here because Sema::GetTypeForDeclarator 5027 // already checks for that case. 5028 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5029 FTI.ArgInfo[0].Param && 5030 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 5031 // Empty arg list, don't push any params. 5032 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param); 5033 5034 // In C++, the empty parameter-type-list must be spelled "void"; a 5035 // typedef of void is not permitted. 5036 if (getLangOptions().CPlusPlus && 5037 Param->getType().getUnqualifiedType() != Context.VoidTy) { 5038 bool IsTypeAlias = false; 5039 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 5040 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 5041 else if (const TemplateSpecializationType *TST = 5042 Param->getType()->getAs<TemplateSpecializationType>()) 5043 IsTypeAlias = TST->isTypeAlias(); 5044 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 5045 << IsTypeAlias; 5046 } 5047 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 5048 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 5049 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 5050 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 5051 Param->setDeclContext(NewFD); 5052 Params.push_back(Param); 5053 5054 if (Param->isInvalidDecl()) 5055 NewFD->setInvalidDecl(); 5056 } 5057 } 5058 5059 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 5060 // When we're declaring a function with a typedef, typeof, etc as in the 5061 // following example, we'll need to synthesize (unnamed) 5062 // parameters for use in the declaration. 5063 // 5064 // @code 5065 // typedef void fn(int); 5066 // fn f; 5067 // @endcode 5068 5069 // Synthesize a parameter for each argument type. 5070 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 5071 AE = FT->arg_type_end(); AI != AE; ++AI) { 5072 ParmVarDecl *Param = 5073 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 5074 Param->setScopeInfo(0, Params.size()); 5075 Params.push_back(Param); 5076 } 5077 } else { 5078 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 5079 "Should not need args for typedef of non-prototype fn"); 5080 } 5081 5082 // Finally, we know we have the right number of parameters, install them. 5083 NewFD->setParams(Params); 5084 5085 // Process the non-inheritable attributes on this declaration. 5086 ProcessDeclAttributes(S, NewFD, D, 5087 /*NonInheritable=*/true, /*Inheritable=*/false); 5088 5089 if (!getLangOptions().CPlusPlus) { 5090 // Perform semantic checking on the function declaration. 5091 bool isExplicitSpecialization=false; 5092 if (!NewFD->isInvalidDecl()) { 5093 if (NewFD->getResultType()->isVariablyModifiedType()) { 5094 // Functions returning a variably modified type violate C99 6.7.5.2p2 5095 // because all functions have linkage. 5096 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 5097 NewFD->setInvalidDecl(); 5098 } else { 5099 if (NewFD->isMain()) 5100 CheckMain(NewFD, D.getDeclSpec()); 5101 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5102 isExplicitSpecialization)); 5103 } 5104 } 5105 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5106 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5107 "previous declaration set still overloaded"); 5108 } else { 5109 // If the declarator is a template-id, translate the parser's template 5110 // argument list into our AST format. 5111 bool HasExplicitTemplateArgs = false; 5112 TemplateArgumentListInfo TemplateArgs; 5113 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5114 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5115 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 5116 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 5117 ASTTemplateArgsPtr TemplateArgsPtr(*this, 5118 TemplateId->getTemplateArgs(), 5119 TemplateId->NumArgs); 5120 translateTemplateArguments(TemplateArgsPtr, 5121 TemplateArgs); 5122 TemplateArgsPtr.release(); 5123 5124 HasExplicitTemplateArgs = true; 5125 5126 if (NewFD->isInvalidDecl()) { 5127 HasExplicitTemplateArgs = false; 5128 } else if (FunctionTemplate) { 5129 // Function template with explicit template arguments. 5130 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 5131 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 5132 5133 HasExplicitTemplateArgs = false; 5134 } else if (!isFunctionTemplateSpecialization && 5135 !D.getDeclSpec().isFriendSpecified()) { 5136 // We have encountered something that the user meant to be a 5137 // specialization (because it has explicitly-specified template 5138 // arguments) but that was not introduced with a "template<>" (or had 5139 // too few of them). 5140 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5141 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5142 << FixItHint::CreateInsertion( 5143 D.getDeclSpec().getSourceRange().getBegin(), 5144 "template<> "); 5145 isFunctionTemplateSpecialization = true; 5146 } else { 5147 // "friend void foo<>(int);" is an implicit specialization decl. 5148 isFunctionTemplateSpecialization = true; 5149 } 5150 } else if (isFriend && isFunctionTemplateSpecialization) { 5151 // This combination is only possible in a recovery case; the user 5152 // wrote something like: 5153 // template <> friend void foo(int); 5154 // which we're recovering from as if the user had written: 5155 // friend void foo<>(int); 5156 // Go ahead and fake up a template id. 5157 HasExplicitTemplateArgs = true; 5158 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 5159 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 5160 } 5161 5162 // If it's a friend (and only if it's a friend), it's possible 5163 // that either the specialized function type or the specialized 5164 // template is dependent, and therefore matching will fail. In 5165 // this case, don't check the specialization yet. 5166 bool InstantiationDependent = false; 5167 if (isFunctionTemplateSpecialization && isFriend && 5168 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 5169 TemplateSpecializationType::anyDependentTemplateArguments( 5170 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 5171 InstantiationDependent))) { 5172 assert(HasExplicitTemplateArgs && 5173 "friend function specialization without template args"); 5174 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 5175 Previous)) 5176 NewFD->setInvalidDecl(); 5177 } else if (isFunctionTemplateSpecialization) { 5178 if (CurContext->isDependentContext() && CurContext->isRecord() 5179 && !isFriend) { 5180 isDependentClassScopeExplicitSpecialization = true; 5181 Diag(NewFD->getLocation(), getLangOptions().MicrosoftExt ? 5182 diag::ext_function_specialization_in_class : 5183 diag::err_function_specialization_in_class) 5184 << NewFD->getDeclName(); 5185 } else if (CheckFunctionTemplateSpecialization(NewFD, 5186 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 5187 Previous)) 5188 NewFD->setInvalidDecl(); 5189 5190 // C++ [dcl.stc]p1: 5191 // A storage-class-specifier shall not be specified in an explicit 5192 // specialization (14.7.3) 5193 if (SC != SC_None) { 5194 if (SC != NewFD->getStorageClass()) 5195 Diag(NewFD->getLocation(), 5196 diag::err_explicit_specialization_inconsistent_storage_class) 5197 << SC 5198 << FixItHint::CreateRemoval( 5199 D.getDeclSpec().getStorageClassSpecLoc()); 5200 5201 else 5202 Diag(NewFD->getLocation(), 5203 diag::ext_explicit_specialization_storage_class) 5204 << FixItHint::CreateRemoval( 5205 D.getDeclSpec().getStorageClassSpecLoc()); 5206 } 5207 5208 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 5209 if (CheckMemberSpecialization(NewFD, Previous)) 5210 NewFD->setInvalidDecl(); 5211 } 5212 5213 // Perform semantic checking on the function declaration. 5214 if (!isDependentClassScopeExplicitSpecialization) { 5215 if (NewFD->isInvalidDecl()) { 5216 // If this is a class member, mark the class invalid immediately. 5217 // This avoids some consistency errors later. 5218 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 5219 methodDecl->getParent()->setInvalidDecl(); 5220 } else { 5221 if (NewFD->isMain()) 5222 CheckMain(NewFD, D.getDeclSpec()); 5223 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5224 isExplicitSpecialization)); 5225 } 5226 } 5227 5228 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5229 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5230 "previous declaration set still overloaded"); 5231 5232 if (NewFD->isConstexpr() && !NewFD->isInvalidDecl() && 5233 !CheckConstexprFunctionDecl(NewFD, CCK_Declaration)) 5234 NewFD->setInvalidDecl(); 5235 5236 NamedDecl *PrincipalDecl = (FunctionTemplate 5237 ? cast<NamedDecl>(FunctionTemplate) 5238 : NewFD); 5239 5240 if (isFriend && D.isRedeclaration()) { 5241 AccessSpecifier Access = AS_public; 5242 if (!NewFD->isInvalidDecl()) 5243 Access = NewFD->getPreviousDeclaration()->getAccess(); 5244 5245 NewFD->setAccess(Access); 5246 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 5247 5248 PrincipalDecl->setObjectOfFriendDecl(true); 5249 } 5250 5251 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 5252 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5253 PrincipalDecl->setNonMemberOperator(); 5254 5255 // If we have a function template, check the template parameter 5256 // list. This will check and merge default template arguments. 5257 if (FunctionTemplate) { 5258 FunctionTemplateDecl *PrevTemplate = 5259 FunctionTemplate->getPreviousDeclaration(); 5260 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 5261 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 5262 D.getDeclSpec().isFriendSpecified() 5263 ? (D.isFunctionDefinition() 5264 ? TPC_FriendFunctionTemplateDefinition 5265 : TPC_FriendFunctionTemplate) 5266 : (D.getCXXScopeSpec().isSet() && 5267 DC && DC->isRecord() && 5268 DC->isDependentContext()) 5269 ? TPC_ClassTemplateMember 5270 : TPC_FunctionTemplate); 5271 } 5272 5273 if (NewFD->isInvalidDecl()) { 5274 // Ignore all the rest of this. 5275 } else if (!D.isRedeclaration()) { 5276 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 5277 AddToScope }; 5278 // Fake up an access specifier if it's supposed to be a class member. 5279 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 5280 NewFD->setAccess(AS_public); 5281 5282 // Qualified decls generally require a previous declaration. 5283 if (D.getCXXScopeSpec().isSet()) { 5284 // ...with the major exception of templated-scope or 5285 // dependent-scope friend declarations. 5286 5287 // TODO: we currently also suppress this check in dependent 5288 // contexts because (1) the parameter depth will be off when 5289 // matching friend templates and (2) we might actually be 5290 // selecting a friend based on a dependent factor. But there 5291 // are situations where these conditions don't apply and we 5292 // can actually do this check immediately. 5293 if (isFriend && 5294 (TemplateParamLists.size() || 5295 D.getCXXScopeSpec().getScopeRep()->isDependent() || 5296 CurContext->isDependentContext())) { 5297 // ignore these 5298 } else { 5299 // The user tried to provide an out-of-line definition for a 5300 // function that is a member of a class or namespace, but there 5301 // was no such member function declared (C++ [class.mfct]p2, 5302 // C++ [namespace.memdef]p2). For example: 5303 // 5304 // class X { 5305 // void f() const; 5306 // }; 5307 // 5308 // void X::f() { } // ill-formed 5309 // 5310 // Complain about this problem, and attempt to suggest close 5311 // matches (e.g., those that differ only in cv-qualifiers and 5312 // whether the parameter types are references). 5313 5314 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 5315 NewFD, 5316 ExtraArgs)) { 5317 AddToScope = ExtraArgs.AddToScope; 5318 return Result; 5319 } 5320 } 5321 5322 // Unqualified local friend declarations are required to resolve 5323 // to something. 5324 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 5325 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 5326 NewFD, 5327 ExtraArgs)) { 5328 AddToScope = ExtraArgs.AddToScope; 5329 return Result; 5330 } 5331 } 5332 5333 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 5334 !isFriend && !isFunctionTemplateSpecialization && 5335 !isExplicitSpecialization) { 5336 // An out-of-line member function declaration must also be a 5337 // definition (C++ [dcl.meaning]p1). 5338 // Note that this is not the case for explicit specializations of 5339 // function templates or member functions of class templates, per 5340 // C++ [temp.expl.spec]p2. We also allow these declarations as an 5341 // extension for compatibility with old SWIG code which likes to 5342 // generate them. 5343 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 5344 << D.getCXXScopeSpec().getRange(); 5345 } 5346 } 5347 5348 5349 // Handle attributes. We need to have merged decls when handling attributes 5350 // (for example to check for conflicts, etc). 5351 // FIXME: This needs to happen before we merge declarations. Then, 5352 // let attribute merging cope with attribute conflicts. 5353 ProcessDeclAttributes(S, NewFD, D, 5354 /*NonInheritable=*/false, /*Inheritable=*/true); 5355 5356 // attributes declared post-definition are currently ignored 5357 // FIXME: This should happen during attribute merging 5358 if (D.isRedeclaration() && Previous.isSingleResult()) { 5359 const FunctionDecl *Def; 5360 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl()); 5361 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) { 5362 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 5363 Diag(Def->getLocation(), diag::note_previous_definition); 5364 } 5365 } 5366 5367 AddKnownFunctionAttributes(NewFD); 5368 5369 if (NewFD->hasAttr<OverloadableAttr>() && 5370 !NewFD->getType()->getAs<FunctionProtoType>()) { 5371 Diag(NewFD->getLocation(), 5372 diag::err_attribute_overloadable_no_prototype) 5373 << NewFD; 5374 5375 // Turn this into a variadic function with no parameters. 5376 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 5377 FunctionProtoType::ExtProtoInfo EPI; 5378 EPI.Variadic = true; 5379 EPI.ExtInfo = FT->getExtInfo(); 5380 5381 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 5382 NewFD->setType(R); 5383 } 5384 5385 // If there's a #pragma GCC visibility in scope, and this isn't a class 5386 // member, set the visibility of this function. 5387 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 5388 AddPushedVisibilityAttribute(NewFD); 5389 5390 // If there's a #pragma clang arc_cf_code_audited in scope, consider 5391 // marking the function. 5392 AddCFAuditedAttribute(NewFD); 5393 5394 // If this is a locally-scoped extern C function, update the 5395 // map of such names. 5396 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 5397 && !NewFD->isInvalidDecl()) 5398 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 5399 5400 // Set this FunctionDecl's range up to the right paren. 5401 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 5402 5403 if (getLangOptions().CPlusPlus) { 5404 if (FunctionTemplate) { 5405 if (NewFD->isInvalidDecl()) 5406 FunctionTemplate->setInvalidDecl(); 5407 return FunctionTemplate; 5408 } 5409 } 5410 5411 MarkUnusedFileScopedDecl(NewFD); 5412 5413 if (getLangOptions().CUDA) 5414 if (IdentifierInfo *II = NewFD->getIdentifier()) 5415 if (!NewFD->isInvalidDecl() && 5416 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5417 if (II->isStr("cudaConfigureCall")) { 5418 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 5419 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 5420 5421 Context.setcudaConfigureCallDecl(NewFD); 5422 } 5423 } 5424 5425 // Here we have an function template explicit specialization at class scope. 5426 // The actually specialization will be postponed to template instatiation 5427 // time via the ClassScopeFunctionSpecializationDecl node. 5428 if (isDependentClassScopeExplicitSpecialization) { 5429 ClassScopeFunctionSpecializationDecl *NewSpec = 5430 ClassScopeFunctionSpecializationDecl::Create( 5431 Context, CurContext, SourceLocation(), 5432 cast<CXXMethodDecl>(NewFD)); 5433 CurContext->addDecl(NewSpec); 5434 AddToScope = false; 5435 } 5436 5437 return NewFD; 5438} 5439 5440/// \brief Perform semantic checking of a new function declaration. 5441/// 5442/// Performs semantic analysis of the new function declaration 5443/// NewFD. This routine performs all semantic checking that does not 5444/// require the actual declarator involved in the declaration, and is 5445/// used both for the declaration of functions as they are parsed 5446/// (called via ActOnDeclarator) and for the declaration of functions 5447/// that have been instantiated via C++ template instantiation (called 5448/// via InstantiateDecl). 5449/// 5450/// \param IsExplicitSpecialiation whether this new function declaration is 5451/// an explicit specialization of the previous declaration. 5452/// 5453/// This sets NewFD->isInvalidDecl() to true if there was an error. 5454/// 5455/// Returns true if the function declaration is a redeclaration. 5456bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 5457 LookupResult &Previous, 5458 bool IsExplicitSpecialization) { 5459 assert(!NewFD->getResultType()->isVariablyModifiedType() 5460 && "Variably modified return types are not handled here"); 5461 5462 // Check for a previous declaration of this name. 5463 if (Previous.empty() && NewFD->isExternC()) { 5464 // Since we did not find anything by this name and we're declaring 5465 // an extern "C" function, look for a non-visible extern "C" 5466 // declaration with the same name. 5467 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5468 = findLocallyScopedExternalDecl(NewFD->getDeclName()); 5469 if (Pos != LocallyScopedExternalDecls.end()) 5470 Previous.addDecl(Pos->second); 5471 } 5472 5473 bool Redeclaration = false; 5474 5475 // Merge or overload the declaration with an existing declaration of 5476 // the same name, if appropriate. 5477 if (!Previous.empty()) { 5478 // Determine whether NewFD is an overload of PrevDecl or 5479 // a declaration that requires merging. If it's an overload, 5480 // there's no more work to do here; we'll just add the new 5481 // function to the scope. 5482 5483 NamedDecl *OldDecl = 0; 5484 if (!AllowOverloadingOfFunction(Previous, Context)) { 5485 Redeclaration = true; 5486 OldDecl = Previous.getFoundDecl(); 5487 } else { 5488 switch (CheckOverload(S, NewFD, Previous, OldDecl, 5489 /*NewIsUsingDecl*/ false)) { 5490 case Ovl_Match: 5491 Redeclaration = true; 5492 break; 5493 5494 case Ovl_NonFunction: 5495 Redeclaration = true; 5496 break; 5497 5498 case Ovl_Overload: 5499 Redeclaration = false; 5500 break; 5501 } 5502 5503 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 5504 // If a function name is overloadable in C, then every function 5505 // with that name must be marked "overloadable". 5506 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 5507 << Redeclaration << NewFD; 5508 NamedDecl *OverloadedDecl = 0; 5509 if (Redeclaration) 5510 OverloadedDecl = OldDecl; 5511 else if (!Previous.empty()) 5512 OverloadedDecl = Previous.getRepresentativeDecl(); 5513 if (OverloadedDecl) 5514 Diag(OverloadedDecl->getLocation(), 5515 diag::note_attribute_overloadable_prev_overload); 5516 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 5517 Context)); 5518 } 5519 } 5520 5521 if (Redeclaration) { 5522 // NewFD and OldDecl represent declarations that need to be 5523 // merged. 5524 if (MergeFunctionDecl(NewFD, OldDecl)) { 5525 NewFD->setInvalidDecl(); 5526 return Redeclaration; 5527 } 5528 5529 Previous.clear(); 5530 Previous.addDecl(OldDecl); 5531 5532 if (FunctionTemplateDecl *OldTemplateDecl 5533 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 5534 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 5535 FunctionTemplateDecl *NewTemplateDecl 5536 = NewFD->getDescribedFunctionTemplate(); 5537 assert(NewTemplateDecl && "Template/non-template mismatch"); 5538 if (CXXMethodDecl *Method 5539 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 5540 Method->setAccess(OldTemplateDecl->getAccess()); 5541 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 5542 } 5543 5544 // If this is an explicit specialization of a member that is a function 5545 // template, mark it as a member specialization. 5546 if (IsExplicitSpecialization && 5547 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 5548 NewTemplateDecl->setMemberSpecialization(); 5549 assert(OldTemplateDecl->isMemberSpecialization()); 5550 } 5551 5552 if (OldTemplateDecl->isModulePrivate()) 5553 NewTemplateDecl->setModulePrivate(); 5554 5555 } else { 5556 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 5557 NewFD->setAccess(OldDecl->getAccess()); 5558 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 5559 } 5560 } 5561 } 5562 5563 // Semantic checking for this function declaration (in isolation). 5564 if (getLangOptions().CPlusPlus) { 5565 // C++-specific checks. 5566 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 5567 CheckConstructor(Constructor); 5568 } else if (CXXDestructorDecl *Destructor = 5569 dyn_cast<CXXDestructorDecl>(NewFD)) { 5570 CXXRecordDecl *Record = Destructor->getParent(); 5571 QualType ClassType = Context.getTypeDeclType(Record); 5572 5573 // FIXME: Shouldn't we be able to perform this check even when the class 5574 // type is dependent? Both gcc and edg can handle that. 5575 if (!ClassType->isDependentType()) { 5576 DeclarationName Name 5577 = Context.DeclarationNames.getCXXDestructorName( 5578 Context.getCanonicalType(ClassType)); 5579 if (NewFD->getDeclName() != Name) { 5580 Diag(NewFD->getLocation(), diag::err_destructor_name); 5581 NewFD->setInvalidDecl(); 5582 return Redeclaration; 5583 } 5584 } 5585 } else if (CXXConversionDecl *Conversion 5586 = dyn_cast<CXXConversionDecl>(NewFD)) { 5587 ActOnConversionDeclarator(Conversion); 5588 } 5589 5590 // Find any virtual functions that this function overrides. 5591 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 5592 if (!Method->isFunctionTemplateSpecialization() && 5593 !Method->getDescribedFunctionTemplate()) { 5594 if (AddOverriddenMethods(Method->getParent(), Method)) { 5595 // If the function was marked as "static", we have a problem. 5596 if (NewFD->getStorageClass() == SC_Static) { 5597 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual) 5598 << NewFD->getDeclName(); 5599 for (CXXMethodDecl::method_iterator 5600 Overridden = Method->begin_overridden_methods(), 5601 OverriddenEnd = Method->end_overridden_methods(); 5602 Overridden != OverriddenEnd; 5603 ++Overridden) { 5604 Diag((*Overridden)->getLocation(), 5605 diag::note_overridden_virtual_function); 5606 } 5607 } 5608 } 5609 } 5610 } 5611 5612 // Extra checking for C++ overloaded operators (C++ [over.oper]). 5613 if (NewFD->isOverloadedOperator() && 5614 CheckOverloadedOperatorDeclaration(NewFD)) { 5615 NewFD->setInvalidDecl(); 5616 return Redeclaration; 5617 } 5618 5619 // Extra checking for C++0x literal operators (C++0x [over.literal]). 5620 if (NewFD->getLiteralIdentifier() && 5621 CheckLiteralOperatorDeclaration(NewFD)) { 5622 NewFD->setInvalidDecl(); 5623 return Redeclaration; 5624 } 5625 5626 // In C++, check default arguments now that we have merged decls. Unless 5627 // the lexical context is the class, because in this case this is done 5628 // during delayed parsing anyway. 5629 if (!CurContext->isRecord()) 5630 CheckCXXDefaultArguments(NewFD); 5631 5632 // If this function declares a builtin function, check the type of this 5633 // declaration against the expected type for the builtin. 5634 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 5635 ASTContext::GetBuiltinTypeError Error; 5636 QualType T = Context.GetBuiltinType(BuiltinID, Error); 5637 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 5638 // The type of this function differs from the type of the builtin, 5639 // so forget about the builtin entirely. 5640 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 5641 } 5642 } 5643 } 5644 return Redeclaration; 5645} 5646 5647void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 5648 // C++ [basic.start.main]p3: A program that declares main to be inline 5649 // or static is ill-formed. 5650 // C99 6.7.4p4: In a hosted environment, the inline function specifier 5651 // shall not appear in a declaration of main. 5652 // static main is not an error under C99, but we should warn about it. 5653 if (FD->getStorageClass() == SC_Static) 5654 Diag(DS.getStorageClassSpecLoc(), getLangOptions().CPlusPlus 5655 ? diag::err_static_main : diag::warn_static_main) 5656 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5657 if (FD->isInlineSpecified()) 5658 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 5659 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 5660 5661 QualType T = FD->getType(); 5662 assert(T->isFunctionType() && "function decl is not of function type"); 5663 const FunctionType* FT = T->getAs<FunctionType>(); 5664 5665 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 5666 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 5667 FD->setInvalidDecl(true); 5668 } 5669 5670 // Treat protoless main() as nullary. 5671 if (isa<FunctionNoProtoType>(FT)) return; 5672 5673 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 5674 unsigned nparams = FTP->getNumArgs(); 5675 assert(FD->getNumParams() == nparams); 5676 5677 bool HasExtraParameters = (nparams > 3); 5678 5679 // Darwin passes an undocumented fourth argument of type char**. If 5680 // other platforms start sprouting these, the logic below will start 5681 // getting shifty. 5682 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 5683 HasExtraParameters = false; 5684 5685 if (HasExtraParameters) { 5686 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 5687 FD->setInvalidDecl(true); 5688 nparams = 3; 5689 } 5690 5691 // FIXME: a lot of the following diagnostics would be improved 5692 // if we had some location information about types. 5693 5694 QualType CharPP = 5695 Context.getPointerType(Context.getPointerType(Context.CharTy)); 5696 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 5697 5698 for (unsigned i = 0; i < nparams; ++i) { 5699 QualType AT = FTP->getArgType(i); 5700 5701 bool mismatch = true; 5702 5703 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 5704 mismatch = false; 5705 else if (Expected[i] == CharPP) { 5706 // As an extension, the following forms are okay: 5707 // char const ** 5708 // char const * const * 5709 // char * const * 5710 5711 QualifierCollector qs; 5712 const PointerType* PT; 5713 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 5714 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 5715 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 5716 qs.removeConst(); 5717 mismatch = !qs.empty(); 5718 } 5719 } 5720 5721 if (mismatch) { 5722 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 5723 // TODO: suggest replacing given type with expected type 5724 FD->setInvalidDecl(true); 5725 } 5726 } 5727 5728 if (nparams == 1 && !FD->isInvalidDecl()) { 5729 Diag(FD->getLocation(), diag::warn_main_one_arg); 5730 } 5731 5732 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 5733 Diag(FD->getLocation(), diag::err_main_template_decl); 5734 FD->setInvalidDecl(); 5735 } 5736} 5737 5738bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 5739 // FIXME: Need strict checking. In C89, we need to check for 5740 // any assignment, increment, decrement, function-calls, or 5741 // commas outside of a sizeof. In C99, it's the same list, 5742 // except that the aforementioned are allowed in unevaluated 5743 // expressions. Everything else falls under the 5744 // "may accept other forms of constant expressions" exception. 5745 // (We never end up here for C++, so the constant expression 5746 // rules there don't matter.) 5747 if (Init->isConstantInitializer(Context, false)) 5748 return false; 5749 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 5750 << Init->getSourceRange(); 5751 return true; 5752} 5753 5754namespace { 5755 // Visits an initialization expression to see if OrigDecl is evaluated in 5756 // its own initialization and throws a warning if it does. 5757 class SelfReferenceChecker 5758 : public EvaluatedExprVisitor<SelfReferenceChecker> { 5759 Sema &S; 5760 Decl *OrigDecl; 5761 bool isRecordType; 5762 bool isPODType; 5763 5764 public: 5765 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 5766 5767 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 5768 S(S), OrigDecl(OrigDecl) { 5769 isPODType = false; 5770 isRecordType = false; 5771 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 5772 isPODType = VD->getType().isPODType(S.Context); 5773 isRecordType = VD->getType()->isRecordType(); 5774 } 5775 } 5776 5777 void VisitExpr(Expr *E) { 5778 if (isa<ObjCMessageExpr>(*E)) return; 5779 if (isRecordType) { 5780 Expr *expr = E; 5781 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 5782 ValueDecl *VD = ME->getMemberDecl(); 5783 if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return; 5784 expr = ME->getBase(); 5785 } 5786 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) { 5787 HandleDeclRefExpr(DRE); 5788 return; 5789 } 5790 } 5791 Inherited::VisitExpr(E); 5792 } 5793 5794 void VisitMemberExpr(MemberExpr *E) { 5795 if (E->getType()->canDecayToPointerType()) return; 5796 if (isa<FieldDecl>(E->getMemberDecl())) 5797 if (DeclRefExpr *DRE 5798 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) { 5799 HandleDeclRefExpr(DRE); 5800 return; 5801 } 5802 Inherited::VisitMemberExpr(E); 5803 } 5804 5805 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 5806 if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) || 5807 (isRecordType && E->getCastKind() == CK_NoOp)) { 5808 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts(); 5809 if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr)) 5810 SubExpr = ME->getBase()->IgnoreParenImpCasts(); 5811 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) { 5812 HandleDeclRefExpr(DRE); 5813 return; 5814 } 5815 } 5816 Inherited::VisitImplicitCastExpr(E); 5817 } 5818 5819 void VisitUnaryOperator(UnaryOperator *E) { 5820 // For POD record types, addresses of its own members are well-defined. 5821 if (isRecordType && isPODType) return; 5822 Inherited::VisitUnaryOperator(E); 5823 } 5824 5825 void HandleDeclRefExpr(DeclRefExpr *DRE) { 5826 Decl* ReferenceDecl = DRE->getDecl(); 5827 if (OrigDecl != ReferenceDecl) return; 5828 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName, 5829 Sema::NotForRedeclaration); 5830 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 5831 S.PDiag(diag::warn_uninit_self_reference_in_init) 5832 << Result.getLookupName() 5833 << OrigDecl->getLocation() 5834 << DRE->getSourceRange()); 5835 } 5836 }; 5837} 5838 5839/// CheckSelfReference - Warns if OrigDecl is used in expression E. 5840void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) { 5841 SelfReferenceChecker(*this, OrigDecl).VisitExpr(E); 5842} 5843 5844/// AddInitializerToDecl - Adds the initializer Init to the 5845/// declaration dcl. If DirectInit is true, this is C++ direct 5846/// initialization rather than copy initialization. 5847void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 5848 bool DirectInit, bool TypeMayContainAuto) { 5849 // If there is no declaration, there was an error parsing it. Just ignore 5850 // the initializer. 5851 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 5852 return; 5853 5854 // Check for self-references within variable initializers. 5855 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) { 5856 // Variables declared within a function/method body are handled 5857 // by a dataflow analysis. 5858 if (!vd->hasLocalStorage() && !vd->isStaticLocal()) 5859 CheckSelfReference(RealDecl, Init); 5860 } 5861 else { 5862 CheckSelfReference(RealDecl, Init); 5863 } 5864 5865 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 5866 // With declarators parsed the way they are, the parser cannot 5867 // distinguish between a normal initializer and a pure-specifier. 5868 // Thus this grotesque test. 5869 IntegerLiteral *IL; 5870 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 5871 Context.getCanonicalType(IL->getType()) == Context.IntTy) 5872 CheckPureMethod(Method, Init->getSourceRange()); 5873 else { 5874 Diag(Method->getLocation(), diag::err_member_function_initialization) 5875 << Method->getDeclName() << Init->getSourceRange(); 5876 Method->setInvalidDecl(); 5877 } 5878 return; 5879 } 5880 5881 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 5882 if (!VDecl) { 5883 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 5884 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 5885 RealDecl->setInvalidDecl(); 5886 return; 5887 } 5888 5889 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 5890 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 5891 TypeSourceInfo *DeducedType = 0; 5892 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 5893 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 5894 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 5895 << Init->getSourceRange(); 5896 if (!DeducedType) { 5897 RealDecl->setInvalidDecl(); 5898 return; 5899 } 5900 VDecl->setTypeSourceInfo(DeducedType); 5901 VDecl->setType(DeducedType->getType()); 5902 5903 // In ARC, infer lifetime. 5904 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 5905 VDecl->setInvalidDecl(); 5906 5907 // If this is a redeclaration, check that the type we just deduced matches 5908 // the previously declared type. 5909 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 5910 MergeVarDeclTypes(VDecl, Old); 5911 } 5912 5913 5914 // A definition must end up with a complete type, which means it must be 5915 // complete with the restriction that an array type might be completed by the 5916 // initializer; note that later code assumes this restriction. 5917 QualType BaseDeclType = VDecl->getType(); 5918 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 5919 BaseDeclType = Array->getElementType(); 5920 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 5921 diag::err_typecheck_decl_incomplete_type)) { 5922 RealDecl->setInvalidDecl(); 5923 return; 5924 } 5925 5926 // The variable can not have an abstract class type. 5927 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 5928 diag::err_abstract_type_in_decl, 5929 AbstractVariableType)) 5930 VDecl->setInvalidDecl(); 5931 5932 const VarDecl *Def; 5933 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 5934 Diag(VDecl->getLocation(), diag::err_redefinition) 5935 << VDecl->getDeclName(); 5936 Diag(Def->getLocation(), diag::note_previous_definition); 5937 VDecl->setInvalidDecl(); 5938 return; 5939 } 5940 5941 const VarDecl* PrevInit = 0; 5942 if (getLangOptions().CPlusPlus) { 5943 // C++ [class.static.data]p4 5944 // If a static data member is of const integral or const 5945 // enumeration type, its declaration in the class definition can 5946 // specify a constant-initializer which shall be an integral 5947 // constant expression (5.19). In that case, the member can appear 5948 // in integral constant expressions. The member shall still be 5949 // defined in a namespace scope if it is used in the program and the 5950 // namespace scope definition shall not contain an initializer. 5951 // 5952 // We already performed a redefinition check above, but for static 5953 // data members we also need to check whether there was an in-class 5954 // declaration with an initializer. 5955 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 5956 Diag(VDecl->getLocation(), diag::err_redefinition) 5957 << VDecl->getDeclName(); 5958 Diag(PrevInit->getLocation(), diag::note_previous_definition); 5959 return; 5960 } 5961 5962 if (VDecl->hasLocalStorage()) 5963 getCurFunction()->setHasBranchProtectedScope(); 5964 5965 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 5966 VDecl->setInvalidDecl(); 5967 return; 5968 } 5969 } 5970 5971 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 5972 // a kernel function cannot be initialized." 5973 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 5974 Diag(VDecl->getLocation(), diag::err_local_cant_init); 5975 VDecl->setInvalidDecl(); 5976 return; 5977 } 5978 5979 // Capture the variable that is being initialized and the style of 5980 // initialization. 5981 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 5982 5983 // FIXME: Poor source location information. 5984 InitializationKind Kind 5985 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(), 5986 Init->getLocStart(), 5987 Init->getLocEnd()) 5988 : InitializationKind::CreateCopy(VDecl->getLocation(), 5989 Init->getLocStart()); 5990 5991 // Get the decls type and save a reference for later, since 5992 // CheckInitializerTypes may change it. 5993 QualType DclT = VDecl->getType(), SavT = DclT; 5994 if (VDecl->isLocalVarDecl()) { 5995 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 5996 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 5997 VDecl->setInvalidDecl(); 5998 } else if (!VDecl->isInvalidDecl()) { 5999 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 6000 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6001 MultiExprArg(*this, &Init, 1), 6002 &DclT); 6003 if (Result.isInvalid()) { 6004 VDecl->setInvalidDecl(); 6005 return; 6006 } 6007 6008 Init = Result.takeAs<Expr>(); 6009 6010 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 6011 // Don't check invalid declarations to avoid emitting useless diagnostics. 6012 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 6013 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4. 6014 CheckForConstantInitializer(Init, DclT); 6015 } 6016 } 6017 } else if (VDecl->isStaticDataMember() && 6018 VDecl->getLexicalDeclContext()->isRecord()) { 6019 // This is an in-class initialization for a static data member, e.g., 6020 // 6021 // struct S { 6022 // static const int value = 17; 6023 // }; 6024 6025 // Try to perform the initialization regardless. 6026 if (!VDecl->isInvalidDecl()) { 6027 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 6028 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6029 MultiExprArg(*this, &Init, 1), 6030 &DclT); 6031 if (Result.isInvalid()) { 6032 VDecl->setInvalidDecl(); 6033 return; 6034 } 6035 6036 Init = Result.takeAs<Expr>(); 6037 } 6038 6039 // C++ [class.mem]p4: 6040 // A member-declarator can contain a constant-initializer only 6041 // if it declares a static member (9.4) of const integral or 6042 // const enumeration type, see 9.4.2. 6043 // 6044 // C++0x [class.static.data]p3: 6045 // If a non-volatile const static data member is of integral or 6046 // enumeration type, its declaration in the class definition can 6047 // specify a brace-or-equal-initializer in which every initalizer-clause 6048 // that is an assignment-expression is a constant expression. A static 6049 // data member of literal type can be declared in the class definition 6050 // with the constexpr specifier; if so, its declaration shall specify a 6051 // brace-or-equal-initializer in which every initializer-clause that is 6052 // an assignment-expression is a constant expression. 6053 QualType T = VDecl->getType(); 6054 6055 // Do nothing on dependent types. 6056 if (T->isDependentType()) { 6057 6058 // Allow any 'static constexpr' members, whether or not they are of literal 6059 // type. We separately check that the initializer is a constant expression, 6060 // which implicitly requires the member to be of literal type. 6061 } else if (VDecl->isConstexpr()) { 6062 6063 // Require constness. 6064 } else if (!T.isConstQualified()) { 6065 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 6066 << Init->getSourceRange(); 6067 VDecl->setInvalidDecl(); 6068 6069 // We allow integer constant expressions in all cases. 6070 } else if (T->isIntegralOrEnumerationType()) { 6071 // Check whether the expression is a constant expression. 6072 SourceLocation Loc; 6073 if (getLangOptions().CPlusPlus0x && T.isVolatileQualified()) 6074 // In C++0x, a non-constexpr const static data member with an 6075 // in-class initializer cannot be volatile. 6076 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 6077 else if (Init->isValueDependent()) 6078 ; // Nothing to check. 6079 else if (Init->isIntegerConstantExpr(Context, &Loc)) 6080 ; // Ok, it's an ICE! 6081 else if (Init->isEvaluatable(Context)) { 6082 // If we can constant fold the initializer through heroics, accept it, 6083 // but report this as a use of an extension for -pedantic. 6084 Diag(Loc, diag::ext_in_class_initializer_non_constant) 6085 << Init->getSourceRange(); 6086 } else { 6087 // Otherwise, this is some crazy unknown case. Report the issue at the 6088 // location provided by the isIntegerConstantExpr failed check. 6089 Diag(Loc, diag::err_in_class_initializer_non_constant) 6090 << Init->getSourceRange(); 6091 VDecl->setInvalidDecl(); 6092 } 6093 6094 // We allow floating-point constants as an extension. 6095 } else if (T->isFloatingType()) { // also permits complex, which is ok 6096 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 6097 << T << Init->getSourceRange(); 6098 if (getLangOptions().CPlusPlus0x) 6099 Diag(VDecl->getLocation(), 6100 diag::note_in_class_initializer_float_type_constexpr) 6101 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 6102 6103 if (!Init->isValueDependent() && 6104 !Init->isConstantInitializer(Context, false)) { 6105 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 6106 << Init->getSourceRange(); 6107 VDecl->setInvalidDecl(); 6108 } 6109 6110 // Suggest adding 'constexpr' in C++0x for literal types. 6111 } else if (getLangOptions().CPlusPlus0x && T->isLiteralType()) { 6112 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 6113 << T << Init->getSourceRange() 6114 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 6115 VDecl->setConstexpr(true); 6116 6117 } else { 6118 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 6119 << T << Init->getSourceRange(); 6120 VDecl->setInvalidDecl(); 6121 } 6122 } else if (VDecl->isFileVarDecl()) { 6123 if (VDecl->getStorageClassAsWritten() == SC_Extern && 6124 (!getLangOptions().CPlusPlus || 6125 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 6126 Diag(VDecl->getLocation(), diag::warn_extern_init); 6127 if (!VDecl->isInvalidDecl()) { 6128 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 6129 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6130 MultiExprArg(*this, &Init, 1), 6131 &DclT); 6132 if (Result.isInvalid()) { 6133 VDecl->setInvalidDecl(); 6134 return; 6135 } 6136 6137 Init = Result.takeAs<Expr>(); 6138 } 6139 6140 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 6141 // Don't check invalid declarations to avoid emitting useless diagnostics. 6142 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 6143 // C99 6.7.8p4. All file scoped initializers need to be constant. 6144 CheckForConstantInitializer(Init, DclT); 6145 } 6146 } 6147 // If the type changed, it means we had an incomplete type that was 6148 // completed by the initializer. For example: 6149 // int ary[] = { 1, 3, 5 }; 6150 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 6151 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 6152 VDecl->setType(DclT); 6153 Init->setType(DclT); 6154 } 6155 6156 // Check any implicit conversions within the expression. 6157 CheckImplicitConversions(Init, VDecl->getLocation()); 6158 6159 if (!VDecl->isInvalidDecl()) 6160 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 6161 6162 if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() && 6163 !VDecl->getType()->isDependentType() && 6164 !Init->isTypeDependent() && !Init->isValueDependent() && 6165 !Init->isConstantInitializer(Context, 6166 VDecl->getType()->isReferenceType())) { 6167 // FIXME: Improve this diagnostic to explain why the initializer is not 6168 // a constant expression. 6169 Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init) 6170 << VDecl << Init->getSourceRange(); 6171 } 6172 6173 Init = MaybeCreateExprWithCleanups(Init); 6174 // Attach the initializer to the decl. 6175 VDecl->setInit(Init); 6176 6177 CheckCompleteVariableDeclaration(VDecl); 6178} 6179 6180/// ActOnInitializerError - Given that there was an error parsing an 6181/// initializer for the given declaration, try to return to some form 6182/// of sanity. 6183void Sema::ActOnInitializerError(Decl *D) { 6184 // Our main concern here is re-establishing invariants like "a 6185 // variable's type is either dependent or complete". 6186 if (!D || D->isInvalidDecl()) return; 6187 6188 VarDecl *VD = dyn_cast<VarDecl>(D); 6189 if (!VD) return; 6190 6191 // Auto types are meaningless if we can't make sense of the initializer. 6192 if (ParsingInitForAutoVars.count(D)) { 6193 D->setInvalidDecl(); 6194 return; 6195 } 6196 6197 QualType Ty = VD->getType(); 6198 if (Ty->isDependentType()) return; 6199 6200 // Require a complete type. 6201 if (RequireCompleteType(VD->getLocation(), 6202 Context.getBaseElementType(Ty), 6203 diag::err_typecheck_decl_incomplete_type)) { 6204 VD->setInvalidDecl(); 6205 return; 6206 } 6207 6208 // Require an abstract type. 6209 if (RequireNonAbstractType(VD->getLocation(), Ty, 6210 diag::err_abstract_type_in_decl, 6211 AbstractVariableType)) { 6212 VD->setInvalidDecl(); 6213 return; 6214 } 6215 6216 // Don't bother complaining about constructors or destructors, 6217 // though. 6218} 6219 6220void Sema::ActOnUninitializedDecl(Decl *RealDecl, 6221 bool TypeMayContainAuto) { 6222 // If there is no declaration, there was an error parsing it. Just ignore it. 6223 if (RealDecl == 0) 6224 return; 6225 6226 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 6227 QualType Type = Var->getType(); 6228 6229 // C++0x [dcl.spec.auto]p3 6230 if (TypeMayContainAuto && Type->getContainedAutoType()) { 6231 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 6232 << Var->getDeclName() << Type; 6233 Var->setInvalidDecl(); 6234 return; 6235 } 6236 6237 // C++0x [dcl.constexpr]p9: An object or reference declared constexpr must 6238 // have an initializer. 6239 // C++0x [class.static.data]p3: A static data member can be declared with 6240 // the constexpr specifier; if so, its declaration shall specify 6241 // a brace-or-equal-initializer. 6242 // 6243 // A static data member's definition may inherit an initializer from an 6244 // in-class declaration. 6245 if (Var->isConstexpr() && !Var->getAnyInitializer()) { 6246 Diag(Var->getLocation(), diag::err_constexpr_var_requires_init) 6247 << Var->getDeclName(); 6248 Var->setInvalidDecl(); 6249 return; 6250 } 6251 6252 switch (Var->isThisDeclarationADefinition()) { 6253 case VarDecl::Definition: 6254 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 6255 break; 6256 6257 // We have an out-of-line definition of a static data member 6258 // that has an in-class initializer, so we type-check this like 6259 // a declaration. 6260 // 6261 // Fall through 6262 6263 case VarDecl::DeclarationOnly: 6264 // It's only a declaration. 6265 6266 // Block scope. C99 6.7p7: If an identifier for an object is 6267 // declared with no linkage (C99 6.2.2p6), the type for the 6268 // object shall be complete. 6269 if (!Type->isDependentType() && Var->isLocalVarDecl() && 6270 !Var->getLinkage() && !Var->isInvalidDecl() && 6271 RequireCompleteType(Var->getLocation(), Type, 6272 diag::err_typecheck_decl_incomplete_type)) 6273 Var->setInvalidDecl(); 6274 6275 // Make sure that the type is not abstract. 6276 if (!Type->isDependentType() && !Var->isInvalidDecl() && 6277 RequireNonAbstractType(Var->getLocation(), Type, 6278 diag::err_abstract_type_in_decl, 6279 AbstractVariableType)) 6280 Var->setInvalidDecl(); 6281 return; 6282 6283 case VarDecl::TentativeDefinition: 6284 // File scope. C99 6.9.2p2: A declaration of an identifier for an 6285 // object that has file scope without an initializer, and without a 6286 // storage-class specifier or with the storage-class specifier "static", 6287 // constitutes a tentative definition. Note: A tentative definition with 6288 // external linkage is valid (C99 6.2.2p5). 6289 if (!Var->isInvalidDecl()) { 6290 if (const IncompleteArrayType *ArrayT 6291 = Context.getAsIncompleteArrayType(Type)) { 6292 if (RequireCompleteType(Var->getLocation(), 6293 ArrayT->getElementType(), 6294 diag::err_illegal_decl_array_incomplete_type)) 6295 Var->setInvalidDecl(); 6296 } else if (Var->getStorageClass() == SC_Static) { 6297 // C99 6.9.2p3: If the declaration of an identifier for an object is 6298 // a tentative definition and has internal linkage (C99 6.2.2p3), the 6299 // declared type shall not be an incomplete type. 6300 // NOTE: code such as the following 6301 // static struct s; 6302 // struct s { int a; }; 6303 // is accepted by gcc. Hence here we issue a warning instead of 6304 // an error and we do not invalidate the static declaration. 6305 // NOTE: to avoid multiple warnings, only check the first declaration. 6306 if (Var->getPreviousDeclaration() == 0) 6307 RequireCompleteType(Var->getLocation(), Type, 6308 diag::ext_typecheck_decl_incomplete_type); 6309 } 6310 } 6311 6312 // Record the tentative definition; we're done. 6313 if (!Var->isInvalidDecl()) 6314 TentativeDefinitions.push_back(Var); 6315 return; 6316 } 6317 6318 // Provide a specific diagnostic for uninitialized variable 6319 // definitions with incomplete array type. 6320 if (Type->isIncompleteArrayType()) { 6321 Diag(Var->getLocation(), 6322 diag::err_typecheck_incomplete_array_needs_initializer); 6323 Var->setInvalidDecl(); 6324 return; 6325 } 6326 6327 // Provide a specific diagnostic for uninitialized variable 6328 // definitions with reference type. 6329 if (Type->isReferenceType()) { 6330 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 6331 << Var->getDeclName() 6332 << SourceRange(Var->getLocation(), Var->getLocation()); 6333 Var->setInvalidDecl(); 6334 return; 6335 } 6336 6337 // Do not attempt to type-check the default initializer for a 6338 // variable with dependent type. 6339 if (Type->isDependentType()) 6340 return; 6341 6342 if (Var->isInvalidDecl()) 6343 return; 6344 6345 if (RequireCompleteType(Var->getLocation(), 6346 Context.getBaseElementType(Type), 6347 diag::err_typecheck_decl_incomplete_type)) { 6348 Var->setInvalidDecl(); 6349 return; 6350 } 6351 6352 // The variable can not have an abstract class type. 6353 if (RequireNonAbstractType(Var->getLocation(), Type, 6354 diag::err_abstract_type_in_decl, 6355 AbstractVariableType)) { 6356 Var->setInvalidDecl(); 6357 return; 6358 } 6359 6360 // Check for jumps past the implicit initializer. C++0x 6361 // clarifies that this applies to a "variable with automatic 6362 // storage duration", not a "local variable". 6363 // C++0x [stmt.dcl]p3 6364 // A program that jumps from a point where a variable with automatic 6365 // storage duration is not in scope to a point where it is in scope is 6366 // ill-formed unless the variable has scalar type, class type with a 6367 // trivial default constructor and a trivial destructor, a cv-qualified 6368 // version of one of these types, or an array of one of the preceding 6369 // types and is declared without an initializer. 6370 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) { 6371 if (const RecordType *Record 6372 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 6373 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 6374 if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) || 6375 (getLangOptions().CPlusPlus0x && 6376 (!CXXRecord->hasTrivialDefaultConstructor() || 6377 !CXXRecord->hasTrivialDestructor()))) 6378 getCurFunction()->setHasBranchProtectedScope(); 6379 } 6380 } 6381 6382 // C++03 [dcl.init]p9: 6383 // If no initializer is specified for an object, and the 6384 // object is of (possibly cv-qualified) non-POD class type (or 6385 // array thereof), the object shall be default-initialized; if 6386 // the object is of const-qualified type, the underlying class 6387 // type shall have a user-declared default 6388 // constructor. Otherwise, if no initializer is specified for 6389 // a non- static object, the object and its subobjects, if 6390 // any, have an indeterminate initial value); if the object 6391 // or any of its subobjects are of const-qualified type, the 6392 // program is ill-formed. 6393 // C++0x [dcl.init]p11: 6394 // If no initializer is specified for an object, the object is 6395 // default-initialized; [...]. 6396 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 6397 InitializationKind Kind 6398 = InitializationKind::CreateDefault(Var->getLocation()); 6399 6400 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 6401 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 6402 MultiExprArg(*this, 0, 0)); 6403 if (Init.isInvalid()) 6404 Var->setInvalidDecl(); 6405 else if (Init.get()) 6406 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 6407 6408 CheckCompleteVariableDeclaration(Var); 6409 } 6410} 6411 6412void Sema::ActOnCXXForRangeDecl(Decl *D) { 6413 VarDecl *VD = dyn_cast<VarDecl>(D); 6414 if (!VD) { 6415 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 6416 D->setInvalidDecl(); 6417 return; 6418 } 6419 6420 VD->setCXXForRangeDecl(true); 6421 6422 // for-range-declaration cannot be given a storage class specifier. 6423 int Error = -1; 6424 switch (VD->getStorageClassAsWritten()) { 6425 case SC_None: 6426 break; 6427 case SC_Extern: 6428 Error = 0; 6429 break; 6430 case SC_Static: 6431 Error = 1; 6432 break; 6433 case SC_PrivateExtern: 6434 Error = 2; 6435 break; 6436 case SC_Auto: 6437 Error = 3; 6438 break; 6439 case SC_Register: 6440 Error = 4; 6441 break; 6442 case SC_OpenCLWorkGroupLocal: 6443 llvm_unreachable("Unexpected storage class"); 6444 } 6445 if (VD->isConstexpr()) 6446 Error = 5; 6447 if (Error != -1) { 6448 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 6449 << VD->getDeclName() << Error; 6450 D->setInvalidDecl(); 6451 } 6452} 6453 6454void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 6455 if (var->isInvalidDecl()) return; 6456 6457 // In ARC, don't allow jumps past the implicit initialization of a 6458 // local retaining variable. 6459 if (getLangOptions().ObjCAutoRefCount && 6460 var->hasLocalStorage()) { 6461 switch (var->getType().getObjCLifetime()) { 6462 case Qualifiers::OCL_None: 6463 case Qualifiers::OCL_ExplicitNone: 6464 case Qualifiers::OCL_Autoreleasing: 6465 break; 6466 6467 case Qualifiers::OCL_Weak: 6468 case Qualifiers::OCL_Strong: 6469 getCurFunction()->setHasBranchProtectedScope(); 6470 break; 6471 } 6472 } 6473 6474 // All the following checks are C++ only. 6475 if (!getLangOptions().CPlusPlus) return; 6476 6477 QualType baseType = Context.getBaseElementType(var->getType()); 6478 if (baseType->isDependentType()) return; 6479 6480 // __block variables might require us to capture a copy-initializer. 6481 if (var->hasAttr<BlocksAttr>()) { 6482 // It's currently invalid to ever have a __block variable with an 6483 // array type; should we diagnose that here? 6484 6485 // Regardless, we don't want to ignore array nesting when 6486 // constructing this copy. 6487 QualType type = var->getType(); 6488 6489 if (type->isStructureOrClassType()) { 6490 SourceLocation poi = var->getLocation(); 6491 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi); 6492 ExprResult result = 6493 PerformCopyInitialization( 6494 InitializedEntity::InitializeBlock(poi, type, false), 6495 poi, Owned(varRef)); 6496 if (!result.isInvalid()) { 6497 result = MaybeCreateExprWithCleanups(result); 6498 Expr *init = result.takeAs<Expr>(); 6499 Context.setBlockVarCopyInits(var, init); 6500 } 6501 } 6502 } 6503 6504 // Check for global constructors. 6505 if (!var->getDeclContext()->isDependentContext() && 6506 var->hasGlobalStorage() && 6507 !var->isStaticLocal() && 6508 var->getInit() && 6509 !var->getInit()->isConstantInitializer(Context, 6510 baseType->isReferenceType())) 6511 Diag(var->getLocation(), diag::warn_global_constructor) 6512 << var->getInit()->getSourceRange(); 6513 6514 // Require the destructor. 6515 if (const RecordType *recordType = baseType->getAs<RecordType>()) 6516 FinalizeVarWithDestructor(var, recordType); 6517} 6518 6519/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 6520/// any semantic actions necessary after any initializer has been attached. 6521void 6522Sema::FinalizeDeclaration(Decl *ThisDecl) { 6523 // Note that we are no longer parsing the initializer for this declaration. 6524 ParsingInitForAutoVars.erase(ThisDecl); 6525} 6526 6527Sema::DeclGroupPtrTy 6528Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 6529 Decl **Group, unsigned NumDecls) { 6530 SmallVector<Decl*, 8> Decls; 6531 6532 if (DS.isTypeSpecOwned()) 6533 Decls.push_back(DS.getRepAsDecl()); 6534 6535 for (unsigned i = 0; i != NumDecls; ++i) 6536 if (Decl *D = Group[i]) 6537 Decls.push_back(D); 6538 6539 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 6540 DS.getTypeSpecType() == DeclSpec::TST_auto); 6541} 6542 6543/// BuildDeclaratorGroup - convert a list of declarations into a declaration 6544/// group, performing any necessary semantic checking. 6545Sema::DeclGroupPtrTy 6546Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 6547 bool TypeMayContainAuto) { 6548 // C++0x [dcl.spec.auto]p7: 6549 // If the type deduced for the template parameter U is not the same in each 6550 // deduction, the program is ill-formed. 6551 // FIXME: When initializer-list support is added, a distinction is needed 6552 // between the deduced type U and the deduced type which 'auto' stands for. 6553 // auto a = 0, b = { 1, 2, 3 }; 6554 // is legal because the deduced type U is 'int' in both cases. 6555 if (TypeMayContainAuto && NumDecls > 1) { 6556 QualType Deduced; 6557 CanQualType DeducedCanon; 6558 VarDecl *DeducedDecl = 0; 6559 for (unsigned i = 0; i != NumDecls; ++i) { 6560 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 6561 AutoType *AT = D->getType()->getContainedAutoType(); 6562 // Don't reissue diagnostics when instantiating a template. 6563 if (AT && D->isInvalidDecl()) 6564 break; 6565 if (AT && AT->isDeduced()) { 6566 QualType U = AT->getDeducedType(); 6567 CanQualType UCanon = Context.getCanonicalType(U); 6568 if (Deduced.isNull()) { 6569 Deduced = U; 6570 DeducedCanon = UCanon; 6571 DeducedDecl = D; 6572 } else if (DeducedCanon != UCanon) { 6573 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 6574 diag::err_auto_different_deductions) 6575 << Deduced << DeducedDecl->getDeclName() 6576 << U << D->getDeclName() 6577 << DeducedDecl->getInit()->getSourceRange() 6578 << D->getInit()->getSourceRange(); 6579 D->setInvalidDecl(); 6580 break; 6581 } 6582 } 6583 } 6584 } 6585 } 6586 6587 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 6588} 6589 6590 6591/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 6592/// to introduce parameters into function prototype scope. 6593Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 6594 const DeclSpec &DS = D.getDeclSpec(); 6595 6596 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 6597 VarDecl::StorageClass StorageClass = SC_None; 6598 VarDecl::StorageClass StorageClassAsWritten = SC_None; 6599 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 6600 StorageClass = SC_Register; 6601 StorageClassAsWritten = SC_Register; 6602 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 6603 Diag(DS.getStorageClassSpecLoc(), 6604 diag::err_invalid_storage_class_in_func_decl); 6605 D.getMutableDeclSpec().ClearStorageClassSpecs(); 6606 } 6607 6608 if (D.getDeclSpec().isThreadSpecified()) 6609 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 6610 if (D.getDeclSpec().isConstexprSpecified()) 6611 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6612 << 0; 6613 6614 DiagnoseFunctionSpecifiers(D); 6615 6616 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6617 QualType parmDeclType = TInfo->getType(); 6618 6619 if (getLangOptions().CPlusPlus) { 6620 // Check that there are no default arguments inside the type of this 6621 // parameter. 6622 CheckExtraCXXDefaultArguments(D); 6623 6624 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 6625 if (D.getCXXScopeSpec().isSet()) { 6626 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 6627 << D.getCXXScopeSpec().getRange(); 6628 D.getCXXScopeSpec().clear(); 6629 } 6630 } 6631 6632 // Ensure we have a valid name 6633 IdentifierInfo *II = 0; 6634 if (D.hasName()) { 6635 II = D.getIdentifier(); 6636 if (!II) { 6637 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 6638 << GetNameForDeclarator(D).getName().getAsString(); 6639 D.setInvalidType(true); 6640 } 6641 } 6642 6643 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 6644 if (II) { 6645 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 6646 ForRedeclaration); 6647 LookupName(R, S); 6648 if (R.isSingleResult()) { 6649 NamedDecl *PrevDecl = R.getFoundDecl(); 6650 if (PrevDecl->isTemplateParameter()) { 6651 // Maybe we will complain about the shadowed template parameter. 6652 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6653 // Just pretend that we didn't see the previous declaration. 6654 PrevDecl = 0; 6655 } else if (S->isDeclScope(PrevDecl)) { 6656 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 6657 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6658 6659 // Recover by removing the name 6660 II = 0; 6661 D.SetIdentifier(0, D.getIdentifierLoc()); 6662 D.setInvalidType(true); 6663 } 6664 } 6665 } 6666 6667 // Temporarily put parameter variables in the translation unit, not 6668 // the enclosing context. This prevents them from accidentally 6669 // looking like class members in C++. 6670 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 6671 D.getSourceRange().getBegin(), 6672 D.getIdentifierLoc(), II, 6673 parmDeclType, TInfo, 6674 StorageClass, StorageClassAsWritten); 6675 6676 if (D.isInvalidType()) 6677 New->setInvalidDecl(); 6678 6679 assert(S->isFunctionPrototypeScope()); 6680 assert(S->getFunctionPrototypeDepth() >= 1); 6681 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 6682 S->getNextFunctionPrototypeIndex()); 6683 6684 // Add the parameter declaration into this scope. 6685 S->AddDecl(New); 6686 if (II) 6687 IdResolver.AddDecl(New); 6688 6689 ProcessDeclAttributes(S, New, D); 6690 6691 if (D.getDeclSpec().isModulePrivateSpecified()) 6692 Diag(New->getLocation(), diag::err_module_private_local) 6693 << 1 << New->getDeclName() 6694 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6695 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6696 6697 if (New->hasAttr<BlocksAttr>()) { 6698 Diag(New->getLocation(), diag::err_block_on_nonlocal); 6699 } 6700 return New; 6701} 6702 6703/// \brief Synthesizes a variable for a parameter arising from a 6704/// typedef. 6705ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 6706 SourceLocation Loc, 6707 QualType T) { 6708 /* FIXME: setting StartLoc == Loc. 6709 Would it be worth to modify callers so as to provide proper source 6710 location for the unnamed parameters, embedding the parameter's type? */ 6711 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 6712 T, Context.getTrivialTypeSourceInfo(T, Loc), 6713 SC_None, SC_None, 0); 6714 Param->setImplicit(); 6715 return Param; 6716} 6717 6718void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 6719 ParmVarDecl * const *ParamEnd) { 6720 // Don't diagnose unused-parameter errors in template instantiations; we 6721 // will already have done so in the template itself. 6722 if (!ActiveTemplateInstantiations.empty()) 6723 return; 6724 6725 for (; Param != ParamEnd; ++Param) { 6726 if (!(*Param)->isUsed() && (*Param)->getDeclName() && 6727 !(*Param)->hasAttr<UnusedAttr>()) { 6728 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 6729 << (*Param)->getDeclName(); 6730 } 6731 } 6732} 6733 6734void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 6735 ParmVarDecl * const *ParamEnd, 6736 QualType ReturnTy, 6737 NamedDecl *D) { 6738 if (LangOpts.NumLargeByValueCopy == 0) // No check. 6739 return; 6740 6741 // Warn if the return value is pass-by-value and larger than the specified 6742 // threshold. 6743 if (ReturnTy.isPODType(Context)) { 6744 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 6745 if (Size > LangOpts.NumLargeByValueCopy) 6746 Diag(D->getLocation(), diag::warn_return_value_size) 6747 << D->getDeclName() << Size; 6748 } 6749 6750 // Warn if any parameter is pass-by-value and larger than the specified 6751 // threshold. 6752 for (; Param != ParamEnd; ++Param) { 6753 QualType T = (*Param)->getType(); 6754 if (!T.isPODType(Context)) 6755 continue; 6756 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 6757 if (Size > LangOpts.NumLargeByValueCopy) 6758 Diag((*Param)->getLocation(), diag::warn_parameter_size) 6759 << (*Param)->getDeclName() << Size; 6760 } 6761} 6762 6763ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 6764 SourceLocation NameLoc, IdentifierInfo *Name, 6765 QualType T, TypeSourceInfo *TSInfo, 6766 VarDecl::StorageClass StorageClass, 6767 VarDecl::StorageClass StorageClassAsWritten) { 6768 // In ARC, infer a lifetime qualifier for appropriate parameter types. 6769 if (getLangOptions().ObjCAutoRefCount && 6770 T.getObjCLifetime() == Qualifiers::OCL_None && 6771 T->isObjCLifetimeType()) { 6772 6773 Qualifiers::ObjCLifetime lifetime; 6774 6775 // Special cases for arrays: 6776 // - if it's const, use __unsafe_unretained 6777 // - otherwise, it's an error 6778 if (T->isArrayType()) { 6779 if (!T.isConstQualified()) { 6780 DelayedDiagnostics.add( 6781 sema::DelayedDiagnostic::makeForbiddenType( 6782 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 6783 } 6784 lifetime = Qualifiers::OCL_ExplicitNone; 6785 } else { 6786 lifetime = T->getObjCARCImplicitLifetime(); 6787 } 6788 T = Context.getLifetimeQualifiedType(T, lifetime); 6789 } 6790 6791 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 6792 Context.getAdjustedParameterType(T), 6793 TSInfo, 6794 StorageClass, StorageClassAsWritten, 6795 0); 6796 6797 // Parameters can not be abstract class types. 6798 // For record types, this is done by the AbstractClassUsageDiagnoser once 6799 // the class has been completely parsed. 6800 if (!CurContext->isRecord() && 6801 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 6802 AbstractParamType)) 6803 New->setInvalidDecl(); 6804 6805 // Parameter declarators cannot be interface types. All ObjC objects are 6806 // passed by reference. 6807 if (T->isObjCObjectType()) { 6808 Diag(NameLoc, 6809 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 6810 << FixItHint::CreateInsertion(NameLoc, "*"); 6811 T = Context.getObjCObjectPointerType(T); 6812 New->setType(T); 6813 } 6814 6815 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 6816 // duration shall not be qualified by an address-space qualifier." 6817 // Since all parameters have automatic store duration, they can not have 6818 // an address space. 6819 if (T.getAddressSpace() != 0) { 6820 Diag(NameLoc, diag::err_arg_with_address_space); 6821 New->setInvalidDecl(); 6822 } 6823 6824 return New; 6825} 6826 6827void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 6828 SourceLocation LocAfterDecls) { 6829 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6830 6831 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 6832 // for a K&R function. 6833 if (!FTI.hasPrototype) { 6834 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 6835 --i; 6836 if (FTI.ArgInfo[i].Param == 0) { 6837 llvm::SmallString<256> Code; 6838 llvm::raw_svector_ostream(Code) << " int " 6839 << FTI.ArgInfo[i].Ident->getName() 6840 << ";\n"; 6841 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 6842 << FTI.ArgInfo[i].Ident 6843 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 6844 6845 // Implicitly declare the argument as type 'int' for lack of a better 6846 // type. 6847 AttributeFactory attrs; 6848 DeclSpec DS(attrs); 6849 const char* PrevSpec; // unused 6850 unsigned DiagID; // unused 6851 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 6852 PrevSpec, DiagID); 6853 Declarator ParamD(DS, Declarator::KNRTypeListContext); 6854 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 6855 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 6856 } 6857 } 6858 } 6859} 6860 6861Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 6862 Declarator &D) { 6863 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 6864 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 6865 Scope *ParentScope = FnBodyScope->getParent(); 6866 6867 D.setFunctionDefinition(true); 6868 Decl *DP = HandleDeclarator(ParentScope, D, 6869 MultiTemplateParamsArg(*this)); 6870 return ActOnStartOfFunctionDef(FnBodyScope, DP); 6871} 6872 6873static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 6874 // Don't warn about invalid declarations. 6875 if (FD->isInvalidDecl()) 6876 return false; 6877 6878 // Or declarations that aren't global. 6879 if (!FD->isGlobal()) 6880 return false; 6881 6882 // Don't warn about C++ member functions. 6883 if (isa<CXXMethodDecl>(FD)) 6884 return false; 6885 6886 // Don't warn about 'main'. 6887 if (FD->isMain()) 6888 return false; 6889 6890 // Don't warn about inline functions. 6891 if (FD->isInlined()) 6892 return false; 6893 6894 // Don't warn about function templates. 6895 if (FD->getDescribedFunctionTemplate()) 6896 return false; 6897 6898 // Don't warn about function template specializations. 6899 if (FD->isFunctionTemplateSpecialization()) 6900 return false; 6901 6902 bool MissingPrototype = true; 6903 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 6904 Prev; Prev = Prev->getPreviousDeclaration()) { 6905 // Ignore any declarations that occur in function or method 6906 // scope, because they aren't visible from the header. 6907 if (Prev->getDeclContext()->isFunctionOrMethod()) 6908 continue; 6909 6910 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 6911 break; 6912 } 6913 6914 return MissingPrototype; 6915} 6916 6917void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 6918 // Don't complain if we're in GNU89 mode and the previous definition 6919 // was an extern inline function. 6920 const FunctionDecl *Definition; 6921 if (FD->isDefined(Definition) && 6922 !canRedefineFunction(Definition, getLangOptions())) { 6923 if (getLangOptions().GNUMode && Definition->isInlineSpecified() && 6924 Definition->getStorageClass() == SC_Extern) 6925 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 6926 << FD->getDeclName() << getLangOptions().CPlusPlus; 6927 else 6928 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 6929 Diag(Definition->getLocation(), diag::note_previous_definition); 6930 } 6931} 6932 6933Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 6934 // Clear the last template instantiation error context. 6935 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 6936 6937 if (!D) 6938 return D; 6939 FunctionDecl *FD = 0; 6940 6941 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 6942 FD = FunTmpl->getTemplatedDecl(); 6943 else 6944 FD = cast<FunctionDecl>(D); 6945 6946 // Enter a new function scope 6947 PushFunctionScope(); 6948 6949 // See if this is a redefinition. 6950 if (!FD->isLateTemplateParsed()) 6951 CheckForFunctionRedefinition(FD); 6952 6953 // Builtin functions cannot be defined. 6954 if (unsigned BuiltinID = FD->getBuiltinID()) { 6955 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 6956 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 6957 FD->setInvalidDecl(); 6958 } 6959 } 6960 6961 // The return type of a function definition must be complete 6962 // (C99 6.9.1p3, C++ [dcl.fct]p6). 6963 QualType ResultType = FD->getResultType(); 6964 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 6965 !FD->isInvalidDecl() && 6966 RequireCompleteType(FD->getLocation(), ResultType, 6967 diag::err_func_def_incomplete_result)) 6968 FD->setInvalidDecl(); 6969 6970 // GNU warning -Wmissing-prototypes: 6971 // Warn if a global function is defined without a previous 6972 // prototype declaration. This warning is issued even if the 6973 // definition itself provides a prototype. The aim is to detect 6974 // global functions that fail to be declared in header files. 6975 if (ShouldWarnAboutMissingPrototype(FD)) 6976 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 6977 6978 if (FnBodyScope) 6979 PushDeclContext(FnBodyScope, FD); 6980 6981 // Check the validity of our function parameters 6982 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 6983 /*CheckParameterNames=*/true); 6984 6985 // Introduce our parameters into the function scope 6986 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 6987 ParmVarDecl *Param = FD->getParamDecl(p); 6988 Param->setOwningFunction(FD); 6989 6990 // If this has an identifier, add it to the scope stack. 6991 if (Param->getIdentifier() && FnBodyScope) { 6992 CheckShadow(FnBodyScope, Param); 6993 6994 PushOnScopeChains(Param, FnBodyScope); 6995 } 6996 } 6997 6998 // Checking attributes of current function definition 6999 // dllimport attribute. 7000 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 7001 if (DA && (!FD->getAttr<DLLExportAttr>())) { 7002 // dllimport attribute cannot be directly applied to definition. 7003 // Microsoft accepts dllimport for functions defined within class scope. 7004 if (!DA->isInherited() && 7005 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 7006 Diag(FD->getLocation(), 7007 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 7008 << "dllimport"; 7009 FD->setInvalidDecl(); 7010 return FD; 7011 } 7012 7013 // Visual C++ appears to not think this is an issue, so only issue 7014 // a warning when Microsoft extensions are disabled. 7015 if (!LangOpts.MicrosoftExt) { 7016 // If a symbol previously declared dllimport is later defined, the 7017 // attribute is ignored in subsequent references, and a warning is 7018 // emitted. 7019 Diag(FD->getLocation(), 7020 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 7021 << FD->getName() << "dllimport"; 7022 } 7023 } 7024 return FD; 7025} 7026 7027/// \brief Given the set of return statements within a function body, 7028/// compute the variables that are subject to the named return value 7029/// optimization. 7030/// 7031/// Each of the variables that is subject to the named return value 7032/// optimization will be marked as NRVO variables in the AST, and any 7033/// return statement that has a marked NRVO variable as its NRVO candidate can 7034/// use the named return value optimization. 7035/// 7036/// This function applies a very simplistic algorithm for NRVO: if every return 7037/// statement in the function has the same NRVO candidate, that candidate is 7038/// the NRVO variable. 7039/// 7040/// FIXME: Employ a smarter algorithm that accounts for multiple return 7041/// statements and the lifetimes of the NRVO candidates. We should be able to 7042/// find a maximal set of NRVO variables. 7043void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 7044 ReturnStmt **Returns = Scope->Returns.data(); 7045 7046 const VarDecl *NRVOCandidate = 0; 7047 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 7048 if (!Returns[I]->getNRVOCandidate()) 7049 return; 7050 7051 if (!NRVOCandidate) 7052 NRVOCandidate = Returns[I]->getNRVOCandidate(); 7053 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 7054 return; 7055 } 7056 7057 if (NRVOCandidate) 7058 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 7059} 7060 7061Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 7062 return ActOnFinishFunctionBody(D, move(BodyArg), false); 7063} 7064 7065Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 7066 bool IsInstantiation) { 7067 FunctionDecl *FD = 0; 7068 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 7069 if (FunTmpl) 7070 FD = FunTmpl->getTemplatedDecl(); 7071 else 7072 FD = dyn_cast_or_null<FunctionDecl>(dcl); 7073 7074 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 7075 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 7076 7077 if (FD) { 7078 FD->setBody(Body); 7079 if (FD->isMain()) { 7080 // C and C++ allow for main to automagically return 0. 7081 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7082 FD->setHasImplicitReturnZero(true); 7083 WP.disableCheckFallThrough(); 7084 } else if (FD->hasAttr<NakedAttr>()) { 7085 // If the function is marked 'naked', don't complain about missing return 7086 // statements. 7087 WP.disableCheckFallThrough(); 7088 } 7089 7090 // MSVC permits the use of pure specifier (=0) on function definition, 7091 // defined at class scope, warn about this non standard construct. 7092 if (getLangOptions().MicrosoftExt && FD->isPure()) 7093 Diag(FD->getLocation(), diag::warn_pure_function_definition); 7094 7095 if (!FD->isInvalidDecl()) { 7096 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 7097 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 7098 FD->getResultType(), FD); 7099 7100 // If this is a constructor, we need a vtable. 7101 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 7102 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 7103 7104 computeNRVO(Body, getCurFunction()); 7105 } 7106 7107 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 7108 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 7109 assert(MD == getCurMethodDecl() && "Method parsing confused"); 7110 MD->setBody(Body); 7111 if (Body) 7112 MD->setEndLoc(Body->getLocEnd()); 7113 if (!MD->isInvalidDecl()) { 7114 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 7115 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 7116 MD->getResultType(), MD); 7117 7118 if (Body) 7119 computeNRVO(Body, getCurFunction()); 7120 } 7121 if (ObjCShouldCallSuperDealloc) { 7122 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc); 7123 ObjCShouldCallSuperDealloc = false; 7124 } 7125 if (ObjCShouldCallSuperFinalize) { 7126 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize); 7127 ObjCShouldCallSuperFinalize = false; 7128 } 7129 } else { 7130 return 0; 7131 } 7132 7133 assert(!ObjCShouldCallSuperDealloc && "This should only be set for " 7134 "ObjC methods, which should have been handled in the block above."); 7135 assert(!ObjCShouldCallSuperFinalize && "This should only be set for " 7136 "ObjC methods, which should have been handled in the block above."); 7137 7138 // Verify and clean out per-function state. 7139 if (Body) { 7140 // C++ constructors that have function-try-blocks can't have return 7141 // statements in the handlers of that block. (C++ [except.handle]p14) 7142 // Verify this. 7143 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 7144 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 7145 7146 // Verify that gotos and switch cases don't jump into scopes illegally. 7147 if (getCurFunction()->NeedsScopeChecking() && 7148 !dcl->isInvalidDecl() && 7149 !hasAnyUnrecoverableErrorsInThisFunction()) 7150 DiagnoseInvalidJumps(Body); 7151 7152 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 7153 if (!Destructor->getParent()->isDependentType()) 7154 CheckDestructor(Destructor); 7155 7156 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7157 Destructor->getParent()); 7158 } 7159 7160 // If any errors have occurred, clear out any temporaries that may have 7161 // been leftover. This ensures that these temporaries won't be picked up for 7162 // deletion in some later function. 7163 if (PP.getDiagnostics().hasErrorOccurred() || 7164 PP.getDiagnostics().getSuppressAllDiagnostics()) { 7165 ExprTemporaries.clear(); 7166 ExprNeedsCleanups = false; 7167 } else if (!isa<FunctionTemplateDecl>(dcl)) { 7168 // Since the body is valid, issue any analysis-based warnings that are 7169 // enabled. 7170 ActivePolicy = &WP; 7171 } 7172 7173 if (FD && FD->isConstexpr() && !FD->isInvalidDecl() && 7174 !CheckConstexprFunctionBody(FD, Body)) 7175 FD->setInvalidDecl(); 7176 7177 assert(ExprTemporaries.empty() && "Leftover temporaries in function"); 7178 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 7179 } 7180 7181 if (!IsInstantiation) 7182 PopDeclContext(); 7183 7184 PopFunctionOrBlockScope(ActivePolicy, dcl); 7185 7186 // If any errors have occurred, clear out any temporaries that may have 7187 // been leftover. This ensures that these temporaries won't be picked up for 7188 // deletion in some later function. 7189 if (getDiagnostics().hasErrorOccurred()) { 7190 ExprTemporaries.clear(); 7191 ExprNeedsCleanups = false; 7192 } 7193 7194 return dcl; 7195} 7196 7197 7198/// When we finish delayed parsing of an attribute, we must attach it to the 7199/// relevant Decl. 7200void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 7201 ParsedAttributes &Attrs) { 7202 ProcessDeclAttributeList(S, D, Attrs.getList()); 7203} 7204 7205 7206/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 7207/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 7208NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 7209 IdentifierInfo &II, Scope *S) { 7210 // Before we produce a declaration for an implicitly defined 7211 // function, see whether there was a locally-scoped declaration of 7212 // this name as a function or variable. If so, use that 7213 // (non-visible) declaration, and complain about it. 7214 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 7215 = findLocallyScopedExternalDecl(&II); 7216 if (Pos != LocallyScopedExternalDecls.end()) { 7217 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 7218 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 7219 return Pos->second; 7220 } 7221 7222 // Extension in C99. Legal in C90, but warn about it. 7223 if (II.getName().startswith("__builtin_")) 7224 Diag(Loc, diag::warn_builtin_unknown) << &II; 7225 else if (getLangOptions().C99) 7226 Diag(Loc, diag::ext_implicit_function_decl) << &II; 7227 else 7228 Diag(Loc, diag::warn_implicit_function_decl) << &II; 7229 7230 // Set a Declarator for the implicit definition: int foo(); 7231 const char *Dummy; 7232 AttributeFactory attrFactory; 7233 DeclSpec DS(attrFactory); 7234 unsigned DiagID; 7235 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 7236 (void)Error; // Silence warning. 7237 assert(!Error && "Error setting up implicit decl!"); 7238 Declarator D(DS, Declarator::BlockContext); 7239 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 7240 0, 0, true, SourceLocation(), 7241 SourceLocation(), SourceLocation(), 7242 SourceLocation(), 7243 EST_None, SourceLocation(), 7244 0, 0, 0, 0, Loc, Loc, D), 7245 DS.getAttributes(), 7246 SourceLocation()); 7247 D.SetIdentifier(&II, Loc); 7248 7249 // Insert this function into translation-unit scope. 7250 7251 DeclContext *PrevDC = CurContext; 7252 CurContext = Context.getTranslationUnitDecl(); 7253 7254 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 7255 FD->setImplicit(); 7256 7257 CurContext = PrevDC; 7258 7259 AddKnownFunctionAttributes(FD); 7260 7261 return FD; 7262} 7263 7264/// \brief Adds any function attributes that we know a priori based on 7265/// the declaration of this function. 7266/// 7267/// These attributes can apply both to implicitly-declared builtins 7268/// (like __builtin___printf_chk) or to library-declared functions 7269/// like NSLog or printf. 7270/// 7271/// We need to check for duplicate attributes both here and where user-written 7272/// attributes are applied to declarations. 7273void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 7274 if (FD->isInvalidDecl()) 7275 return; 7276 7277 // If this is a built-in function, map its builtin attributes to 7278 // actual attributes. 7279 if (unsigned BuiltinID = FD->getBuiltinID()) { 7280 // Handle printf-formatting attributes. 7281 unsigned FormatIdx; 7282 bool HasVAListArg; 7283 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 7284 if (!FD->getAttr<FormatAttr>()) 7285 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7286 "printf", FormatIdx+1, 7287 HasVAListArg ? 0 : FormatIdx+2)); 7288 } 7289 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 7290 HasVAListArg)) { 7291 if (!FD->getAttr<FormatAttr>()) 7292 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7293 "scanf", FormatIdx+1, 7294 HasVAListArg ? 0 : FormatIdx+2)); 7295 } 7296 7297 // Mark const if we don't care about errno and that is the only 7298 // thing preventing the function from being const. This allows 7299 // IRgen to use LLVM intrinsics for such functions. 7300 if (!getLangOptions().MathErrno && 7301 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 7302 if (!FD->getAttr<ConstAttr>()) 7303 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 7304 } 7305 7306 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 7307 !FD->getAttr<ReturnsTwiceAttr>()) 7308 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 7309 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 7310 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 7311 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 7312 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 7313 } 7314 7315 IdentifierInfo *Name = FD->getIdentifier(); 7316 if (!Name) 7317 return; 7318 if ((!getLangOptions().CPlusPlus && 7319 FD->getDeclContext()->isTranslationUnit()) || 7320 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 7321 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 7322 LinkageSpecDecl::lang_c)) { 7323 // Okay: this could be a libc/libm/Objective-C function we know 7324 // about. 7325 } else 7326 return; 7327 7328 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 7329 // FIXME: NSLog and NSLogv should be target specific 7330 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 7331 // FIXME: We known better than our headers. 7332 const_cast<FormatAttr *>(Format)->setType(Context, "printf"); 7333 } else 7334 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7335 "printf", 1, 7336 Name->isStr("NSLogv") ? 0 : 2)); 7337 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 7338 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 7339 // target-specific builtins, perhaps? 7340 if (!FD->getAttr<FormatAttr>()) 7341 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 7342 "printf", 2, 7343 Name->isStr("vasprintf") ? 0 : 3)); 7344 } 7345} 7346 7347TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 7348 TypeSourceInfo *TInfo) { 7349 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 7350 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 7351 7352 if (!TInfo) { 7353 assert(D.isInvalidType() && "no declarator info for valid type"); 7354 TInfo = Context.getTrivialTypeSourceInfo(T); 7355 } 7356 7357 // Scope manipulation handled by caller. 7358 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 7359 D.getSourceRange().getBegin(), 7360 D.getIdentifierLoc(), 7361 D.getIdentifier(), 7362 TInfo); 7363 7364 // Bail out immediately if we have an invalid declaration. 7365 if (D.isInvalidType()) { 7366 NewTD->setInvalidDecl(); 7367 return NewTD; 7368 } 7369 7370 if (D.getDeclSpec().isModulePrivateSpecified()) { 7371 if (CurContext->isFunctionOrMethod()) 7372 Diag(NewTD->getLocation(), diag::err_module_private_local) 7373 << 2 << NewTD->getDeclName() 7374 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7375 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7376 else 7377 NewTD->setModulePrivate(); 7378 } 7379 7380 // C++ [dcl.typedef]p8: 7381 // If the typedef declaration defines an unnamed class (or 7382 // enum), the first typedef-name declared by the declaration 7383 // to be that class type (or enum type) is used to denote the 7384 // class type (or enum type) for linkage purposes only. 7385 // We need to check whether the type was declared in the declaration. 7386 switch (D.getDeclSpec().getTypeSpecType()) { 7387 case TST_enum: 7388 case TST_struct: 7389 case TST_union: 7390 case TST_class: { 7391 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 7392 7393 // Do nothing if the tag is not anonymous or already has an 7394 // associated typedef (from an earlier typedef in this decl group). 7395 if (tagFromDeclSpec->getIdentifier()) break; 7396 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 7397 7398 // A well-formed anonymous tag must always be a TUK_Definition. 7399 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 7400 7401 // The type must match the tag exactly; no qualifiers allowed. 7402 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 7403 break; 7404 7405 // Otherwise, set this is the anon-decl typedef for the tag. 7406 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 7407 break; 7408 } 7409 7410 default: 7411 break; 7412 } 7413 7414 return NewTD; 7415} 7416 7417 7418/// \brief Determine whether a tag with a given kind is acceptable 7419/// as a redeclaration of the given tag declaration. 7420/// 7421/// \returns true if the new tag kind is acceptable, false otherwise. 7422bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 7423 TagTypeKind NewTag, bool isDefinition, 7424 SourceLocation NewTagLoc, 7425 const IdentifierInfo &Name) { 7426 // C++ [dcl.type.elab]p3: 7427 // The class-key or enum keyword present in the 7428 // elaborated-type-specifier shall agree in kind with the 7429 // declaration to which the name in the elaborated-type-specifier 7430 // refers. This rule also applies to the form of 7431 // elaborated-type-specifier that declares a class-name or 7432 // friend class since it can be construed as referring to the 7433 // definition of the class. Thus, in any 7434 // elaborated-type-specifier, the enum keyword shall be used to 7435 // refer to an enumeration (7.2), the union class-key shall be 7436 // used to refer to a union (clause 9), and either the class or 7437 // struct class-key shall be used to refer to a class (clause 9) 7438 // declared using the class or struct class-key. 7439 TagTypeKind OldTag = Previous->getTagKind(); 7440 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct)) 7441 if (OldTag == NewTag) 7442 return true; 7443 7444 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 7445 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 7446 // Warn about the struct/class tag mismatch. 7447 bool isTemplate = false; 7448 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 7449 isTemplate = Record->getDescribedClassTemplate(); 7450 7451 if (!ActiveTemplateInstantiations.empty()) { 7452 // In a template instantiation, do not offer fix-its for tag mismatches 7453 // since they usually mess up the template instead of fixing the problem. 7454 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 7455 << (NewTag == TTK_Class) << isTemplate << &Name; 7456 return true; 7457 } 7458 7459 if (isDefinition) { 7460 // On definitions, check previous tags and issue a fix-it for each 7461 // one that doesn't match the current tag. 7462 if (Previous->getDefinition()) { 7463 // Don't suggest fix-its for redefinitions. 7464 return true; 7465 } 7466 7467 bool previousMismatch = false; 7468 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 7469 E(Previous->redecls_end()); I != E; ++I) { 7470 if (I->getTagKind() != NewTag) { 7471 if (!previousMismatch) { 7472 previousMismatch = true; 7473 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 7474 << (NewTag == TTK_Class) << isTemplate << &Name; 7475 } 7476 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 7477 << (NewTag == TTK_Class) 7478 << FixItHint::CreateReplacement(I->getInnerLocStart(), 7479 NewTag == TTK_Class? 7480 "class" : "struct"); 7481 } 7482 } 7483 return true; 7484 } 7485 7486 // Check for a previous definition. If current tag and definition 7487 // are same type, do nothing. If no definition, but disagree with 7488 // with previous tag type, give a warning, but no fix-it. 7489 const TagDecl *Redecl = Previous->getDefinition() ? 7490 Previous->getDefinition() : Previous; 7491 if (Redecl->getTagKind() == NewTag) { 7492 return true; 7493 } 7494 7495 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 7496 << (NewTag == TTK_Class) 7497 << isTemplate << &Name; 7498 Diag(Redecl->getLocation(), diag::note_previous_use); 7499 7500 // If there is a previous defintion, suggest a fix-it. 7501 if (Previous->getDefinition()) { 7502 Diag(NewTagLoc, diag::note_struct_class_suggestion) 7503 << (Redecl->getTagKind() == TTK_Class) 7504 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 7505 Redecl->getTagKind() == TTK_Class? "class" : "struct"); 7506 } 7507 7508 return true; 7509 } 7510 return false; 7511} 7512 7513/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 7514/// former case, Name will be non-null. In the later case, Name will be null. 7515/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 7516/// reference/declaration/definition of a tag. 7517Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 7518 SourceLocation KWLoc, CXXScopeSpec &SS, 7519 IdentifierInfo *Name, SourceLocation NameLoc, 7520 AttributeList *Attr, AccessSpecifier AS, 7521 SourceLocation ModulePrivateLoc, 7522 MultiTemplateParamsArg TemplateParameterLists, 7523 bool &OwnedDecl, bool &IsDependent, 7524 bool ScopedEnum, bool ScopedEnumUsesClassTag, 7525 TypeResult UnderlyingType) { 7526 // If this is not a definition, it must have a name. 7527 assert((Name != 0 || TUK == TUK_Definition) && 7528 "Nameless record must be a definition!"); 7529 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 7530 7531 OwnedDecl = false; 7532 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 7533 7534 // FIXME: Check explicit specializations more carefully. 7535 bool isExplicitSpecialization = false; 7536 bool Invalid = false; 7537 7538 // We only need to do this matching if we have template parameters 7539 // or a scope specifier, which also conveniently avoids this work 7540 // for non-C++ cases. 7541 if (TemplateParameterLists.size() > 0 || 7542 (SS.isNotEmpty() && TUK != TUK_Reference)) { 7543 if (TemplateParameterList *TemplateParams 7544 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 7545 TemplateParameterLists.get(), 7546 TemplateParameterLists.size(), 7547 TUK == TUK_Friend, 7548 isExplicitSpecialization, 7549 Invalid)) { 7550 if (TemplateParams->size() > 0) { 7551 // This is a declaration or definition of a class template (which may 7552 // be a member of another template). 7553 7554 if (Invalid) 7555 return 0; 7556 7557 OwnedDecl = false; 7558 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 7559 SS, Name, NameLoc, Attr, 7560 TemplateParams, AS, 7561 ModulePrivateLoc, 7562 TemplateParameterLists.size() - 1, 7563 (TemplateParameterList**) TemplateParameterLists.release()); 7564 return Result.get(); 7565 } else { 7566 // The "template<>" header is extraneous. 7567 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 7568 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 7569 isExplicitSpecialization = true; 7570 } 7571 } 7572 } 7573 7574 // Figure out the underlying type if this a enum declaration. We need to do 7575 // this early, because it's needed to detect if this is an incompatible 7576 // redeclaration. 7577 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 7578 7579 if (Kind == TTK_Enum) { 7580 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 7581 // No underlying type explicitly specified, or we failed to parse the 7582 // type, default to int. 7583 EnumUnderlying = Context.IntTy.getTypePtr(); 7584 else if (UnderlyingType.get()) { 7585 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 7586 // integral type; any cv-qualification is ignored. 7587 TypeSourceInfo *TI = 0; 7588 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI); 7589 EnumUnderlying = TI; 7590 7591 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 7592 7593 if (!T->isDependentType() && !T->isIntegralType(Context)) { 7594 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 7595 << T; 7596 // Recover by falling back to int. 7597 EnumUnderlying = Context.IntTy.getTypePtr(); 7598 } 7599 7600 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI, 7601 UPPC_FixedUnderlyingType)) 7602 EnumUnderlying = Context.IntTy.getTypePtr(); 7603 7604 } else if (getLangOptions().MicrosoftExt) 7605 // Microsoft enums are always of int type. 7606 EnumUnderlying = Context.IntTy.getTypePtr(); 7607 } 7608 7609 DeclContext *SearchDC = CurContext; 7610 DeclContext *DC = CurContext; 7611 bool isStdBadAlloc = false; 7612 7613 RedeclarationKind Redecl = ForRedeclaration; 7614 if (TUK == TUK_Friend || TUK == TUK_Reference) 7615 Redecl = NotForRedeclaration; 7616 7617 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 7618 7619 if (Name && SS.isNotEmpty()) { 7620 // We have a nested-name tag ('struct foo::bar'). 7621 7622 // Check for invalid 'foo::'. 7623 if (SS.isInvalid()) { 7624 Name = 0; 7625 goto CreateNewDecl; 7626 } 7627 7628 // If this is a friend or a reference to a class in a dependent 7629 // context, don't try to make a decl for it. 7630 if (TUK == TUK_Friend || TUK == TUK_Reference) { 7631 DC = computeDeclContext(SS, false); 7632 if (!DC) { 7633 IsDependent = true; 7634 return 0; 7635 } 7636 } else { 7637 DC = computeDeclContext(SS, true); 7638 if (!DC) { 7639 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 7640 << SS.getRange(); 7641 return 0; 7642 } 7643 } 7644 7645 if (RequireCompleteDeclContext(SS, DC)) 7646 return 0; 7647 7648 SearchDC = DC; 7649 // Look-up name inside 'foo::'. 7650 LookupQualifiedName(Previous, DC); 7651 7652 if (Previous.isAmbiguous()) 7653 return 0; 7654 7655 if (Previous.empty()) { 7656 // Name lookup did not find anything. However, if the 7657 // nested-name-specifier refers to the current instantiation, 7658 // and that current instantiation has any dependent base 7659 // classes, we might find something at instantiation time: treat 7660 // this as a dependent elaborated-type-specifier. 7661 // But this only makes any sense for reference-like lookups. 7662 if (Previous.wasNotFoundInCurrentInstantiation() && 7663 (TUK == TUK_Reference || TUK == TUK_Friend)) { 7664 IsDependent = true; 7665 return 0; 7666 } 7667 7668 // A tag 'foo::bar' must already exist. 7669 Diag(NameLoc, diag::err_not_tag_in_scope) 7670 << Kind << Name << DC << SS.getRange(); 7671 Name = 0; 7672 Invalid = true; 7673 goto CreateNewDecl; 7674 } 7675 } else if (Name) { 7676 // If this is a named struct, check to see if there was a previous forward 7677 // declaration or definition. 7678 // FIXME: We're looking into outer scopes here, even when we 7679 // shouldn't be. Doing so can result in ambiguities that we 7680 // shouldn't be diagnosing. 7681 LookupName(Previous, S); 7682 7683 if (Previous.isAmbiguous() && 7684 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 7685 LookupResult::Filter F = Previous.makeFilter(); 7686 while (F.hasNext()) { 7687 NamedDecl *ND = F.next(); 7688 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 7689 F.erase(); 7690 } 7691 F.done(); 7692 } 7693 7694 // Note: there used to be some attempt at recovery here. 7695 if (Previous.isAmbiguous()) 7696 return 0; 7697 7698 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 7699 // FIXME: This makes sure that we ignore the contexts associated 7700 // with C structs, unions, and enums when looking for a matching 7701 // tag declaration or definition. See the similar lookup tweak 7702 // in Sema::LookupName; is there a better way to deal with this? 7703 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 7704 SearchDC = SearchDC->getParent(); 7705 } 7706 } else if (S->isFunctionPrototypeScope()) { 7707 // If this is an enum declaration in function prototype scope, set its 7708 // initial context to the translation unit. 7709 SearchDC = Context.getTranslationUnitDecl(); 7710 } 7711 7712 if (Previous.isSingleResult() && 7713 Previous.getFoundDecl()->isTemplateParameter()) { 7714 // Maybe we will complain about the shadowed template parameter. 7715 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 7716 // Just pretend that we didn't see the previous declaration. 7717 Previous.clear(); 7718 } 7719 7720 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 7721 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 7722 // This is a declaration of or a reference to "std::bad_alloc". 7723 isStdBadAlloc = true; 7724 7725 if (Previous.empty() && StdBadAlloc) { 7726 // std::bad_alloc has been implicitly declared (but made invisible to 7727 // name lookup). Fill in this implicit declaration as the previous 7728 // declaration, so that the declarations get chained appropriately. 7729 Previous.addDecl(getStdBadAlloc()); 7730 } 7731 } 7732 7733 // If we didn't find a previous declaration, and this is a reference 7734 // (or friend reference), move to the correct scope. In C++, we 7735 // also need to do a redeclaration lookup there, just in case 7736 // there's a shadow friend decl. 7737 if (Name && Previous.empty() && 7738 (TUK == TUK_Reference || TUK == TUK_Friend)) { 7739 if (Invalid) goto CreateNewDecl; 7740 assert(SS.isEmpty()); 7741 7742 if (TUK == TUK_Reference) { 7743 // C++ [basic.scope.pdecl]p5: 7744 // -- for an elaborated-type-specifier of the form 7745 // 7746 // class-key identifier 7747 // 7748 // if the elaborated-type-specifier is used in the 7749 // decl-specifier-seq or parameter-declaration-clause of a 7750 // function defined in namespace scope, the identifier is 7751 // declared as a class-name in the namespace that contains 7752 // the declaration; otherwise, except as a friend 7753 // declaration, the identifier is declared in the smallest 7754 // non-class, non-function-prototype scope that contains the 7755 // declaration. 7756 // 7757 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 7758 // C structs and unions. 7759 // 7760 // It is an error in C++ to declare (rather than define) an enum 7761 // type, including via an elaborated type specifier. We'll 7762 // diagnose that later; for now, declare the enum in the same 7763 // scope as we would have picked for any other tag type. 7764 // 7765 // GNU C also supports this behavior as part of its incomplete 7766 // enum types extension, while GNU C++ does not. 7767 // 7768 // Find the context where we'll be declaring the tag. 7769 // FIXME: We would like to maintain the current DeclContext as the 7770 // lexical context, 7771 while (SearchDC->isRecord() || SearchDC->isTransparentContext()) 7772 SearchDC = SearchDC->getParent(); 7773 7774 // Find the scope where we'll be declaring the tag. 7775 while (S->isClassScope() || 7776 (getLangOptions().CPlusPlus && 7777 S->isFunctionPrototypeScope()) || 7778 ((S->getFlags() & Scope::DeclScope) == 0) || 7779 (S->getEntity() && 7780 ((DeclContext *)S->getEntity())->isTransparentContext())) 7781 S = S->getParent(); 7782 } else { 7783 assert(TUK == TUK_Friend); 7784 // C++ [namespace.memdef]p3: 7785 // If a friend declaration in a non-local class first declares a 7786 // class or function, the friend class or function is a member of 7787 // the innermost enclosing namespace. 7788 SearchDC = SearchDC->getEnclosingNamespaceContext(); 7789 } 7790 7791 // In C++, we need to do a redeclaration lookup to properly 7792 // diagnose some problems. 7793 if (getLangOptions().CPlusPlus) { 7794 Previous.setRedeclarationKind(ForRedeclaration); 7795 LookupQualifiedName(Previous, SearchDC); 7796 } 7797 } 7798 7799 if (!Previous.empty()) { 7800 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 7801 7802 // It's okay to have a tag decl in the same scope as a typedef 7803 // which hides a tag decl in the same scope. Finding this 7804 // insanity with a redeclaration lookup can only actually happen 7805 // in C++. 7806 // 7807 // This is also okay for elaborated-type-specifiers, which is 7808 // technically forbidden by the current standard but which is 7809 // okay according to the likely resolution of an open issue; 7810 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 7811 if (getLangOptions().CPlusPlus) { 7812 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7813 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 7814 TagDecl *Tag = TT->getDecl(); 7815 if (Tag->getDeclName() == Name && 7816 Tag->getDeclContext()->getRedeclContext() 7817 ->Equals(TD->getDeclContext()->getRedeclContext())) { 7818 PrevDecl = Tag; 7819 Previous.clear(); 7820 Previous.addDecl(Tag); 7821 Previous.resolveKind(); 7822 } 7823 } 7824 } 7825 } 7826 7827 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 7828 // If this is a use of a previous tag, or if the tag is already declared 7829 // in the same scope (so that the definition/declaration completes or 7830 // rementions the tag), reuse the decl. 7831 if (TUK == TUK_Reference || TUK == TUK_Friend || 7832 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 7833 // Make sure that this wasn't declared as an enum and now used as a 7834 // struct or something similar. 7835 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 7836 TUK == TUK_Definition, KWLoc, 7837 *Name)) { 7838 bool SafeToContinue 7839 = (PrevTagDecl->getTagKind() != TTK_Enum && 7840 Kind != TTK_Enum); 7841 if (SafeToContinue) 7842 Diag(KWLoc, diag::err_use_with_wrong_tag) 7843 << Name 7844 << FixItHint::CreateReplacement(SourceRange(KWLoc), 7845 PrevTagDecl->getKindName()); 7846 else 7847 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 7848 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7849 7850 if (SafeToContinue) 7851 Kind = PrevTagDecl->getTagKind(); 7852 else { 7853 // Recover by making this an anonymous redefinition. 7854 Name = 0; 7855 Previous.clear(); 7856 Invalid = true; 7857 } 7858 } 7859 7860 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 7861 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 7862 7863 // All conflicts with previous declarations are recovered by 7864 // returning the previous declaration. 7865 if (ScopedEnum != PrevEnum->isScoped()) { 7866 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch) 7867 << PrevEnum->isScoped(); 7868 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7869 return PrevTagDecl; 7870 } 7871 else if (EnumUnderlying && PrevEnum->isFixed()) { 7872 QualType T; 7873 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 7874 T = TI->getType(); 7875 else 7876 T = QualType(EnumUnderlying.get<const Type*>(), 0); 7877 7878 if (!Context.hasSameUnqualifiedType(T, 7879 PrevEnum->getIntegerType())) { 7880 Diag(NameLoc.isValid() ? NameLoc : KWLoc, 7881 diag::err_enum_redeclare_type_mismatch) 7882 << T 7883 << PrevEnum->getIntegerType(); 7884 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7885 return PrevTagDecl; 7886 } 7887 } 7888 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) { 7889 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch) 7890 << PrevEnum->isFixed(); 7891 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7892 return PrevTagDecl; 7893 } 7894 } 7895 7896 if (!Invalid) { 7897 // If this is a use, just return the declaration we found. 7898 7899 // FIXME: In the future, return a variant or some other clue 7900 // for the consumer of this Decl to know it doesn't own it. 7901 // For our current ASTs this shouldn't be a problem, but will 7902 // need to be changed with DeclGroups. 7903 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 7904 getLangOptions().MicrosoftExt)) || TUK == TUK_Friend) 7905 return PrevTagDecl; 7906 7907 // Diagnose attempts to redefine a tag. 7908 if (TUK == TUK_Definition) { 7909 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 7910 // If we're defining a specialization and the previous definition 7911 // is from an implicit instantiation, don't emit an error 7912 // here; we'll catch this in the general case below. 7913 if (!isExplicitSpecialization || 7914 !isa<CXXRecordDecl>(Def) || 7915 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 7916 == TSK_ExplicitSpecialization) { 7917 Diag(NameLoc, diag::err_redefinition) << Name; 7918 Diag(Def->getLocation(), diag::note_previous_definition); 7919 // If this is a redefinition, recover by making this 7920 // struct be anonymous, which will make any later 7921 // references get the previous definition. 7922 Name = 0; 7923 Previous.clear(); 7924 Invalid = true; 7925 } 7926 } else { 7927 // If the type is currently being defined, complain 7928 // about a nested redefinition. 7929 const TagType *Tag 7930 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 7931 if (Tag->isBeingDefined()) { 7932 Diag(NameLoc, diag::err_nested_redefinition) << Name; 7933 Diag(PrevTagDecl->getLocation(), 7934 diag::note_previous_definition); 7935 Name = 0; 7936 Previous.clear(); 7937 Invalid = true; 7938 } 7939 } 7940 7941 // Okay, this is definition of a previously declared or referenced 7942 // tag PrevDecl. We're going to create a new Decl for it. 7943 } 7944 } 7945 // If we get here we have (another) forward declaration or we 7946 // have a definition. Just create a new decl. 7947 7948 } else { 7949 // If we get here, this is a definition of a new tag type in a nested 7950 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 7951 // new decl/type. We set PrevDecl to NULL so that the entities 7952 // have distinct types. 7953 Previous.clear(); 7954 } 7955 // If we get here, we're going to create a new Decl. If PrevDecl 7956 // is non-NULL, it's a definition of the tag declared by 7957 // PrevDecl. If it's NULL, we have a new definition. 7958 7959 7960 // Otherwise, PrevDecl is not a tag, but was found with tag 7961 // lookup. This is only actually possible in C++, where a few 7962 // things like templates still live in the tag namespace. 7963 } else { 7964 assert(getLangOptions().CPlusPlus); 7965 7966 // Use a better diagnostic if an elaborated-type-specifier 7967 // found the wrong kind of type on the first 7968 // (non-redeclaration) lookup. 7969 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 7970 !Previous.isForRedeclaration()) { 7971 unsigned Kind = 0; 7972 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 7973 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 7974 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 7975 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 7976 Diag(PrevDecl->getLocation(), diag::note_declared_at); 7977 Invalid = true; 7978 7979 // Otherwise, only diagnose if the declaration is in scope. 7980 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 7981 isExplicitSpecialization)) { 7982 // do nothing 7983 7984 // Diagnose implicit declarations introduced by elaborated types. 7985 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 7986 unsigned Kind = 0; 7987 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 7988 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 7989 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 7990 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 7991 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 7992 Invalid = true; 7993 7994 // Otherwise it's a declaration. Call out a particularly common 7995 // case here. 7996 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7997 unsigned Kind = 0; 7998 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 7999 Diag(NameLoc, diag::err_tag_definition_of_typedef) 8000 << Name << Kind << TND->getUnderlyingType(); 8001 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 8002 Invalid = true; 8003 8004 // Otherwise, diagnose. 8005 } else { 8006 // The tag name clashes with something else in the target scope, 8007 // issue an error and recover by making this tag be anonymous. 8008 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 8009 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8010 Name = 0; 8011 Invalid = true; 8012 } 8013 8014 // The existing declaration isn't relevant to us; we're in a 8015 // new scope, so clear out the previous declaration. 8016 Previous.clear(); 8017 } 8018 } 8019 8020CreateNewDecl: 8021 8022 TagDecl *PrevDecl = 0; 8023 if (Previous.isSingleResult()) 8024 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 8025 8026 // If there is an identifier, use the location of the identifier as the 8027 // location of the decl, otherwise use the location of the struct/union 8028 // keyword. 8029 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 8030 8031 // Otherwise, create a new declaration. If there is a previous 8032 // declaration of the same entity, the two will be linked via 8033 // PrevDecl. 8034 TagDecl *New; 8035 8036 bool IsForwardReference = false; 8037 if (Kind == TTK_Enum) { 8038 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 8039 // enum X { A, B, C } D; D should chain to X. 8040 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 8041 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 8042 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 8043 // If this is an undefined enum, warn. 8044 if (TUK != TUK_Definition && !Invalid) { 8045 TagDecl *Def; 8046 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) { 8047 // C++0x: 7.2p2: opaque-enum-declaration. 8048 // Conflicts are diagnosed above. Do nothing. 8049 } 8050 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 8051 Diag(Loc, diag::ext_forward_ref_enum_def) 8052 << New; 8053 Diag(Def->getLocation(), diag::note_previous_definition); 8054 } else { 8055 unsigned DiagID = diag::ext_forward_ref_enum; 8056 if (getLangOptions().MicrosoftExt) 8057 DiagID = diag::ext_ms_forward_ref_enum; 8058 else if (getLangOptions().CPlusPlus) 8059 DiagID = diag::err_forward_ref_enum; 8060 Diag(Loc, DiagID); 8061 8062 // If this is a forward-declared reference to an enumeration, make a 8063 // note of it; we won't actually be introducing the declaration into 8064 // the declaration context. 8065 if (TUK == TUK_Reference) 8066 IsForwardReference = true; 8067 } 8068 } 8069 8070 if (EnumUnderlying) { 8071 EnumDecl *ED = cast<EnumDecl>(New); 8072 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 8073 ED->setIntegerTypeSourceInfo(TI); 8074 else 8075 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 8076 ED->setPromotionType(ED->getIntegerType()); 8077 } 8078 8079 } else { 8080 // struct/union/class 8081 8082 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 8083 // struct X { int A; } D; D should chain to X. 8084 if (getLangOptions().CPlusPlus) { 8085 // FIXME: Look for a way to use RecordDecl for simple structs. 8086 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 8087 cast_or_null<CXXRecordDecl>(PrevDecl)); 8088 8089 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 8090 StdBadAlloc = cast<CXXRecordDecl>(New); 8091 } else 8092 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 8093 cast_or_null<RecordDecl>(PrevDecl)); 8094 } 8095 8096 // Maybe add qualifier info. 8097 if (SS.isNotEmpty()) { 8098 if (SS.isSet()) { 8099 New->setQualifierInfo(SS.getWithLocInContext(Context)); 8100 if (TemplateParameterLists.size() > 0) { 8101 New->setTemplateParameterListsInfo(Context, 8102 TemplateParameterLists.size(), 8103 (TemplateParameterList**) TemplateParameterLists.release()); 8104 } 8105 } 8106 else 8107 Invalid = true; 8108 } 8109 8110 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 8111 // Add alignment attributes if necessary; these attributes are checked when 8112 // the ASTContext lays out the structure. 8113 // 8114 // It is important for implementing the correct semantics that this 8115 // happen here (in act on tag decl). The #pragma pack stack is 8116 // maintained as a result of parser callbacks which can occur at 8117 // many points during the parsing of a struct declaration (because 8118 // the #pragma tokens are effectively skipped over during the 8119 // parsing of the struct). 8120 AddAlignmentAttributesForRecord(RD); 8121 8122 AddMsStructLayoutForRecord(RD); 8123 } 8124 8125 if (PrevDecl && PrevDecl->isModulePrivate()) 8126 New->setModulePrivate(); 8127 else if (ModulePrivateLoc.isValid()) { 8128 if (isExplicitSpecialization) 8129 Diag(New->getLocation(), diag::err_module_private_specialization) 8130 << 2 8131 << FixItHint::CreateRemoval(ModulePrivateLoc); 8132 else if (PrevDecl && !PrevDecl->isModulePrivate()) 8133 diagnoseModulePrivateRedeclaration(New, PrevDecl, ModulePrivateLoc); 8134 // __module_private__ does not apply to local classes. However, we only 8135 // diagnose this as an error when the declaration specifiers are 8136 // freestanding. Here, we just ignore the __module_private__. 8137 // foobar 8138 else if (!SearchDC->isFunctionOrMethod()) 8139 New->setModulePrivate(); 8140 } 8141 8142 // If this is a specialization of a member class (of a class template), 8143 // check the specialization. 8144 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 8145 Invalid = true; 8146 8147 if (Invalid) 8148 New->setInvalidDecl(); 8149 8150 if (Attr) 8151 ProcessDeclAttributeList(S, New, Attr); 8152 8153 // If we're declaring or defining a tag in function prototype scope 8154 // in C, note that this type can only be used within the function. 8155 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 8156 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 8157 8158 // Set the lexical context. If the tag has a C++ scope specifier, the 8159 // lexical context will be different from the semantic context. 8160 New->setLexicalDeclContext(CurContext); 8161 8162 // Mark this as a friend decl if applicable. 8163 // In Microsoft mode, a friend declaration also acts as a forward 8164 // declaration so we always pass true to setObjectOfFriendDecl to make 8165 // the tag name visible. 8166 if (TUK == TUK_Friend) 8167 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 8168 getLangOptions().MicrosoftExt); 8169 8170 // Set the access specifier. 8171 if (!Invalid && SearchDC->isRecord()) 8172 SetMemberAccessSpecifier(New, PrevDecl, AS); 8173 8174 if (TUK == TUK_Definition) 8175 New->startDefinition(); 8176 8177 // If this has an identifier, add it to the scope stack. 8178 if (TUK == TUK_Friend) { 8179 // We might be replacing an existing declaration in the lookup tables; 8180 // if so, borrow its access specifier. 8181 if (PrevDecl) 8182 New->setAccess(PrevDecl->getAccess()); 8183 8184 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 8185 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 8186 if (Name) // can be null along some error paths 8187 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 8188 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 8189 } else if (Name) { 8190 S = getNonFieldDeclScope(S); 8191 PushOnScopeChains(New, S, !IsForwardReference); 8192 if (IsForwardReference) 8193 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 8194 8195 } else { 8196 CurContext->addDecl(New); 8197 } 8198 8199 // If this is the C FILE type, notify the AST context. 8200 if (IdentifierInfo *II = New->getIdentifier()) 8201 if (!New->isInvalidDecl() && 8202 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 8203 II->isStr("FILE")) 8204 Context.setFILEDecl(New); 8205 8206 OwnedDecl = true; 8207 return New; 8208} 8209 8210void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 8211 AdjustDeclIfTemplate(TagD); 8212 TagDecl *Tag = cast<TagDecl>(TagD); 8213 8214 // Enter the tag context. 8215 PushDeclContext(S, Tag); 8216} 8217 8218Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 8219 assert(isa<ObjCContainerDecl>(IDecl) && 8220 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 8221 DeclContext *OCD = cast<DeclContext>(IDecl); 8222 assert(getContainingDC(OCD) == CurContext && 8223 "The next DeclContext should be lexically contained in the current one."); 8224 CurContext = OCD; 8225 return IDecl; 8226} 8227 8228void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 8229 SourceLocation FinalLoc, 8230 SourceLocation LBraceLoc) { 8231 AdjustDeclIfTemplate(TagD); 8232 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 8233 8234 FieldCollector->StartClass(); 8235 8236 if (!Record->getIdentifier()) 8237 return; 8238 8239 if (FinalLoc.isValid()) 8240 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 8241 8242 // C++ [class]p2: 8243 // [...] The class-name is also inserted into the scope of the 8244 // class itself; this is known as the injected-class-name. For 8245 // purposes of access checking, the injected-class-name is treated 8246 // as if it were a public member name. 8247 CXXRecordDecl *InjectedClassName 8248 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 8249 Record->getLocStart(), Record->getLocation(), 8250 Record->getIdentifier(), 8251 /*PrevDecl=*/0, 8252 /*DelayTypeCreation=*/true); 8253 Context.getTypeDeclType(InjectedClassName, Record); 8254 InjectedClassName->setImplicit(); 8255 InjectedClassName->setAccess(AS_public); 8256 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 8257 InjectedClassName->setDescribedClassTemplate(Template); 8258 PushOnScopeChains(InjectedClassName, S); 8259 assert(InjectedClassName->isInjectedClassName() && 8260 "Broken injected-class-name"); 8261} 8262 8263void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 8264 SourceLocation RBraceLoc) { 8265 AdjustDeclIfTemplate(TagD); 8266 TagDecl *Tag = cast<TagDecl>(TagD); 8267 Tag->setRBraceLoc(RBraceLoc); 8268 8269 if (isa<CXXRecordDecl>(Tag)) 8270 FieldCollector->FinishClass(); 8271 8272 // Exit this scope of this tag's definition. 8273 PopDeclContext(); 8274 8275 // Notify the consumer that we've defined a tag. 8276 Consumer.HandleTagDeclDefinition(Tag); 8277} 8278 8279void Sema::ActOnObjCContainerFinishDefinition() { 8280 // Exit this scope of this interface definition. 8281 PopDeclContext(); 8282} 8283 8284void Sema::ActOnObjCTemporaryExitContainerContext() { 8285 OriginalLexicalContext = CurContext; 8286 ActOnObjCContainerFinishDefinition(); 8287} 8288 8289void Sema::ActOnObjCReenterContainerContext() { 8290 ActOnObjCContainerStartDefinition(cast<Decl>(OriginalLexicalContext)); 8291 OriginalLexicalContext = 0; 8292} 8293 8294void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 8295 AdjustDeclIfTemplate(TagD); 8296 TagDecl *Tag = cast<TagDecl>(TagD); 8297 Tag->setInvalidDecl(); 8298 8299 // We're undoing ActOnTagStartDefinition here, not 8300 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 8301 // the FieldCollector. 8302 8303 PopDeclContext(); 8304} 8305 8306// Note that FieldName may be null for anonymous bitfields. 8307bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 8308 QualType FieldTy, const Expr *BitWidth, 8309 bool *ZeroWidth) { 8310 // Default to true; that shouldn't confuse checks for emptiness 8311 if (ZeroWidth) 8312 *ZeroWidth = true; 8313 8314 // C99 6.7.2.1p4 - verify the field type. 8315 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 8316 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 8317 // Handle incomplete types with specific error. 8318 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 8319 return true; 8320 if (FieldName) 8321 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 8322 << FieldName << FieldTy << BitWidth->getSourceRange(); 8323 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 8324 << FieldTy << BitWidth->getSourceRange(); 8325 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 8326 UPPC_BitFieldWidth)) 8327 return true; 8328 8329 // If the bit-width is type- or value-dependent, don't try to check 8330 // it now. 8331 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 8332 return false; 8333 8334 llvm::APSInt Value; 8335 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 8336 return true; 8337 8338 if (Value != 0 && ZeroWidth) 8339 *ZeroWidth = false; 8340 8341 // Zero-width bitfield is ok for anonymous field. 8342 if (Value == 0 && FieldName) 8343 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 8344 8345 if (Value.isSigned() && Value.isNegative()) { 8346 if (FieldName) 8347 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 8348 << FieldName << Value.toString(10); 8349 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 8350 << Value.toString(10); 8351 } 8352 8353 if (!FieldTy->isDependentType()) { 8354 uint64_t TypeSize = Context.getTypeSize(FieldTy); 8355 if (Value.getZExtValue() > TypeSize) { 8356 if (!getLangOptions().CPlusPlus) { 8357 if (FieldName) 8358 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 8359 << FieldName << (unsigned)Value.getZExtValue() 8360 << (unsigned)TypeSize; 8361 8362 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 8363 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 8364 } 8365 8366 if (FieldName) 8367 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 8368 << FieldName << (unsigned)Value.getZExtValue() 8369 << (unsigned)TypeSize; 8370 else 8371 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 8372 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 8373 } 8374 } 8375 8376 return false; 8377} 8378 8379/// ActOnField - Each field of a C struct/union is passed into this in order 8380/// to create a FieldDecl object for it. 8381Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 8382 Declarator &D, Expr *BitfieldWidth) { 8383 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 8384 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 8385 /*HasInit=*/false, AS_public); 8386 return Res; 8387} 8388 8389/// HandleField - Analyze a field of a C struct or a C++ data member. 8390/// 8391FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 8392 SourceLocation DeclStart, 8393 Declarator &D, Expr *BitWidth, bool HasInit, 8394 AccessSpecifier AS) { 8395 IdentifierInfo *II = D.getIdentifier(); 8396 SourceLocation Loc = DeclStart; 8397 if (II) Loc = D.getIdentifierLoc(); 8398 8399 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8400 QualType T = TInfo->getType(); 8401 if (getLangOptions().CPlusPlus) { 8402 CheckExtraCXXDefaultArguments(D); 8403 8404 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 8405 UPPC_DataMemberType)) { 8406 D.setInvalidType(); 8407 T = Context.IntTy; 8408 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 8409 } 8410 } 8411 8412 DiagnoseFunctionSpecifiers(D); 8413 8414 if (D.getDeclSpec().isThreadSpecified()) 8415 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 8416 if (D.getDeclSpec().isConstexprSpecified()) 8417 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 8418 << 2; 8419 8420 // Check to see if this name was declared as a member previously 8421 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 8422 LookupName(Previous, S); 8423 assert((Previous.empty() || Previous.isOverloadedResult() || 8424 Previous.isSingleResult()) 8425 && "Lookup of member name should be either overloaded, single or null"); 8426 8427 // If the name is overloaded then get any declaration else get the single 8428 // result 8429 NamedDecl *PrevDecl = Previous.isOverloadedResult() ? 8430 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>(); 8431 8432 if (PrevDecl && PrevDecl->isTemplateParameter()) { 8433 // Maybe we will complain about the shadowed template parameter. 8434 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 8435 // Just pretend that we didn't see the previous declaration. 8436 PrevDecl = 0; 8437 } 8438 8439 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 8440 PrevDecl = 0; 8441 8442 bool Mutable 8443 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 8444 SourceLocation TSSL = D.getSourceRange().getBegin(); 8445 FieldDecl *NewFD 8446 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit, 8447 TSSL, AS, PrevDecl, &D); 8448 8449 if (NewFD->isInvalidDecl()) 8450 Record->setInvalidDecl(); 8451 8452 if (D.getDeclSpec().isModulePrivateSpecified()) 8453 NewFD->setModulePrivate(); 8454 8455 if (NewFD->isInvalidDecl() && PrevDecl) { 8456 // Don't introduce NewFD into scope; there's already something 8457 // with the same name in the same scope. 8458 } else if (II) { 8459 PushOnScopeChains(NewFD, S); 8460 } else 8461 Record->addDecl(NewFD); 8462 8463 return NewFD; 8464} 8465 8466/// \brief Build a new FieldDecl and check its well-formedness. 8467/// 8468/// This routine builds a new FieldDecl given the fields name, type, 8469/// record, etc. \p PrevDecl should refer to any previous declaration 8470/// with the same name and in the same scope as the field to be 8471/// created. 8472/// 8473/// \returns a new FieldDecl. 8474/// 8475/// \todo The Declarator argument is a hack. It will be removed once 8476FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 8477 TypeSourceInfo *TInfo, 8478 RecordDecl *Record, SourceLocation Loc, 8479 bool Mutable, Expr *BitWidth, bool HasInit, 8480 SourceLocation TSSL, 8481 AccessSpecifier AS, NamedDecl *PrevDecl, 8482 Declarator *D) { 8483 IdentifierInfo *II = Name.getAsIdentifierInfo(); 8484 bool InvalidDecl = false; 8485 if (D) InvalidDecl = D->isInvalidType(); 8486 8487 // If we receive a broken type, recover by assuming 'int' and 8488 // marking this declaration as invalid. 8489 if (T.isNull()) { 8490 InvalidDecl = true; 8491 T = Context.IntTy; 8492 } 8493 8494 QualType EltTy = Context.getBaseElementType(T); 8495 if (!EltTy->isDependentType() && 8496 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 8497 // Fields of incomplete type force their record to be invalid. 8498 Record->setInvalidDecl(); 8499 InvalidDecl = true; 8500 } 8501 8502 // C99 6.7.2.1p8: A member of a structure or union may have any type other 8503 // than a variably modified type. 8504 if (!InvalidDecl && T->isVariablyModifiedType()) { 8505 bool SizeIsNegative; 8506 llvm::APSInt Oversized; 8507 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 8508 SizeIsNegative, 8509 Oversized); 8510 if (!FixedTy.isNull()) { 8511 Diag(Loc, diag::warn_illegal_constant_array_size); 8512 T = FixedTy; 8513 } else { 8514 if (SizeIsNegative) 8515 Diag(Loc, diag::err_typecheck_negative_array_size); 8516 else if (Oversized.getBoolValue()) 8517 Diag(Loc, diag::err_array_too_large) 8518 << Oversized.toString(10); 8519 else 8520 Diag(Loc, diag::err_typecheck_field_variable_size); 8521 InvalidDecl = true; 8522 } 8523 } 8524 8525 // Fields can not have abstract class types 8526 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 8527 diag::err_abstract_type_in_decl, 8528 AbstractFieldType)) 8529 InvalidDecl = true; 8530 8531 bool ZeroWidth = false; 8532 // If this is declared as a bit-field, check the bit-field. 8533 if (!InvalidDecl && BitWidth && 8534 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 8535 InvalidDecl = true; 8536 BitWidth = 0; 8537 ZeroWidth = false; 8538 } 8539 8540 // Check that 'mutable' is consistent with the type of the declaration. 8541 if (!InvalidDecl && Mutable) { 8542 unsigned DiagID = 0; 8543 if (T->isReferenceType()) 8544 DiagID = diag::err_mutable_reference; 8545 else if (T.isConstQualified()) 8546 DiagID = diag::err_mutable_const; 8547 8548 if (DiagID) { 8549 SourceLocation ErrLoc = Loc; 8550 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 8551 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 8552 Diag(ErrLoc, DiagID); 8553 Mutable = false; 8554 InvalidDecl = true; 8555 } 8556 } 8557 8558 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 8559 BitWidth, Mutable, HasInit); 8560 if (InvalidDecl) 8561 NewFD->setInvalidDecl(); 8562 8563 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 8564 Diag(Loc, diag::err_duplicate_member) << II; 8565 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8566 NewFD->setInvalidDecl(); 8567 } 8568 8569 if (!InvalidDecl && getLangOptions().CPlusPlus) { 8570 if (Record->isUnion()) { 8571 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 8572 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 8573 if (RDecl->getDefinition()) { 8574 // C++ [class.union]p1: An object of a class with a non-trivial 8575 // constructor, a non-trivial copy constructor, a non-trivial 8576 // destructor, or a non-trivial copy assignment operator 8577 // cannot be a member of a union, nor can an array of such 8578 // objects. 8579 if (CheckNontrivialField(NewFD)) 8580 NewFD->setInvalidDecl(); 8581 } 8582 } 8583 8584 // C++ [class.union]p1: If a union contains a member of reference type, 8585 // the program is ill-formed. 8586 if (EltTy->isReferenceType()) { 8587 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 8588 << NewFD->getDeclName() << EltTy; 8589 NewFD->setInvalidDecl(); 8590 } 8591 } 8592 } 8593 8594 // FIXME: We need to pass in the attributes given an AST 8595 // representation, not a parser representation. 8596 if (D) 8597 // FIXME: What to pass instead of TUScope? 8598 ProcessDeclAttributes(TUScope, NewFD, *D); 8599 8600 // In auto-retain/release, infer strong retension for fields of 8601 // retainable type. 8602 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 8603 NewFD->setInvalidDecl(); 8604 8605 if (T.isObjCGCWeak()) 8606 Diag(Loc, diag::warn_attribute_weak_on_field); 8607 8608 NewFD->setAccess(AS); 8609 return NewFD; 8610} 8611 8612bool Sema::CheckNontrivialField(FieldDecl *FD) { 8613 assert(FD); 8614 assert(getLangOptions().CPlusPlus && "valid check only for C++"); 8615 8616 if (FD->isInvalidDecl()) 8617 return true; 8618 8619 QualType EltTy = Context.getBaseElementType(FD->getType()); 8620 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 8621 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 8622 if (RDecl->getDefinition()) { 8623 // We check for copy constructors before constructors 8624 // because otherwise we'll never get complaints about 8625 // copy constructors. 8626 8627 CXXSpecialMember member = CXXInvalid; 8628 if (!RDecl->hasTrivialCopyConstructor()) 8629 member = CXXCopyConstructor; 8630 else if (!RDecl->hasTrivialDefaultConstructor()) 8631 member = CXXDefaultConstructor; 8632 else if (!RDecl->hasTrivialCopyAssignment()) 8633 member = CXXCopyAssignment; 8634 else if (!RDecl->hasTrivialDestructor()) 8635 member = CXXDestructor; 8636 8637 if (member != CXXInvalid) { 8638 if (!getLangOptions().CPlusPlus0x && 8639 getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) { 8640 // Objective-C++ ARC: it is an error to have a non-trivial field of 8641 // a union. However, system headers in Objective-C programs 8642 // occasionally have Objective-C lifetime objects within unions, 8643 // and rather than cause the program to fail, we make those 8644 // members unavailable. 8645 SourceLocation Loc = FD->getLocation(); 8646 if (getSourceManager().isInSystemHeader(Loc)) { 8647 if (!FD->hasAttr<UnavailableAttr>()) 8648 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 8649 "this system field has retaining ownership")); 8650 return false; 8651 } 8652 } 8653 8654 Diag(FD->getLocation(), getLangOptions().CPlusPlus0x ? 8655 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 8656 diag::err_illegal_union_or_anon_struct_member) 8657 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 8658 DiagnoseNontrivial(RT, member); 8659 return !getLangOptions().CPlusPlus0x; 8660 } 8661 } 8662 } 8663 8664 return false; 8665} 8666 8667/// DiagnoseNontrivial - Given that a class has a non-trivial 8668/// special member, figure out why. 8669void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 8670 QualType QT(T, 0U); 8671 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 8672 8673 // Check whether the member was user-declared. 8674 switch (member) { 8675 case CXXInvalid: 8676 break; 8677 8678 case CXXDefaultConstructor: 8679 if (RD->hasUserDeclaredConstructor()) { 8680 typedef CXXRecordDecl::ctor_iterator ctor_iter; 8681 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 8682 const FunctionDecl *body = 0; 8683 ci->hasBody(body); 8684 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) { 8685 SourceLocation CtorLoc = ci->getLocation(); 8686 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8687 return; 8688 } 8689 } 8690 8691 llvm_unreachable("found no user-declared constructors"); 8692 } 8693 break; 8694 8695 case CXXCopyConstructor: 8696 if (RD->hasUserDeclaredCopyConstructor()) { 8697 SourceLocation CtorLoc = 8698 RD->getCopyConstructor(0)->getLocation(); 8699 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8700 return; 8701 } 8702 break; 8703 8704 case CXXMoveConstructor: 8705 if (RD->hasUserDeclaredMoveConstructor()) { 8706 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation(); 8707 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8708 return; 8709 } 8710 break; 8711 8712 case CXXCopyAssignment: 8713 if (RD->hasUserDeclaredCopyAssignment()) { 8714 // FIXME: this should use the location of the copy 8715 // assignment, not the type. 8716 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 8717 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 8718 return; 8719 } 8720 break; 8721 8722 case CXXMoveAssignment: 8723 if (RD->hasUserDeclaredMoveAssignment()) { 8724 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation(); 8725 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 8726 return; 8727 } 8728 break; 8729 8730 case CXXDestructor: 8731 if (RD->hasUserDeclaredDestructor()) { 8732 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 8733 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8734 return; 8735 } 8736 break; 8737 } 8738 8739 typedef CXXRecordDecl::base_class_iterator base_iter; 8740 8741 // Virtual bases and members inhibit trivial copying/construction, 8742 // but not trivial destruction. 8743 if (member != CXXDestructor) { 8744 // Check for virtual bases. vbases includes indirect virtual bases, 8745 // so we just iterate through the direct bases. 8746 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 8747 if (bi->isVirtual()) { 8748 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8749 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 8750 return; 8751 } 8752 8753 // Check for virtual methods. 8754 typedef CXXRecordDecl::method_iterator meth_iter; 8755 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 8756 ++mi) { 8757 if (mi->isVirtual()) { 8758 SourceLocation MLoc = mi->getSourceRange().getBegin(); 8759 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 8760 return; 8761 } 8762 } 8763 } 8764 8765 bool (CXXRecordDecl::*hasTrivial)() const; 8766 switch (member) { 8767 case CXXDefaultConstructor: 8768 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break; 8769 case CXXCopyConstructor: 8770 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 8771 case CXXCopyAssignment: 8772 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 8773 case CXXDestructor: 8774 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 8775 default: 8776 llvm_unreachable("unexpected special member"); 8777 } 8778 8779 // Check for nontrivial bases (and recurse). 8780 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 8781 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 8782 assert(BaseRT && "Don't know how to handle dependent bases"); 8783 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 8784 if (!(BaseRecTy->*hasTrivial)()) { 8785 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8786 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 8787 DiagnoseNontrivial(BaseRT, member); 8788 return; 8789 } 8790 } 8791 8792 // Check for nontrivial members (and recurse). 8793 typedef RecordDecl::field_iterator field_iter; 8794 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 8795 ++fi) { 8796 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 8797 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 8798 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 8799 8800 if (!(EltRD->*hasTrivial)()) { 8801 SourceLocation FLoc = (*fi)->getLocation(); 8802 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 8803 DiagnoseNontrivial(EltRT, member); 8804 return; 8805 } 8806 } 8807 8808 if (EltTy->isObjCLifetimeType()) { 8809 switch (EltTy.getObjCLifetime()) { 8810 case Qualifiers::OCL_None: 8811 case Qualifiers::OCL_ExplicitNone: 8812 break; 8813 8814 case Qualifiers::OCL_Autoreleasing: 8815 case Qualifiers::OCL_Weak: 8816 case Qualifiers::OCL_Strong: 8817 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership) 8818 << QT << EltTy.getObjCLifetime(); 8819 return; 8820 } 8821 } 8822 } 8823 8824 llvm_unreachable("found no explanation for non-trivial member"); 8825} 8826 8827/// TranslateIvarVisibility - Translate visibility from a token ID to an 8828/// AST enum value. 8829static ObjCIvarDecl::AccessControl 8830TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 8831 switch (ivarVisibility) { 8832 default: llvm_unreachable("Unknown visitibility kind"); 8833 case tok::objc_private: return ObjCIvarDecl::Private; 8834 case tok::objc_public: return ObjCIvarDecl::Public; 8835 case tok::objc_protected: return ObjCIvarDecl::Protected; 8836 case tok::objc_package: return ObjCIvarDecl::Package; 8837 } 8838} 8839 8840/// ActOnIvar - Each ivar field of an objective-c class is passed into this 8841/// in order to create an IvarDecl object for it. 8842Decl *Sema::ActOnIvar(Scope *S, 8843 SourceLocation DeclStart, 8844 Declarator &D, Expr *BitfieldWidth, 8845 tok::ObjCKeywordKind Visibility) { 8846 8847 IdentifierInfo *II = D.getIdentifier(); 8848 Expr *BitWidth = (Expr*)BitfieldWidth; 8849 SourceLocation Loc = DeclStart; 8850 if (II) Loc = D.getIdentifierLoc(); 8851 8852 // FIXME: Unnamed fields can be handled in various different ways, for 8853 // example, unnamed unions inject all members into the struct namespace! 8854 8855 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8856 QualType T = TInfo->getType(); 8857 8858 if (BitWidth) { 8859 // 6.7.2.1p3, 6.7.2.1p4 8860 if (VerifyBitField(Loc, II, T, BitWidth)) { 8861 D.setInvalidType(); 8862 BitWidth = 0; 8863 } 8864 } else { 8865 // Not a bitfield. 8866 8867 // validate II. 8868 8869 } 8870 if (T->isReferenceType()) { 8871 Diag(Loc, diag::err_ivar_reference_type); 8872 D.setInvalidType(); 8873 } 8874 // C99 6.7.2.1p8: A member of a structure or union may have any type other 8875 // than a variably modified type. 8876 else if (T->isVariablyModifiedType()) { 8877 Diag(Loc, diag::err_typecheck_ivar_variable_size); 8878 D.setInvalidType(); 8879 } 8880 8881 // Get the visibility (access control) for this ivar. 8882 ObjCIvarDecl::AccessControl ac = 8883 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 8884 : ObjCIvarDecl::None; 8885 // Must set ivar's DeclContext to its enclosing interface. 8886 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 8887 ObjCContainerDecl *EnclosingContext; 8888 if (ObjCImplementationDecl *IMPDecl = 8889 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 8890 if (!LangOpts.ObjCNonFragileABI2) { 8891 // Case of ivar declared in an implementation. Context is that of its class. 8892 EnclosingContext = IMPDecl->getClassInterface(); 8893 assert(EnclosingContext && "Implementation has no class interface!"); 8894 } 8895 else 8896 EnclosingContext = EnclosingDecl; 8897 } else { 8898 if (ObjCCategoryDecl *CDecl = 8899 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8900 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 8901 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 8902 return 0; 8903 } 8904 } 8905 EnclosingContext = EnclosingDecl; 8906 } 8907 8908 // Construct the decl. 8909 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 8910 DeclStart, Loc, II, T, 8911 TInfo, ac, (Expr *)BitfieldWidth); 8912 8913 if (II) { 8914 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 8915 ForRedeclaration); 8916 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 8917 && !isa<TagDecl>(PrevDecl)) { 8918 Diag(Loc, diag::err_duplicate_member) << II; 8919 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8920 NewID->setInvalidDecl(); 8921 } 8922 } 8923 8924 // Process attributes attached to the ivar. 8925 ProcessDeclAttributes(S, NewID, D); 8926 8927 if (D.isInvalidType()) 8928 NewID->setInvalidDecl(); 8929 8930 // In ARC, infer 'retaining' for ivars of retainable type. 8931 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 8932 NewID->setInvalidDecl(); 8933 8934 if (D.getDeclSpec().isModulePrivateSpecified()) 8935 NewID->setModulePrivate(); 8936 8937 if (II) { 8938 // FIXME: When interfaces are DeclContexts, we'll need to add 8939 // these to the interface. 8940 S->AddDecl(NewID); 8941 IdResolver.AddDecl(NewID); 8942 } 8943 8944 return NewID; 8945} 8946 8947/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 8948/// class and class extensions. For every class @interface and class 8949/// extension @interface, if the last ivar is a bitfield of any type, 8950/// then add an implicit `char :0` ivar to the end of that interface. 8951void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 8952 SmallVectorImpl<Decl *> &AllIvarDecls) { 8953 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty()) 8954 return; 8955 8956 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 8957 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 8958 8959 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 8960 return; 8961 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 8962 if (!ID) { 8963 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 8964 if (!CD->IsClassExtension()) 8965 return; 8966 } 8967 // No need to add this to end of @implementation. 8968 else 8969 return; 8970 } 8971 // All conditions are met. Add a new bitfield to the tail end of ivars. 8972 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 8973 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 8974 8975 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 8976 DeclLoc, DeclLoc, 0, 8977 Context.CharTy, 8978 Context.getTrivialTypeSourceInfo(Context.CharTy, 8979 DeclLoc), 8980 ObjCIvarDecl::Private, BW, 8981 true); 8982 AllIvarDecls.push_back(Ivar); 8983} 8984 8985void Sema::ActOnFields(Scope* S, 8986 SourceLocation RecLoc, Decl *EnclosingDecl, 8987 llvm::ArrayRef<Decl *> Fields, 8988 SourceLocation LBrac, SourceLocation RBrac, 8989 AttributeList *Attr) { 8990 assert(EnclosingDecl && "missing record or interface decl"); 8991 8992 // If the decl this is being inserted into is invalid, then it may be a 8993 // redeclaration or some other bogus case. Don't try to add fields to it. 8994 if (EnclosingDecl->isInvalidDecl()) 8995 return; 8996 8997 // Verify that all the fields are okay. 8998 unsigned NumNamedMembers = 0; 8999 SmallVector<FieldDecl*, 32> RecFields; 9000 9001 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 9002 bool ARCErrReported = false; 9003 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 9004 i != end; ++i) { 9005 FieldDecl *FD = cast<FieldDecl>(*i); 9006 9007 // Get the type for the field. 9008 const Type *FDTy = FD->getType().getTypePtr(); 9009 9010 if (!FD->isAnonymousStructOrUnion()) { 9011 // Remember all fields written by the user. 9012 RecFields.push_back(FD); 9013 } 9014 9015 // If the field is already invalid for some reason, don't emit more 9016 // diagnostics about it. 9017 if (FD->isInvalidDecl()) { 9018 EnclosingDecl->setInvalidDecl(); 9019 continue; 9020 } 9021 9022 // C99 6.7.2.1p2: 9023 // A structure or union shall not contain a member with 9024 // incomplete or function type (hence, a structure shall not 9025 // contain an instance of itself, but may contain a pointer to 9026 // an instance of itself), except that the last member of a 9027 // structure with more than one named member may have incomplete 9028 // array type; such a structure (and any union containing, 9029 // possibly recursively, a member that is such a structure) 9030 // shall not be a member of a structure or an element of an 9031 // array. 9032 if (FDTy->isFunctionType()) { 9033 // Field declared as a function. 9034 Diag(FD->getLocation(), diag::err_field_declared_as_function) 9035 << FD->getDeclName(); 9036 FD->setInvalidDecl(); 9037 EnclosingDecl->setInvalidDecl(); 9038 continue; 9039 } else if (FDTy->isIncompleteArrayType() && Record && 9040 ((i + 1 == Fields.end() && !Record->isUnion()) || 9041 ((getLangOptions().MicrosoftExt || 9042 getLangOptions().CPlusPlus) && 9043 (i + 1 == Fields.end() || Record->isUnion())))) { 9044 // Flexible array member. 9045 // Microsoft and g++ is more permissive regarding flexible array. 9046 // It will accept flexible array in union and also 9047 // as the sole element of a struct/class. 9048 if (getLangOptions().MicrosoftExt) { 9049 if (Record->isUnion()) 9050 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 9051 << FD->getDeclName(); 9052 else if (Fields.size() == 1) 9053 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 9054 << FD->getDeclName() << Record->getTagKind(); 9055 } else if (getLangOptions().CPlusPlus) { 9056 if (Record->isUnion()) 9057 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 9058 << FD->getDeclName(); 9059 else if (Fields.size() == 1) 9060 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 9061 << FD->getDeclName() << Record->getTagKind(); 9062 } else if (NumNamedMembers < 1) { 9063 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 9064 << FD->getDeclName(); 9065 FD->setInvalidDecl(); 9066 EnclosingDecl->setInvalidDecl(); 9067 continue; 9068 } 9069 if (!FD->getType()->isDependentType() && 9070 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 9071 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 9072 << FD->getDeclName() << FD->getType(); 9073 FD->setInvalidDecl(); 9074 EnclosingDecl->setInvalidDecl(); 9075 continue; 9076 } 9077 // Okay, we have a legal flexible array member at the end of the struct. 9078 if (Record) 9079 Record->setHasFlexibleArrayMember(true); 9080 } else if (!FDTy->isDependentType() && 9081 RequireCompleteType(FD->getLocation(), FD->getType(), 9082 diag::err_field_incomplete)) { 9083 // Incomplete type 9084 FD->setInvalidDecl(); 9085 EnclosingDecl->setInvalidDecl(); 9086 continue; 9087 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 9088 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 9089 // If this is a member of a union, then entire union becomes "flexible". 9090 if (Record && Record->isUnion()) { 9091 Record->setHasFlexibleArrayMember(true); 9092 } else { 9093 // If this is a struct/class and this is not the last element, reject 9094 // it. Note that GCC supports variable sized arrays in the middle of 9095 // structures. 9096 if (i + 1 != Fields.end()) 9097 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 9098 << FD->getDeclName() << FD->getType(); 9099 else { 9100 // We support flexible arrays at the end of structs in 9101 // other structs as an extension. 9102 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 9103 << FD->getDeclName(); 9104 if (Record) 9105 Record->setHasFlexibleArrayMember(true); 9106 } 9107 } 9108 } 9109 if (Record && FDTTy->getDecl()->hasObjectMember()) 9110 Record->setHasObjectMember(true); 9111 } else if (FDTy->isObjCObjectType()) { 9112 /// A field cannot be an Objective-c object 9113 Diag(FD->getLocation(), diag::err_statically_allocated_object) 9114 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 9115 QualType T = Context.getObjCObjectPointerType(FD->getType()); 9116 FD->setType(T); 9117 } 9118 else if (!getLangOptions().CPlusPlus) { 9119 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) { 9120 // It's an error in ARC if a field has lifetime. 9121 // We don't want to report this in a system header, though, 9122 // so we just make the field unavailable. 9123 // FIXME: that's really not sufficient; we need to make the type 9124 // itself invalid to, say, initialize or copy. 9125 QualType T = FD->getType(); 9126 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 9127 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 9128 SourceLocation loc = FD->getLocation(); 9129 if (getSourceManager().isInSystemHeader(loc)) { 9130 if (!FD->hasAttr<UnavailableAttr>()) { 9131 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 9132 "this system field has retaining ownership")); 9133 } 9134 } else { 9135 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct); 9136 } 9137 ARCErrReported = true; 9138 } 9139 } 9140 else if (getLangOptions().ObjC1 && 9141 getLangOptions().getGC() != LangOptions::NonGC && 9142 Record && !Record->hasObjectMember()) { 9143 if (FD->getType()->isObjCObjectPointerType() || 9144 FD->getType().isObjCGCStrong()) 9145 Record->setHasObjectMember(true); 9146 else if (Context.getAsArrayType(FD->getType())) { 9147 QualType BaseType = Context.getBaseElementType(FD->getType()); 9148 if (BaseType->isRecordType() && 9149 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 9150 Record->setHasObjectMember(true); 9151 else if (BaseType->isObjCObjectPointerType() || 9152 BaseType.isObjCGCStrong()) 9153 Record->setHasObjectMember(true); 9154 } 9155 } 9156 } 9157 // Keep track of the number of named members. 9158 if (FD->getIdentifier()) 9159 ++NumNamedMembers; 9160 } 9161 9162 // Okay, we successfully defined 'Record'. 9163 if (Record) { 9164 bool Completed = false; 9165 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 9166 if (!CXXRecord->isInvalidDecl()) { 9167 // Set access bits correctly on the directly-declared conversions. 9168 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions(); 9169 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 9170 I != E; ++I) 9171 Convs->setAccess(I, (*I)->getAccess()); 9172 9173 if (!CXXRecord->isDependentType()) { 9174 // Objective-C Automatic Reference Counting: 9175 // If a class has a non-static data member of Objective-C pointer 9176 // type (or array thereof), it is a non-POD type and its 9177 // default constructor (if any), copy constructor, copy assignment 9178 // operator, and destructor are non-trivial. 9179 // 9180 // This rule is also handled by CXXRecordDecl::completeDefinition(). 9181 // However, here we check whether this particular class is only 9182 // non-POD because of the presence of an Objective-C pointer member. 9183 // If so, objects of this type cannot be shared between code compiled 9184 // with instant objects and code compiled with manual retain/release. 9185 if (getLangOptions().ObjCAutoRefCount && 9186 CXXRecord->hasObjectMember() && 9187 CXXRecord->getLinkage() == ExternalLinkage) { 9188 if (CXXRecord->isPOD()) { 9189 Diag(CXXRecord->getLocation(), 9190 diag::warn_arc_non_pod_class_with_object_member) 9191 << CXXRecord; 9192 } else { 9193 // FIXME: Fix-Its would be nice here, but finding a good location 9194 // for them is going to be tricky. 9195 if (CXXRecord->hasTrivialCopyConstructor()) 9196 Diag(CXXRecord->getLocation(), 9197 diag::warn_arc_trivial_member_function_with_object_member) 9198 << CXXRecord << 0; 9199 if (CXXRecord->hasTrivialCopyAssignment()) 9200 Diag(CXXRecord->getLocation(), 9201 diag::warn_arc_trivial_member_function_with_object_member) 9202 << CXXRecord << 1; 9203 if (CXXRecord->hasTrivialDestructor()) 9204 Diag(CXXRecord->getLocation(), 9205 diag::warn_arc_trivial_member_function_with_object_member) 9206 << CXXRecord << 2; 9207 } 9208 } 9209 9210 // Adjust user-defined destructor exception spec. 9211 if (getLangOptions().CPlusPlus0x && 9212 CXXRecord->hasUserDeclaredDestructor()) 9213 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 9214 9215 // Add any implicitly-declared members to this class. 9216 AddImplicitlyDeclaredMembersToClass(CXXRecord); 9217 9218 // If we have virtual base classes, we may end up finding multiple 9219 // final overriders for a given virtual function. Check for this 9220 // problem now. 9221 if (CXXRecord->getNumVBases()) { 9222 CXXFinalOverriderMap FinalOverriders; 9223 CXXRecord->getFinalOverriders(FinalOverriders); 9224 9225 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 9226 MEnd = FinalOverriders.end(); 9227 M != MEnd; ++M) { 9228 for (OverridingMethods::iterator SO = M->second.begin(), 9229 SOEnd = M->second.end(); 9230 SO != SOEnd; ++SO) { 9231 assert(SO->second.size() > 0 && 9232 "Virtual function without overridding functions?"); 9233 if (SO->second.size() == 1) 9234 continue; 9235 9236 // C++ [class.virtual]p2: 9237 // In a derived class, if a virtual member function of a base 9238 // class subobject has more than one final overrider the 9239 // program is ill-formed. 9240 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 9241 << (NamedDecl *)M->first << Record; 9242 Diag(M->first->getLocation(), 9243 diag::note_overridden_virtual_function); 9244 for (OverridingMethods::overriding_iterator 9245 OM = SO->second.begin(), 9246 OMEnd = SO->second.end(); 9247 OM != OMEnd; ++OM) 9248 Diag(OM->Method->getLocation(), diag::note_final_overrider) 9249 << (NamedDecl *)M->first << OM->Method->getParent(); 9250 9251 Record->setInvalidDecl(); 9252 } 9253 } 9254 CXXRecord->completeDefinition(&FinalOverriders); 9255 Completed = true; 9256 } 9257 } 9258 } 9259 } 9260 9261 if (!Completed) 9262 Record->completeDefinition(); 9263 9264 // Now that the record is complete, do any delayed exception spec checks 9265 // we were missing. 9266 while (!DelayedDestructorExceptionSpecChecks.empty()) { 9267 const CXXDestructorDecl *Dtor = 9268 DelayedDestructorExceptionSpecChecks.back().first; 9269 if (Dtor->getParent() != Record) 9270 break; 9271 9272 assert(!Dtor->getParent()->isDependentType() && 9273 "Should not ever add destructors of templates into the list."); 9274 CheckOverridingFunctionExceptionSpec(Dtor, 9275 DelayedDestructorExceptionSpecChecks.back().second); 9276 DelayedDestructorExceptionSpecChecks.pop_back(); 9277 } 9278 9279 } else { 9280 ObjCIvarDecl **ClsFields = 9281 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 9282 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 9283 ID->setLocEnd(RBrac); 9284 // Add ivar's to class's DeclContext. 9285 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 9286 ClsFields[i]->setLexicalDeclContext(ID); 9287 ID->addDecl(ClsFields[i]); 9288 } 9289 // Must enforce the rule that ivars in the base classes may not be 9290 // duplicates. 9291 if (ID->getSuperClass()) 9292 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 9293 } else if (ObjCImplementationDecl *IMPDecl = 9294 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 9295 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 9296 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 9297 // Ivar declared in @implementation never belongs to the implementation. 9298 // Only it is in implementation's lexical context. 9299 ClsFields[I]->setLexicalDeclContext(IMPDecl); 9300 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 9301 } else if (ObjCCategoryDecl *CDecl = 9302 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 9303 // case of ivars in class extension; all other cases have been 9304 // reported as errors elsewhere. 9305 // FIXME. Class extension does not have a LocEnd field. 9306 // CDecl->setLocEnd(RBrac); 9307 // Add ivar's to class extension's DeclContext. 9308 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 9309 ClsFields[i]->setLexicalDeclContext(CDecl); 9310 CDecl->addDecl(ClsFields[i]); 9311 } 9312 } 9313 } 9314 9315 if (Attr) 9316 ProcessDeclAttributeList(S, Record, Attr); 9317 9318 // If there's a #pragma GCC visibility in scope, and this isn't a subclass, 9319 // set the visibility of this record. 9320 if (Record && !Record->getDeclContext()->isRecord()) 9321 AddPushedVisibilityAttribute(Record); 9322} 9323 9324/// \brief Determine whether the given integral value is representable within 9325/// the given type T. 9326static bool isRepresentableIntegerValue(ASTContext &Context, 9327 llvm::APSInt &Value, 9328 QualType T) { 9329 assert(T->isIntegralType(Context) && "Integral type required!"); 9330 unsigned BitWidth = Context.getIntWidth(T); 9331 9332 if (Value.isUnsigned() || Value.isNonNegative()) { 9333 if (T->isSignedIntegerOrEnumerationType()) 9334 --BitWidth; 9335 return Value.getActiveBits() <= BitWidth; 9336 } 9337 return Value.getMinSignedBits() <= BitWidth; 9338} 9339 9340// \brief Given an integral type, return the next larger integral type 9341// (or a NULL type of no such type exists). 9342static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 9343 // FIXME: Int128/UInt128 support, which also needs to be introduced into 9344 // enum checking below. 9345 assert(T->isIntegralType(Context) && "Integral type required!"); 9346 const unsigned NumTypes = 4; 9347 QualType SignedIntegralTypes[NumTypes] = { 9348 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 9349 }; 9350 QualType UnsignedIntegralTypes[NumTypes] = { 9351 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 9352 Context.UnsignedLongLongTy 9353 }; 9354 9355 unsigned BitWidth = Context.getTypeSize(T); 9356 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 9357 : UnsignedIntegralTypes; 9358 for (unsigned I = 0; I != NumTypes; ++I) 9359 if (Context.getTypeSize(Types[I]) > BitWidth) 9360 return Types[I]; 9361 9362 return QualType(); 9363} 9364 9365EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 9366 EnumConstantDecl *LastEnumConst, 9367 SourceLocation IdLoc, 9368 IdentifierInfo *Id, 9369 Expr *Val) { 9370 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 9371 llvm::APSInt EnumVal(IntWidth); 9372 QualType EltTy; 9373 9374 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 9375 Val = 0; 9376 9377 if (Val) { 9378 if (Enum->isDependentType() || Val->isTypeDependent()) 9379 EltTy = Context.DependentTy; 9380 else { 9381 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 9382 SourceLocation ExpLoc; 9383 if (!Val->isValueDependent() && 9384 VerifyIntegerConstantExpression(Val, &EnumVal)) { 9385 Val = 0; 9386 } else { 9387 if (!getLangOptions().CPlusPlus) { 9388 // C99 6.7.2.2p2: 9389 // The expression that defines the value of an enumeration constant 9390 // shall be an integer constant expression that has a value 9391 // representable as an int. 9392 9393 // Complain if the value is not representable in an int. 9394 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 9395 Diag(IdLoc, diag::ext_enum_value_not_int) 9396 << EnumVal.toString(10) << Val->getSourceRange() 9397 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 9398 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 9399 // Force the type of the expression to 'int'. 9400 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 9401 } 9402 } 9403 9404 if (Enum->isFixed()) { 9405 EltTy = Enum->getIntegerType(); 9406 9407 // C++0x [dcl.enum]p5: 9408 // ... if the initializing value of an enumerator cannot be 9409 // represented by the underlying type, the program is ill-formed. 9410 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 9411 if (getLangOptions().MicrosoftExt) { 9412 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 9413 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 9414 } else 9415 Diag(IdLoc, diag::err_enumerator_too_large) 9416 << EltTy; 9417 } else 9418 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 9419 } 9420 else { 9421 // C++0x [dcl.enum]p5: 9422 // If the underlying type is not fixed, the type of each enumerator 9423 // is the type of its initializing value: 9424 // - If an initializer is specified for an enumerator, the 9425 // initializing value has the same type as the expression. 9426 EltTy = Val->getType(); 9427 } 9428 } 9429 } 9430 } 9431 9432 if (!Val) { 9433 if (Enum->isDependentType()) 9434 EltTy = Context.DependentTy; 9435 else if (!LastEnumConst) { 9436 // C++0x [dcl.enum]p5: 9437 // If the underlying type is not fixed, the type of each enumerator 9438 // is the type of its initializing value: 9439 // - If no initializer is specified for the first enumerator, the 9440 // initializing value has an unspecified integral type. 9441 // 9442 // GCC uses 'int' for its unspecified integral type, as does 9443 // C99 6.7.2.2p3. 9444 if (Enum->isFixed()) { 9445 EltTy = Enum->getIntegerType(); 9446 } 9447 else { 9448 EltTy = Context.IntTy; 9449 } 9450 } else { 9451 // Assign the last value + 1. 9452 EnumVal = LastEnumConst->getInitVal(); 9453 ++EnumVal; 9454 EltTy = LastEnumConst->getType(); 9455 9456 // Check for overflow on increment. 9457 if (EnumVal < LastEnumConst->getInitVal()) { 9458 // C++0x [dcl.enum]p5: 9459 // If the underlying type is not fixed, the type of each enumerator 9460 // is the type of its initializing value: 9461 // 9462 // - Otherwise the type of the initializing value is the same as 9463 // the type of the initializing value of the preceding enumerator 9464 // unless the incremented value is not representable in that type, 9465 // in which case the type is an unspecified integral type 9466 // sufficient to contain the incremented value. If no such type 9467 // exists, the program is ill-formed. 9468 QualType T = getNextLargerIntegralType(Context, EltTy); 9469 if (T.isNull() || Enum->isFixed()) { 9470 // There is no integral type larger enough to represent this 9471 // value. Complain, then allow the value to wrap around. 9472 EnumVal = LastEnumConst->getInitVal(); 9473 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 9474 ++EnumVal; 9475 if (Enum->isFixed()) 9476 // When the underlying type is fixed, this is ill-formed. 9477 Diag(IdLoc, diag::err_enumerator_wrapped) 9478 << EnumVal.toString(10) 9479 << EltTy; 9480 else 9481 Diag(IdLoc, diag::warn_enumerator_too_large) 9482 << EnumVal.toString(10); 9483 } else { 9484 EltTy = T; 9485 } 9486 9487 // Retrieve the last enumerator's value, extent that type to the 9488 // type that is supposed to be large enough to represent the incremented 9489 // value, then increment. 9490 EnumVal = LastEnumConst->getInitVal(); 9491 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 9492 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 9493 ++EnumVal; 9494 9495 // If we're not in C++, diagnose the overflow of enumerator values, 9496 // which in C99 means that the enumerator value is not representable in 9497 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 9498 // permits enumerator values that are representable in some larger 9499 // integral type. 9500 if (!getLangOptions().CPlusPlus && !T.isNull()) 9501 Diag(IdLoc, diag::warn_enum_value_overflow); 9502 } else if (!getLangOptions().CPlusPlus && 9503 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 9504 // Enforce C99 6.7.2.2p2 even when we compute the next value. 9505 Diag(IdLoc, diag::ext_enum_value_not_int) 9506 << EnumVal.toString(10) << 1; 9507 } 9508 } 9509 } 9510 9511 if (!EltTy->isDependentType()) { 9512 // Make the enumerator value match the signedness and size of the 9513 // enumerator's type. 9514 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 9515 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 9516 } 9517 9518 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 9519 Val, EnumVal); 9520} 9521 9522 9523Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 9524 SourceLocation IdLoc, IdentifierInfo *Id, 9525 AttributeList *Attr, 9526 SourceLocation EqualLoc, Expr *val) { 9527 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 9528 EnumConstantDecl *LastEnumConst = 9529 cast_or_null<EnumConstantDecl>(lastEnumConst); 9530 Expr *Val = static_cast<Expr*>(val); 9531 9532 // The scope passed in may not be a decl scope. Zip up the scope tree until 9533 // we find one that is. 9534 S = getNonFieldDeclScope(S); 9535 9536 // Verify that there isn't already something declared with this name in this 9537 // scope. 9538 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 9539 ForRedeclaration); 9540 if (PrevDecl && PrevDecl->isTemplateParameter()) { 9541 // Maybe we will complain about the shadowed template parameter. 9542 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 9543 // Just pretend that we didn't see the previous declaration. 9544 PrevDecl = 0; 9545 } 9546 9547 if (PrevDecl) { 9548 // When in C++, we may get a TagDecl with the same name; in this case the 9549 // enum constant will 'hide' the tag. 9550 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 9551 "Received TagDecl when not in C++!"); 9552 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 9553 if (isa<EnumConstantDecl>(PrevDecl)) 9554 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 9555 else 9556 Diag(IdLoc, diag::err_redefinition) << Id; 9557 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9558 return 0; 9559 } 9560 } 9561 9562 // C++ [class.mem]p13: 9563 // If T is the name of a class, then each of the following shall have a 9564 // name different from T: 9565 // - every enumerator of every member of class T that is an enumerated 9566 // type 9567 if (CXXRecordDecl *Record 9568 = dyn_cast<CXXRecordDecl>( 9569 TheEnumDecl->getDeclContext()->getRedeclContext())) 9570 if (Record->getIdentifier() && Record->getIdentifier() == Id) 9571 Diag(IdLoc, diag::err_member_name_of_class) << Id; 9572 9573 EnumConstantDecl *New = 9574 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 9575 9576 if (New) { 9577 // Process attributes. 9578 if (Attr) ProcessDeclAttributeList(S, New, Attr); 9579 9580 // Register this decl in the current scope stack. 9581 New->setAccess(TheEnumDecl->getAccess()); 9582 PushOnScopeChains(New, S); 9583 } 9584 9585 return New; 9586} 9587 9588void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 9589 SourceLocation RBraceLoc, Decl *EnumDeclX, 9590 Decl **Elements, unsigned NumElements, 9591 Scope *S, AttributeList *Attr) { 9592 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 9593 QualType EnumType = Context.getTypeDeclType(Enum); 9594 9595 if (Attr) 9596 ProcessDeclAttributeList(S, Enum, Attr); 9597 9598 if (Enum->isDependentType()) { 9599 for (unsigned i = 0; i != NumElements; ++i) { 9600 EnumConstantDecl *ECD = 9601 cast_or_null<EnumConstantDecl>(Elements[i]); 9602 if (!ECD) continue; 9603 9604 ECD->setType(EnumType); 9605 } 9606 9607 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 9608 return; 9609 } 9610 9611 // TODO: If the result value doesn't fit in an int, it must be a long or long 9612 // long value. ISO C does not support this, but GCC does as an extension, 9613 // emit a warning. 9614 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 9615 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 9616 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 9617 9618 // Verify that all the values are okay, compute the size of the values, and 9619 // reverse the list. 9620 unsigned NumNegativeBits = 0; 9621 unsigned NumPositiveBits = 0; 9622 9623 // Keep track of whether all elements have type int. 9624 bool AllElementsInt = true; 9625 9626 for (unsigned i = 0; i != NumElements; ++i) { 9627 EnumConstantDecl *ECD = 9628 cast_or_null<EnumConstantDecl>(Elements[i]); 9629 if (!ECD) continue; // Already issued a diagnostic. 9630 9631 const llvm::APSInt &InitVal = ECD->getInitVal(); 9632 9633 // Keep track of the size of positive and negative values. 9634 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 9635 NumPositiveBits = std::max(NumPositiveBits, 9636 (unsigned)InitVal.getActiveBits()); 9637 else 9638 NumNegativeBits = std::max(NumNegativeBits, 9639 (unsigned)InitVal.getMinSignedBits()); 9640 9641 // Keep track of whether every enum element has type int (very commmon). 9642 if (AllElementsInt) 9643 AllElementsInt = ECD->getType() == Context.IntTy; 9644 } 9645 9646 // Figure out the type that should be used for this enum. 9647 QualType BestType; 9648 unsigned BestWidth; 9649 9650 // C++0x N3000 [conv.prom]p3: 9651 // An rvalue of an unscoped enumeration type whose underlying 9652 // type is not fixed can be converted to an rvalue of the first 9653 // of the following types that can represent all the values of 9654 // the enumeration: int, unsigned int, long int, unsigned long 9655 // int, long long int, or unsigned long long int. 9656 // C99 6.4.4.3p2: 9657 // An identifier declared as an enumeration constant has type int. 9658 // The C99 rule is modified by a gcc extension 9659 QualType BestPromotionType; 9660 9661 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 9662 // -fshort-enums is the equivalent to specifying the packed attribute on all 9663 // enum definitions. 9664 if (LangOpts.ShortEnums) 9665 Packed = true; 9666 9667 if (Enum->isFixed()) { 9668 BestType = BestPromotionType = Enum->getIntegerType(); 9669 // We don't need to set BestWidth, because BestType is going to be the type 9670 // of the enumerators, but we do anyway because otherwise some compilers 9671 // warn that it might be used uninitialized. 9672 BestWidth = CharWidth; 9673 } 9674 else if (NumNegativeBits) { 9675 // If there is a negative value, figure out the smallest integer type (of 9676 // int/long/longlong) that fits. 9677 // If it's packed, check also if it fits a char or a short. 9678 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 9679 BestType = Context.SignedCharTy; 9680 BestWidth = CharWidth; 9681 } else if (Packed && NumNegativeBits <= ShortWidth && 9682 NumPositiveBits < ShortWidth) { 9683 BestType = Context.ShortTy; 9684 BestWidth = ShortWidth; 9685 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 9686 BestType = Context.IntTy; 9687 BestWidth = IntWidth; 9688 } else { 9689 BestWidth = Context.getTargetInfo().getLongWidth(); 9690 9691 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 9692 BestType = Context.LongTy; 9693 } else { 9694 BestWidth = Context.getTargetInfo().getLongLongWidth(); 9695 9696 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 9697 Diag(Enum->getLocation(), diag::warn_enum_too_large); 9698 BestType = Context.LongLongTy; 9699 } 9700 } 9701 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 9702 } else { 9703 // If there is no negative value, figure out the smallest type that fits 9704 // all of the enumerator values. 9705 // If it's packed, check also if it fits a char or a short. 9706 if (Packed && NumPositiveBits <= CharWidth) { 9707 BestType = Context.UnsignedCharTy; 9708 BestPromotionType = Context.IntTy; 9709 BestWidth = CharWidth; 9710 } else if (Packed && NumPositiveBits <= ShortWidth) { 9711 BestType = Context.UnsignedShortTy; 9712 BestPromotionType = Context.IntTy; 9713 BestWidth = ShortWidth; 9714 } else if (NumPositiveBits <= IntWidth) { 9715 BestType = Context.UnsignedIntTy; 9716 BestWidth = IntWidth; 9717 BestPromotionType 9718 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9719 ? Context.UnsignedIntTy : Context.IntTy; 9720 } else if (NumPositiveBits <= 9721 (BestWidth = Context.getTargetInfo().getLongWidth())) { 9722 BestType = Context.UnsignedLongTy; 9723 BestPromotionType 9724 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9725 ? Context.UnsignedLongTy : Context.LongTy; 9726 } else { 9727 BestWidth = Context.getTargetInfo().getLongLongWidth(); 9728 assert(NumPositiveBits <= BestWidth && 9729 "How could an initializer get larger than ULL?"); 9730 BestType = Context.UnsignedLongLongTy; 9731 BestPromotionType 9732 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9733 ? Context.UnsignedLongLongTy : Context.LongLongTy; 9734 } 9735 } 9736 9737 // Loop over all of the enumerator constants, changing their types to match 9738 // the type of the enum if needed. 9739 for (unsigned i = 0; i != NumElements; ++i) { 9740 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 9741 if (!ECD) continue; // Already issued a diagnostic. 9742 9743 // Standard C says the enumerators have int type, but we allow, as an 9744 // extension, the enumerators to be larger than int size. If each 9745 // enumerator value fits in an int, type it as an int, otherwise type it the 9746 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 9747 // that X has type 'int', not 'unsigned'. 9748 9749 // Determine whether the value fits into an int. 9750 llvm::APSInt InitVal = ECD->getInitVal(); 9751 9752 // If it fits into an integer type, force it. Otherwise force it to match 9753 // the enum decl type. 9754 QualType NewTy; 9755 unsigned NewWidth; 9756 bool NewSign; 9757 if (!getLangOptions().CPlusPlus && 9758 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 9759 NewTy = Context.IntTy; 9760 NewWidth = IntWidth; 9761 NewSign = true; 9762 } else if (ECD->getType() == BestType) { 9763 // Already the right type! 9764 if (getLangOptions().CPlusPlus) 9765 // C++ [dcl.enum]p4: Following the closing brace of an 9766 // enum-specifier, each enumerator has the type of its 9767 // enumeration. 9768 ECD->setType(EnumType); 9769 continue; 9770 } else { 9771 NewTy = BestType; 9772 NewWidth = BestWidth; 9773 NewSign = BestType->isSignedIntegerOrEnumerationType(); 9774 } 9775 9776 // Adjust the APSInt value. 9777 InitVal = InitVal.extOrTrunc(NewWidth); 9778 InitVal.setIsSigned(NewSign); 9779 ECD->setInitVal(InitVal); 9780 9781 // Adjust the Expr initializer and type. 9782 if (ECD->getInitExpr() && 9783 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 9784 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 9785 CK_IntegralCast, 9786 ECD->getInitExpr(), 9787 /*base paths*/ 0, 9788 VK_RValue)); 9789 if (getLangOptions().CPlusPlus) 9790 // C++ [dcl.enum]p4: Following the closing brace of an 9791 // enum-specifier, each enumerator has the type of its 9792 // enumeration. 9793 ECD->setType(EnumType); 9794 else 9795 ECD->setType(NewTy); 9796 } 9797 9798 Enum->completeDefinition(BestType, BestPromotionType, 9799 NumPositiveBits, NumNegativeBits); 9800} 9801 9802Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 9803 SourceLocation StartLoc, 9804 SourceLocation EndLoc) { 9805 StringLiteral *AsmString = cast<StringLiteral>(expr); 9806 9807 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 9808 AsmString, StartLoc, 9809 EndLoc); 9810 CurContext->addDecl(New); 9811 return New; 9812} 9813 9814DeclResult Sema::ActOnModuleImport(SourceLocation ImportLoc, 9815 IdentifierInfo &ModuleName, 9816 SourceLocation ModuleNameLoc) { 9817 ModuleKey Module = PP.getModuleLoader().loadModule(ImportLoc, 9818 ModuleName, ModuleNameLoc); 9819 if (!Module) 9820 return true; 9821 9822 // FIXME: Actually create a declaration to describe the module import. 9823 (void)Module; 9824 return DeclResult((Decl *)0); 9825} 9826 9827void 9828Sema::diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old, 9829 SourceLocation ModulePrivateKeyword) { 9830 assert(!Old->isModulePrivate() && "Old is module-private!"); 9831 9832 Diag(New->getLocation(), diag::err_module_private_follows_public) 9833 << New->getDeclName() << SourceRange(ModulePrivateKeyword); 9834 Diag(Old->getLocation(), diag::note_previous_declaration) 9835 << Old->getDeclName(); 9836 9837 // Drop the __module_private__ from the new declaration, since it's invalid. 9838 New->setModulePrivate(false); 9839} 9840 9841void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 9842 SourceLocation PragmaLoc, 9843 SourceLocation NameLoc) { 9844 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 9845 9846 if (PrevDecl) { 9847 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 9848 } else { 9849 (void)WeakUndeclaredIdentifiers.insert( 9850 std::pair<IdentifierInfo*,WeakInfo> 9851 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 9852 } 9853} 9854 9855void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 9856 IdentifierInfo* AliasName, 9857 SourceLocation PragmaLoc, 9858 SourceLocation NameLoc, 9859 SourceLocation AliasNameLoc) { 9860 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 9861 LookupOrdinaryName); 9862 WeakInfo W = WeakInfo(Name, NameLoc); 9863 9864 if (PrevDecl) { 9865 if (!PrevDecl->hasAttr<AliasAttr>()) 9866 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 9867 DeclApplyPragmaWeak(TUScope, ND, W); 9868 } else { 9869 (void)WeakUndeclaredIdentifiers.insert( 9870 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 9871 } 9872} 9873 9874Decl *Sema::getObjCDeclContext() const { 9875 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 9876} 9877 9878AvailabilityResult Sema::getCurContextAvailability() const { 9879 const Decl *D = cast<Decl>(getCurLexicalContext()); 9880 // A category implicitly has the availability of the interface. 9881 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 9882 D = CatD->getClassInterface(); 9883 9884 return D->getAvailability(); 9885} 9886