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