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