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