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 "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex 32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex 33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex 34 #include "clang/Parse/ParseDiagnostic.h" 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/Template.h" 44 #include "llvm/ADT/SmallString.h" 45 #include "llvm/ADT/Triple.h" 46 #include <algorithm> 47 #include <cstring> 48 #include <functional> 49 using namespace clang; 50 using namespace sema; 51 52 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 53 if (OwnedType) { 54 Decl *Group[2] = { OwnedType, Ptr }; 55 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 56 } 57 58 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 59 } 60 61 namespace { 62 63 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 64 public: 65 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false) 66 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) { 67 WantExpressionKeywords = false; 68 WantCXXNamedCasts = false; 69 WantRemainingKeywords = false; 70 } 71 72 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 73 if (NamedDecl *ND = candidate.getCorrectionDecl()) 74 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 75 (AllowInvalidDecl || !ND->isInvalidDecl()); 76 else 77 return !WantClassName && candidate.isKeyword(); 78 } 79 80 private: 81 bool AllowInvalidDecl; 82 bool WantClassName; 83 }; 84 85 } 86 87 /// \brief Determine whether the token kind starts a simple-type-specifier. 88 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 89 switch (Kind) { 90 // FIXME: Take into account the current language when deciding whether a 91 // token kind is a valid type specifier 92 case tok::kw_short: 93 case tok::kw_long: 94 case tok::kw___int64: 95 case tok::kw___int128: 96 case tok::kw_signed: 97 case tok::kw_unsigned: 98 case tok::kw_void: 99 case tok::kw_char: 100 case tok::kw_int: 101 case tok::kw_half: 102 case tok::kw_float: 103 case tok::kw_double: 104 case tok::kw_wchar_t: 105 case tok::kw_bool: 106 case tok::kw___underlying_type: 107 return true; 108 109 case tok::annot_typename: 110 case tok::kw_char16_t: 111 case tok::kw_char32_t: 112 case tok::kw_typeof: 113 case tok::annot_decltype: 114 case tok::kw_decltype: 115 return getLangOpts().CPlusPlus; 116 117 default: 118 break; 119 } 120 121 return false; 122 } 123 124 /// \brief If the identifier refers to a type name within this scope, 125 /// return the declaration of that type. 126 /// 127 /// This routine performs ordinary name lookup of the identifier II 128 /// within the given scope, with optional C++ scope specifier SS, to 129 /// determine whether the name refers to a type. If so, returns an 130 /// opaque pointer (actually a QualType) corresponding to that 131 /// type. Otherwise, returns NULL. 132 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 133 Scope *S, CXXScopeSpec *SS, 134 bool isClassName, bool HasTrailingDot, 135 ParsedType ObjectTypePtr, 136 bool IsCtorOrDtorName, 137 bool WantNontrivialTypeSourceInfo, 138 IdentifierInfo **CorrectedII) { 139 // Determine where we will perform name lookup. 140 DeclContext *LookupCtx = 0; 141 if (ObjectTypePtr) { 142 QualType ObjectType = ObjectTypePtr.get(); 143 if (ObjectType->isRecordType()) 144 LookupCtx = computeDeclContext(ObjectType); 145 } else if (SS && SS->isNotEmpty()) { 146 LookupCtx = computeDeclContext(*SS, false); 147 148 if (!LookupCtx) { 149 if (isDependentScopeSpecifier(*SS)) { 150 // C++ [temp.res]p3: 151 // A qualified-id that refers to a type and in which the 152 // nested-name-specifier depends on a template-parameter (14.6.2) 153 // shall be prefixed by the keyword typename to indicate that the 154 // qualified-id denotes a type, forming an 155 // elaborated-type-specifier (7.1.5.3). 156 // 157 // We therefore do not perform any name lookup if the result would 158 // refer to a member of an unknown specialization. 159 if (!isClassName && !IsCtorOrDtorName) 160 return ParsedType(); 161 162 // We know from the grammar that this name refers to a type, 163 // so build a dependent node to describe the type. 164 if (WantNontrivialTypeSourceInfo) 165 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 166 167 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 168 QualType T = 169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 170 II, NameLoc); 171 172 return ParsedType::make(T); 173 } 174 175 return ParsedType(); 176 } 177 178 if (!LookupCtx->isDependentContext() && 179 RequireCompleteDeclContext(*SS, LookupCtx)) 180 return ParsedType(); 181 } 182 183 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 184 // lookup for class-names. 185 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 186 LookupOrdinaryName; 187 LookupResult Result(*this, &II, NameLoc, Kind); 188 if (LookupCtx) { 189 // Perform "qualified" name lookup into the declaration context we 190 // computed, which is either the type of the base of a member access 191 // expression or the declaration context associated with a prior 192 // nested-name-specifier. 193 LookupQualifiedName(Result, LookupCtx); 194 195 if (ObjectTypePtr && Result.empty()) { 196 // C++ [basic.lookup.classref]p3: 197 // If the unqualified-id is ~type-name, the type-name is looked up 198 // in the context of the entire postfix-expression. If the type T of 199 // the object expression is of a class type C, the type-name is also 200 // looked up in the scope of class C. At least one of the lookups shall 201 // find a name that refers to (possibly cv-qualified) T. 202 LookupName(Result, S); 203 } 204 } else { 205 // Perform unqualified name lookup. 206 LookupName(Result, S); 207 } 208 209 NamedDecl *IIDecl = 0; 210 switch (Result.getResultKind()) { 211 case LookupResult::NotFound: 212 case LookupResult::NotFoundInCurrentInstantiation: 213 if (CorrectedII) { 214 TypeNameValidatorCCC Validator(true, isClassName); 215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 216 Kind, S, SS, Validator); 217 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 218 TemplateTy Template; 219 bool MemberOfUnknownSpecialization; 220 UnqualifiedId TemplateName; 221 TemplateName.setIdentifier(NewII, NameLoc); 222 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 223 CXXScopeSpec NewSS, *NewSSPtr = SS; 224 if (SS && NNS) { 225 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 226 NewSSPtr = &NewSS; 227 } 228 if (Correction && (NNS || NewII != &II) && 229 // Ignore a correction to a template type as the to-be-corrected 230 // identifier is not a template (typo correction for template names 231 // is handled elsewhere). 232 !(getLangOpts().CPlusPlus && NewSSPtr && 233 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 234 false, Template, MemberOfUnknownSpecialization))) { 235 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 236 isClassName, HasTrailingDot, ObjectTypePtr, 237 IsCtorOrDtorName, 238 WantNontrivialTypeSourceInfo); 239 if (Ty) { 240 diagnoseTypo(Correction, 241 PDiag(diag::err_unknown_type_or_class_name_suggest) 242 << Result.getLookupName() << isClassName); 243 if (SS && NNS) 244 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 245 *CorrectedII = NewII; 246 return Ty; 247 } 248 } 249 } 250 // If typo correction failed or was not performed, fall through 251 case LookupResult::FoundOverloaded: 252 case LookupResult::FoundUnresolvedValue: 253 Result.suppressDiagnostics(); 254 return ParsedType(); 255 256 case LookupResult::Ambiguous: 257 // Recover from type-hiding ambiguities by hiding the type. We'll 258 // do the lookup again when looking for an object, and we can 259 // diagnose the error then. If we don't do this, then the error 260 // about hiding the type will be immediately followed by an error 261 // that only makes sense if the identifier was treated like a type. 262 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 263 Result.suppressDiagnostics(); 264 return ParsedType(); 265 } 266 267 // Look to see if we have a type anywhere in the list of results. 268 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 269 Res != ResEnd; ++Res) { 270 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 271 if (!IIDecl || 272 (*Res)->getLocation().getRawEncoding() < 273 IIDecl->getLocation().getRawEncoding()) 274 IIDecl = *Res; 275 } 276 } 277 278 if (!IIDecl) { 279 // None of the entities we found is a type, so there is no way 280 // to even assume that the result is a type. In this case, don't 281 // complain about the ambiguity. The parser will either try to 282 // perform this lookup again (e.g., as an object name), which 283 // will produce the ambiguity, or will complain that it expected 284 // a type name. 285 Result.suppressDiagnostics(); 286 return ParsedType(); 287 } 288 289 // We found a type within the ambiguous lookup; diagnose the 290 // ambiguity and then return that type. This might be the right 291 // answer, or it might not be, but it suppresses any attempt to 292 // perform the name lookup again. 293 break; 294 295 case LookupResult::Found: 296 IIDecl = Result.getFoundDecl(); 297 break; 298 } 299 300 assert(IIDecl && "Didn't find decl"); 301 302 QualType T; 303 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 304 DiagnoseUseOfDecl(IIDecl, NameLoc); 305 306 if (T.isNull()) 307 T = Context.getTypeDeclType(TD); 308 309 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 310 // constructor or destructor name (in such a case, the scope specifier 311 // will be attached to the enclosing Expr or Decl node). 312 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 313 if (WantNontrivialTypeSourceInfo) { 314 // Construct a type with type-source information. 315 TypeLocBuilder Builder; 316 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 317 318 T = getElaboratedType(ETK_None, *SS, T); 319 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 320 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 321 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 322 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 323 } else { 324 T = getElaboratedType(ETK_None, *SS, T); 325 } 326 } 327 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 328 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 329 if (!HasTrailingDot) 330 T = Context.getObjCInterfaceType(IDecl); 331 } 332 333 if (T.isNull()) { 334 // If it's not plausibly a type, suppress diagnostics. 335 Result.suppressDiagnostics(); 336 return ParsedType(); 337 } 338 return ParsedType::make(T); 339 } 340 341 /// isTagName() - This method is called *for error recovery purposes only* 342 /// to determine if the specified name is a valid tag name ("struct foo"). If 343 /// so, this returns the TST for the tag corresponding to it (TST_enum, 344 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 345 /// cases in C where the user forgot to specify the tag. 346 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 347 // Do a tag name lookup in this scope. 348 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 349 LookupName(R, S, false); 350 R.suppressDiagnostics(); 351 if (R.getResultKind() == LookupResult::Found) 352 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 353 switch (TD->getTagKind()) { 354 case TTK_Struct: return DeclSpec::TST_struct; 355 case TTK_Interface: return DeclSpec::TST_interface; 356 case TTK_Union: return DeclSpec::TST_union; 357 case TTK_Class: return DeclSpec::TST_class; 358 case TTK_Enum: return DeclSpec::TST_enum; 359 } 360 } 361 362 return DeclSpec::TST_unspecified; 363 } 364 365 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 366 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 367 /// then downgrade the missing typename error to a warning. 368 /// This is needed for MSVC compatibility; Example: 369 /// @code 370 /// template<class T> class A { 371 /// public: 372 /// typedef int TYPE; 373 /// }; 374 /// template<class T> class B : public A<T> { 375 /// public: 376 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 377 /// }; 378 /// @endcode 379 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 380 if (CurContext->isRecord()) { 381 const Type *Ty = SS->getScopeRep()->getAsType(); 382 383 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 384 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 385 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 386 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 387 return true; 388 return S->isFunctionPrototypeScope(); 389 } 390 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 391 } 392 393 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 394 SourceLocation IILoc, 395 Scope *S, 396 CXXScopeSpec *SS, 397 ParsedType &SuggestedType) { 398 // We don't have anything to suggest (yet). 399 SuggestedType = ParsedType(); 400 401 // There may have been a typo in the name of the type. Look up typo 402 // results, in case we have something that we can suggest. 403 TypeNameValidatorCCC Validator(false); 404 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 405 LookupOrdinaryName, S, SS, 406 Validator)) { 407 if (Corrected.isKeyword()) { 408 // We corrected to a keyword. 409 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 410 II = Corrected.getCorrectionAsIdentifierInfo(); 411 } else { 412 // We found a similarly-named type or interface; suggest that. 413 if (!SS || !SS->isSet()) { 414 diagnoseTypo(Corrected, 415 PDiag(diag::err_unknown_typename_suggest) << II); 416 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 417 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 418 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 419 II->getName().equals(CorrectedStr); 420 diagnoseTypo(Corrected, 421 PDiag(diag::err_unknown_nested_typename_suggest) 422 << II << DC << DroppedSpecifier << SS->getRange()); 423 } else { 424 llvm_unreachable("could not have corrected a typo here"); 425 } 426 427 CXXScopeSpec tmpSS; 428 if (Corrected.getCorrectionSpecifier()) 429 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 430 SourceRange(IILoc)); 431 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 432 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 433 false, ParsedType(), 434 /*IsCtorOrDtorName=*/false, 435 /*NonTrivialTypeSourceInfo=*/true); 436 } 437 return true; 438 } 439 440 if (getLangOpts().CPlusPlus) { 441 // See if II is a class template that the user forgot to pass arguments to. 442 UnqualifiedId Name; 443 Name.setIdentifier(II, IILoc); 444 CXXScopeSpec EmptySS; 445 TemplateTy TemplateResult; 446 bool MemberOfUnknownSpecialization; 447 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 448 Name, ParsedType(), true, TemplateResult, 449 MemberOfUnknownSpecialization) == TNK_Type_template) { 450 TemplateName TplName = TemplateResult.get(); 451 Diag(IILoc, diag::err_template_missing_args) << TplName; 452 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 453 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 454 << TplDecl->getTemplateParameters()->getSourceRange(); 455 } 456 return true; 457 } 458 } 459 460 // FIXME: Should we move the logic that tries to recover from a missing tag 461 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 462 463 if (!SS || (!SS->isSet() && !SS->isInvalid())) 464 Diag(IILoc, diag::err_unknown_typename) << II; 465 else if (DeclContext *DC = computeDeclContext(*SS, false)) 466 Diag(IILoc, diag::err_typename_nested_not_found) 467 << II << DC << SS->getRange(); 468 else if (isDependentScopeSpecifier(*SS)) { 469 unsigned DiagID = diag::err_typename_missing; 470 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 471 DiagID = diag::warn_typename_missing; 472 473 Diag(SS->getRange().getBegin(), DiagID) 474 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName() 475 << SourceRange(SS->getRange().getBegin(), IILoc) 476 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 477 SuggestedType = ActOnTypenameType(S, SourceLocation(), 478 *SS, *II, IILoc).get(); 479 } else { 480 assert(SS && SS->isInvalid() && 481 "Invalid scope specifier has already been diagnosed"); 482 } 483 484 return true; 485 } 486 487 /// \brief Determine whether the given result set contains either a type name 488 /// or 489 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 490 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 491 NextToken.is(tok::less); 492 493 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 494 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 495 return true; 496 497 if (CheckTemplate && isa<TemplateDecl>(*I)) 498 return true; 499 } 500 501 return false; 502 } 503 504 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 505 Scope *S, CXXScopeSpec &SS, 506 IdentifierInfo *&Name, 507 SourceLocation NameLoc) { 508 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 509 SemaRef.LookupParsedName(R, S, &SS); 510 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 511 const char *TagName = 0; 512 const char *FixItTagName = 0; 513 switch (Tag->getTagKind()) { 514 case TTK_Class: 515 TagName = "class"; 516 FixItTagName = "class "; 517 break; 518 519 case TTK_Enum: 520 TagName = "enum"; 521 FixItTagName = "enum "; 522 break; 523 524 case TTK_Struct: 525 TagName = "struct"; 526 FixItTagName = "struct "; 527 break; 528 529 case TTK_Interface: 530 TagName = "__interface"; 531 FixItTagName = "__interface "; 532 break; 533 534 case TTK_Union: 535 TagName = "union"; 536 FixItTagName = "union "; 537 break; 538 } 539 540 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 541 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 542 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 543 544 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 545 I != IEnd; ++I) 546 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 547 << Name << TagName; 548 549 // Replace lookup results with just the tag decl. 550 Result.clear(Sema::LookupTagName); 551 SemaRef.LookupParsedName(Result, S, &SS); 552 return true; 553 } 554 555 return false; 556 } 557 558 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 559 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 560 QualType T, SourceLocation NameLoc) { 561 ASTContext &Context = S.Context; 562 563 TypeLocBuilder Builder; 564 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 565 566 T = S.getElaboratedType(ETK_None, SS, T); 567 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 568 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 569 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 570 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 571 } 572 573 Sema::NameClassification Sema::ClassifyName(Scope *S, 574 CXXScopeSpec &SS, 575 IdentifierInfo *&Name, 576 SourceLocation NameLoc, 577 const Token &NextToken, 578 bool IsAddressOfOperand, 579 CorrectionCandidateCallback *CCC) { 580 DeclarationNameInfo NameInfo(Name, NameLoc); 581 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 582 583 if (NextToken.is(tok::coloncolon)) { 584 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 585 QualType(), false, SS, 0, false); 586 587 } 588 589 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 590 LookupParsedName(Result, S, &SS, !CurMethod); 591 592 // Perform lookup for Objective-C instance variables (including automatically 593 // synthesized instance variables), if we're in an Objective-C method. 594 // FIXME: This lookup really, really needs to be folded in to the normal 595 // unqualified lookup mechanism. 596 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 597 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 598 if (E.get() || E.isInvalid()) 599 return E; 600 } 601 602 bool SecondTry = false; 603 bool IsFilteredTemplateName = false; 604 605 Corrected: 606 switch (Result.getResultKind()) { 607 case LookupResult::NotFound: 608 // If an unqualified-id is followed by a '(', then we have a function 609 // call. 610 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 611 // In C++, this is an ADL-only call. 612 // FIXME: Reference? 613 if (getLangOpts().CPlusPlus) 614 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 615 616 // C90 6.3.2.2: 617 // If the expression that precedes the parenthesized argument list in a 618 // function call consists solely of an identifier, and if no 619 // declaration is visible for this identifier, the identifier is 620 // implicitly declared exactly as if, in the innermost block containing 621 // the function call, the declaration 622 // 623 // extern int identifier (); 624 // 625 // appeared. 626 // 627 // We also allow this in C99 as an extension. 628 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 629 Result.addDecl(D); 630 Result.resolveKind(); 631 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 632 } 633 } 634 635 // In C, we first see whether there is a tag type by the same name, in 636 // which case it's likely that the user just forget to write "enum", 637 // "struct", or "union". 638 if (!getLangOpts().CPlusPlus && !SecondTry && 639 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 640 break; 641 } 642 643 // Perform typo correction to determine if there is another name that is 644 // close to this name. 645 if (!SecondTry && CCC) { 646 SecondTry = true; 647 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 648 Result.getLookupKind(), S, 649 &SS, *CCC)) { 650 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 651 unsigned QualifiedDiag = diag::err_no_member_suggest; 652 653 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 654 NamedDecl *UnderlyingFirstDecl 655 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 656 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 657 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 658 UnqualifiedDiag = diag::err_no_template_suggest; 659 QualifiedDiag = diag::err_no_member_template_suggest; 660 } else if (UnderlyingFirstDecl && 661 (isa<TypeDecl>(UnderlyingFirstDecl) || 662 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 663 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 664 UnqualifiedDiag = diag::err_unknown_typename_suggest; 665 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 666 } 667 668 if (SS.isEmpty()) { 669 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 670 } else {// FIXME: is this even reachable? Test it. 671 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 672 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 673 Name->getName().equals(CorrectedStr); 674 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 675 << Name << computeDeclContext(SS, false) 676 << DroppedSpecifier << SS.getRange()); 677 } 678 679 // Update the name, so that the caller has the new name. 680 Name = Corrected.getCorrectionAsIdentifierInfo(); 681 682 // Typo correction corrected to a keyword. 683 if (Corrected.isKeyword()) 684 return Name; 685 686 // Also update the LookupResult... 687 // FIXME: This should probably go away at some point 688 Result.clear(); 689 Result.setLookupName(Corrected.getCorrection()); 690 if (FirstDecl) 691 Result.addDecl(FirstDecl); 692 693 // If we found an Objective-C instance variable, let 694 // LookupInObjCMethod build the appropriate expression to 695 // reference the ivar. 696 // FIXME: This is a gross hack. 697 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 698 Result.clear(); 699 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 700 return E; 701 } 702 703 goto Corrected; 704 } 705 } 706 707 // We failed to correct; just fall through and let the parser deal with it. 708 Result.suppressDiagnostics(); 709 return NameClassification::Unknown(); 710 711 case LookupResult::NotFoundInCurrentInstantiation: { 712 // We performed name lookup into the current instantiation, and there were 713 // dependent bases, so we treat this result the same way as any other 714 // dependent nested-name-specifier. 715 716 // C++ [temp.res]p2: 717 // A name used in a template declaration or definition and that is 718 // dependent on a template-parameter is assumed not to name a type 719 // unless the applicable name lookup finds a type name or the name is 720 // qualified by the keyword typename. 721 // 722 // FIXME: If the next token is '<', we might want to ask the parser to 723 // perform some heroics to see if we actually have a 724 // template-argument-list, which would indicate a missing 'template' 725 // keyword here. 726 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 727 NameInfo, IsAddressOfOperand, 728 /*TemplateArgs=*/0); 729 } 730 731 case LookupResult::Found: 732 case LookupResult::FoundOverloaded: 733 case LookupResult::FoundUnresolvedValue: 734 break; 735 736 case LookupResult::Ambiguous: 737 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 738 hasAnyAcceptableTemplateNames(Result)) { 739 // C++ [temp.local]p3: 740 // A lookup that finds an injected-class-name (10.2) can result in an 741 // ambiguity in certain cases (for example, if it is found in more than 742 // one base class). If all of the injected-class-names that are found 743 // refer to specializations of the same class template, and if the name 744 // is followed by a template-argument-list, the reference refers to the 745 // class template itself and not a specialization thereof, and is not 746 // ambiguous. 747 // 748 // This filtering can make an ambiguous result into an unambiguous one, 749 // so try again after filtering out template names. 750 FilterAcceptableTemplateNames(Result); 751 if (!Result.isAmbiguous()) { 752 IsFilteredTemplateName = true; 753 break; 754 } 755 } 756 757 // Diagnose the ambiguity and return an error. 758 return NameClassification::Error(); 759 } 760 761 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 762 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 763 // C++ [temp.names]p3: 764 // After name lookup (3.4) finds that a name is a template-name or that 765 // an operator-function-id or a literal- operator-id refers to a set of 766 // overloaded functions any member of which is a function template if 767 // this is followed by a <, the < is always taken as the delimiter of a 768 // template-argument-list and never as the less-than operator. 769 if (!IsFilteredTemplateName) 770 FilterAcceptableTemplateNames(Result); 771 772 if (!Result.empty()) { 773 bool IsFunctionTemplate; 774 bool IsVarTemplate; 775 TemplateName Template; 776 if (Result.end() - Result.begin() > 1) { 777 IsFunctionTemplate = true; 778 Template = Context.getOverloadedTemplateName(Result.begin(), 779 Result.end()); 780 } else { 781 TemplateDecl *TD 782 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 783 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 784 IsVarTemplate = isa<VarTemplateDecl>(TD); 785 786 if (SS.isSet() && !SS.isInvalid()) 787 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 788 /*TemplateKeyword=*/false, 789 TD); 790 else 791 Template = TemplateName(TD); 792 } 793 794 if (IsFunctionTemplate) { 795 // Function templates always go through overload resolution, at which 796 // point we'll perform the various checks (e.g., accessibility) we need 797 // to based on which function we selected. 798 Result.suppressDiagnostics(); 799 800 return NameClassification::FunctionTemplate(Template); 801 } 802 803 return IsVarTemplate ? NameClassification::VarTemplate(Template) 804 : NameClassification::TypeTemplate(Template); 805 } 806 } 807 808 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 809 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 810 DiagnoseUseOfDecl(Type, NameLoc); 811 QualType T = Context.getTypeDeclType(Type); 812 if (SS.isNotEmpty()) 813 return buildNestedType(*this, SS, T, NameLoc); 814 return ParsedType::make(T); 815 } 816 817 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 818 if (!Class) { 819 // FIXME: It's unfortunate that we don't have a Type node for handling this. 820 if (ObjCCompatibleAliasDecl *Alias 821 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 822 Class = Alias->getClassInterface(); 823 } 824 825 if (Class) { 826 DiagnoseUseOfDecl(Class, NameLoc); 827 828 if (NextToken.is(tok::period)) { 829 // Interface. <something> is parsed as a property reference expression. 830 // Just return "unknown" as a fall-through for now. 831 Result.suppressDiagnostics(); 832 return NameClassification::Unknown(); 833 } 834 835 QualType T = Context.getObjCInterfaceType(Class); 836 return ParsedType::make(T); 837 } 838 839 // We can have a type template here if we're classifying a template argument. 840 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 841 return NameClassification::TypeTemplate( 842 TemplateName(cast<TemplateDecl>(FirstDecl))); 843 844 // Check for a tag type hidden by a non-type decl in a few cases where it 845 // seems likely a type is wanted instead of the non-type that was found. 846 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 847 if ((NextToken.is(tok::identifier) || 848 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 849 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 850 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 851 DiagnoseUseOfDecl(Type, NameLoc); 852 QualType T = Context.getTypeDeclType(Type); 853 if (SS.isNotEmpty()) 854 return buildNestedType(*this, SS, T, NameLoc); 855 return ParsedType::make(T); 856 } 857 858 if (FirstDecl->isCXXClassMember()) 859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 860 861 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 862 return BuildDeclarationNameExpr(SS, Result, ADL); 863 } 864 865 // Determines the context to return to after temporarily entering a 866 // context. This depends in an unnecessarily complicated way on the 867 // exact ordering of callbacks from the parser. 868 DeclContext *Sema::getContainingDC(DeclContext *DC) { 869 870 // Functions defined inline within classes aren't parsed until we've 871 // finished parsing the top-level class, so the top-level class is 872 // the context we'll need to return to. 873 if (isa<FunctionDecl>(DC)) { 874 DC = DC->getLexicalParent(); 875 876 // A function not defined within a class will always return to its 877 // lexical context. 878 if (!isa<CXXRecordDecl>(DC)) 879 return DC; 880 881 // A C++ inline method/friend is parsed *after* the topmost class 882 // it was declared in is fully parsed ("complete"); the topmost 883 // class is the context we need to return to. 884 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 885 DC = RD; 886 887 // Return the declaration context of the topmost class the inline method is 888 // declared in. 889 return DC; 890 } 891 892 return DC->getLexicalParent(); 893 } 894 895 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 896 assert(getContainingDC(DC) == CurContext && 897 "The next DeclContext should be lexically contained in the current one."); 898 CurContext = DC; 899 S->setEntity(DC); 900 } 901 902 void Sema::PopDeclContext() { 903 assert(CurContext && "DeclContext imbalance!"); 904 905 CurContext = getContainingDC(CurContext); 906 assert(CurContext && "Popped translation unit!"); 907 } 908 909 /// EnterDeclaratorContext - Used when we must lookup names in the context 910 /// of a declarator's nested name specifier. 911 /// 912 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 913 // C++0x [basic.lookup.unqual]p13: 914 // A name used in the definition of a static data member of class 915 // X (after the qualified-id of the static member) is looked up as 916 // if the name was used in a member function of X. 917 // C++0x [basic.lookup.unqual]p14: 918 // If a variable member of a namespace is defined outside of the 919 // scope of its namespace then any name used in the definition of 920 // the variable member (after the declarator-id) is looked up as 921 // if the definition of the variable member occurred in its 922 // namespace. 923 // Both of these imply that we should push a scope whose context 924 // is the semantic context of the declaration. We can't use 925 // PushDeclContext here because that context is not necessarily 926 // lexically contained in the current context. Fortunately, 927 // the containing scope should have the appropriate information. 928 929 assert(!S->getEntity() && "scope already has entity"); 930 931 #ifndef NDEBUG 932 Scope *Ancestor = S->getParent(); 933 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 934 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 935 #endif 936 937 CurContext = DC; 938 S->setEntity(DC); 939 } 940 941 void Sema::ExitDeclaratorContext(Scope *S) { 942 assert(S->getEntity() == CurContext && "Context imbalance!"); 943 944 // Switch back to the lexical context. The safety of this is 945 // enforced by an assert in EnterDeclaratorContext. 946 Scope *Ancestor = S->getParent(); 947 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 948 CurContext = Ancestor->getEntity(); 949 950 // We don't need to do anything with the scope, which is going to 951 // disappear. 952 } 953 954 955 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 956 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 957 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 958 // We assume that the caller has already called 959 // ActOnReenterTemplateScope 960 FD = TFD->getTemplatedDecl(); 961 } 962 if (!FD) 963 return; 964 965 // Same implementation as PushDeclContext, but enters the context 966 // from the lexical parent, rather than the top-level class. 967 assert(CurContext == FD->getLexicalParent() && 968 "The next DeclContext should be lexically contained in the current one."); 969 CurContext = FD; 970 S->setEntity(CurContext); 971 972 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 973 ParmVarDecl *Param = FD->getParamDecl(P); 974 // If the parameter has an identifier, then add it to the scope 975 if (Param->getIdentifier()) { 976 S->AddDecl(Param); 977 IdResolver.AddDecl(Param); 978 } 979 } 980 } 981 982 983 void Sema::ActOnExitFunctionContext() { 984 // Same implementation as PopDeclContext, but returns to the lexical parent, 985 // rather than the top-level class. 986 assert(CurContext && "DeclContext imbalance!"); 987 CurContext = CurContext->getLexicalParent(); 988 assert(CurContext && "Popped translation unit!"); 989 } 990 991 992 /// \brief Determine whether we allow overloading of the function 993 /// PrevDecl with another declaration. 994 /// 995 /// This routine determines whether overloading is possible, not 996 /// whether some new function is actually an overload. It will return 997 /// true in C++ (where we can always provide overloads) or, as an 998 /// extension, in C when the previous function is already an 999 /// overloaded function declaration or has the "overloadable" 1000 /// attribute. 1001 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1002 ASTContext &Context) { 1003 if (Context.getLangOpts().CPlusPlus) 1004 return true; 1005 1006 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1007 return true; 1008 1009 return (Previous.getResultKind() == LookupResult::Found 1010 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1011 } 1012 1013 /// Add this decl to the scope shadowed decl chains. 1014 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1015 // Move up the scope chain until we find the nearest enclosing 1016 // non-transparent context. The declaration will be introduced into this 1017 // scope. 1018 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1019 S = S->getParent(); 1020 1021 // Add scoped declarations into their context, so that they can be 1022 // found later. Declarations without a context won't be inserted 1023 // into any context. 1024 if (AddToContext) 1025 CurContext->addDecl(D); 1026 1027 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1028 // are function-local declarations. 1029 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1030 !D->getDeclContext()->getRedeclContext()->Equals( 1031 D->getLexicalDeclContext()->getRedeclContext()) && 1032 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1033 return; 1034 1035 // Template instantiations should also not be pushed into scope. 1036 if (isa<FunctionDecl>(D) && 1037 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1038 return; 1039 1040 // If this replaces anything in the current scope, 1041 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1042 IEnd = IdResolver.end(); 1043 for (; I != IEnd; ++I) { 1044 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1045 S->RemoveDecl(*I); 1046 IdResolver.RemoveDecl(*I); 1047 1048 // Should only need to replace one decl. 1049 break; 1050 } 1051 } 1052 1053 S->AddDecl(D); 1054 1055 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1056 // Implicitly-generated labels may end up getting generated in an order that 1057 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1058 // the label at the appropriate place in the identifier chain. 1059 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1060 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1061 if (IDC == CurContext) { 1062 if (!S->isDeclScope(*I)) 1063 continue; 1064 } else if (IDC->Encloses(CurContext)) 1065 break; 1066 } 1067 1068 IdResolver.InsertDeclAfter(I, D); 1069 } else { 1070 IdResolver.AddDecl(D); 1071 } 1072 } 1073 1074 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1075 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1076 TUScope->AddDecl(D); 1077 } 1078 1079 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1080 bool ExplicitInstantiationOrSpecialization) { 1081 return IdResolver.isDeclInScope(D, Ctx, S, 1082 ExplicitInstantiationOrSpecialization); 1083 } 1084 1085 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1086 DeclContext *TargetDC = DC->getPrimaryContext(); 1087 do { 1088 if (DeclContext *ScopeDC = S->getEntity()) 1089 if (ScopeDC->getPrimaryContext() == TargetDC) 1090 return S; 1091 } while ((S = S->getParent())); 1092 1093 return 0; 1094 } 1095 1096 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1097 DeclContext*, 1098 ASTContext&); 1099 1100 /// Filters out lookup results that don't fall within the given scope 1101 /// as determined by isDeclInScope. 1102 void Sema::FilterLookupForScope(LookupResult &R, 1103 DeclContext *Ctx, Scope *S, 1104 bool ConsiderLinkage, 1105 bool ExplicitInstantiationOrSpecialization) { 1106 LookupResult::Filter F = R.makeFilter(); 1107 while (F.hasNext()) { 1108 NamedDecl *D = F.next(); 1109 1110 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 1111 continue; 1112 1113 if (ConsiderLinkage && 1114 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1115 continue; 1116 1117 F.erase(); 1118 } 1119 1120 F.done(); 1121 } 1122 1123 static bool isUsingDecl(NamedDecl *D) { 1124 return isa<UsingShadowDecl>(D) || 1125 isa<UnresolvedUsingTypenameDecl>(D) || 1126 isa<UnresolvedUsingValueDecl>(D); 1127 } 1128 1129 /// Removes using shadow declarations from the lookup results. 1130 static void RemoveUsingDecls(LookupResult &R) { 1131 LookupResult::Filter F = R.makeFilter(); 1132 while (F.hasNext()) 1133 if (isUsingDecl(F.next())) 1134 F.erase(); 1135 1136 F.done(); 1137 } 1138 1139 /// \brief Check for this common pattern: 1140 /// @code 1141 /// class S { 1142 /// S(const S&); // DO NOT IMPLEMENT 1143 /// void operator=(const S&); // DO NOT IMPLEMENT 1144 /// }; 1145 /// @endcode 1146 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1147 // FIXME: Should check for private access too but access is set after we get 1148 // the decl here. 1149 if (D->doesThisDeclarationHaveABody()) 1150 return false; 1151 1152 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1153 return CD->isCopyConstructor(); 1154 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1155 return Method->isCopyAssignmentOperator(); 1156 return false; 1157 } 1158 1159 // We need this to handle 1160 // 1161 // typedef struct { 1162 // void *foo() { return 0; } 1163 // } A; 1164 // 1165 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1166 // for example. If 'A', foo will have external linkage. If we have '*A', 1167 // foo will have no linkage. Since we can't know untill we get to the end 1168 // of the typedef, this function finds out if D might have non external linkage. 1169 // Callers should verify at the end of the TU if it D has external linkage or 1170 // not. 1171 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1172 const DeclContext *DC = D->getDeclContext(); 1173 while (!DC->isTranslationUnit()) { 1174 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1175 if (!RD->hasNameForLinkage()) 1176 return true; 1177 } 1178 DC = DC->getParent(); 1179 } 1180 1181 return !D->isExternallyVisible(); 1182 } 1183 1184 // FIXME: This needs to be refactored; some other isInMainFile users want 1185 // these semantics. 1186 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1187 if (S.TUKind != TU_Complete) 1188 return false; 1189 return S.SourceMgr.isInMainFile(Loc); 1190 } 1191 1192 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1193 assert(D); 1194 1195 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1196 return false; 1197 1198 // Ignore class templates. 1199 if (D->getDeclContext()->isDependentContext() || 1200 D->getLexicalDeclContext()->isDependentContext()) 1201 return false; 1202 1203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1204 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1205 return false; 1206 1207 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1208 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1209 return false; 1210 } else { 1211 // 'static inline' functions are defined in headers; don't warn. 1212 if (FD->isInlineSpecified() && 1213 !isMainFileLoc(*this, FD->getLocation())) 1214 return false; 1215 } 1216 1217 if (FD->doesThisDeclarationHaveABody() && 1218 Context.DeclMustBeEmitted(FD)) 1219 return false; 1220 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1221 // Constants and utility variables are defined in headers with internal 1222 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1223 // like "inline".) 1224 if (!isMainFileLoc(*this, VD->getLocation())) 1225 return false; 1226 1227 if (Context.DeclMustBeEmitted(VD)) 1228 return false; 1229 1230 if (VD->isStaticDataMember() && 1231 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1232 return false; 1233 } else { 1234 return false; 1235 } 1236 1237 // Only warn for unused decls internal to the translation unit. 1238 return mightHaveNonExternalLinkage(D); 1239 } 1240 1241 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1242 if (!D) 1243 return; 1244 1245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1246 const FunctionDecl *First = FD->getFirstDecl(); 1247 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1248 return; // First should already be in the vector. 1249 } 1250 1251 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1252 const VarDecl *First = VD->getFirstDecl(); 1253 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1254 return; // First should already be in the vector. 1255 } 1256 1257 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1258 UnusedFileScopedDecls.push_back(D); 1259 } 1260 1261 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1262 if (D->isInvalidDecl()) 1263 return false; 1264 1265 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1266 return false; 1267 1268 if (isa<LabelDecl>(D)) 1269 return true; 1270 1271 // White-list anything that isn't a local variable. 1272 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1273 !D->getDeclContext()->isFunctionOrMethod()) 1274 return false; 1275 1276 // Types of valid local variables should be complete, so this should succeed. 1277 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1278 1279 // White-list anything with an __attribute__((unused)) type. 1280 QualType Ty = VD->getType(); 1281 1282 // Only look at the outermost level of typedef. 1283 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1284 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1285 return false; 1286 } 1287 1288 // If we failed to complete the type for some reason, or if the type is 1289 // dependent, don't diagnose the variable. 1290 if (Ty->isIncompleteType() || Ty->isDependentType()) 1291 return false; 1292 1293 if (const TagType *TT = Ty->getAs<TagType>()) { 1294 const TagDecl *Tag = TT->getDecl(); 1295 if (Tag->hasAttr<UnusedAttr>()) 1296 return false; 1297 1298 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1299 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1300 return false; 1301 1302 if (const Expr *Init = VD->getInit()) { 1303 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1304 Init = Cleanups->getSubExpr(); 1305 const CXXConstructExpr *Construct = 1306 dyn_cast<CXXConstructExpr>(Init); 1307 if (Construct && !Construct->isElidable()) { 1308 CXXConstructorDecl *CD = Construct->getConstructor(); 1309 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1310 return false; 1311 } 1312 } 1313 } 1314 } 1315 1316 // TODO: __attribute__((unused)) templates? 1317 } 1318 1319 return true; 1320 } 1321 1322 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1323 FixItHint &Hint) { 1324 if (isa<LabelDecl>(D)) { 1325 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1326 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1327 if (AfterColon.isInvalid()) 1328 return; 1329 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1330 getCharRange(D->getLocStart(), AfterColon)); 1331 } 1332 return; 1333 } 1334 1335 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1336 /// unless they are marked attr(unused). 1337 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1338 FixItHint Hint; 1339 if (!ShouldDiagnoseUnusedDecl(D)) 1340 return; 1341 1342 GenerateFixForUnusedDecl(D, Context, Hint); 1343 1344 unsigned DiagID; 1345 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1346 DiagID = diag::warn_unused_exception_param; 1347 else if (isa<LabelDecl>(D)) 1348 DiagID = diag::warn_unused_label; 1349 else 1350 DiagID = diag::warn_unused_variable; 1351 1352 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1353 } 1354 1355 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1356 // Verify that we have no forward references left. If so, there was a goto 1357 // or address of a label taken, but no definition of it. Label fwd 1358 // definitions are indicated with a null substmt. 1359 if (L->getStmt() == 0) 1360 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1361 } 1362 1363 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1364 if (S->decl_empty()) return; 1365 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1366 "Scope shouldn't contain decls!"); 1367 1368 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1369 I != E; ++I) { 1370 Decl *TmpD = (*I); 1371 assert(TmpD && "This decl didn't get pushed??"); 1372 1373 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1374 NamedDecl *D = cast<NamedDecl>(TmpD); 1375 1376 if (!D->getDeclName()) continue; 1377 1378 // Diagnose unused variables in this scope. 1379 if (!S->hasUnrecoverableErrorOccurred()) 1380 DiagnoseUnusedDecl(D); 1381 1382 // If this was a forward reference to a label, verify it was defined. 1383 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1384 CheckPoppedLabel(LD, *this); 1385 1386 // Remove this name from our lexical scope. 1387 IdResolver.RemoveDecl(D); 1388 } 1389 DiagnoseUnusedBackingIvarInAccessor(S); 1390 } 1391 1392 void Sema::ActOnStartFunctionDeclarator() { 1393 ++InFunctionDeclarator; 1394 } 1395 1396 void Sema::ActOnEndFunctionDeclarator() { 1397 assert(InFunctionDeclarator); 1398 --InFunctionDeclarator; 1399 } 1400 1401 /// \brief Look for an Objective-C class in the translation unit. 1402 /// 1403 /// \param Id The name of the Objective-C class we're looking for. If 1404 /// typo-correction fixes this name, the Id will be updated 1405 /// to the fixed name. 1406 /// 1407 /// \param IdLoc The location of the name in the translation unit. 1408 /// 1409 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1410 /// if there is no class with the given name. 1411 /// 1412 /// \returns The declaration of the named Objective-C class, or NULL if the 1413 /// class could not be found. 1414 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1415 SourceLocation IdLoc, 1416 bool DoTypoCorrection) { 1417 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1418 // creation from this context. 1419 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1420 1421 if (!IDecl && DoTypoCorrection) { 1422 // Perform typo correction at the given location, but only if we 1423 // find an Objective-C class name. 1424 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1425 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1426 LookupOrdinaryName, TUScope, NULL, 1427 Validator)) { 1428 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1429 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1430 Id = IDecl->getIdentifier(); 1431 } 1432 } 1433 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1434 // This routine must always return a class definition, if any. 1435 if (Def && Def->getDefinition()) 1436 Def = Def->getDefinition(); 1437 return Def; 1438 } 1439 1440 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1441 /// from S, where a non-field would be declared. This routine copes 1442 /// with the difference between C and C++ scoping rules in structs and 1443 /// unions. For example, the following code is well-formed in C but 1444 /// ill-formed in C++: 1445 /// @code 1446 /// struct S6 { 1447 /// enum { BAR } e; 1448 /// }; 1449 /// 1450 /// void test_S6() { 1451 /// struct S6 a; 1452 /// a.e = BAR; 1453 /// } 1454 /// @endcode 1455 /// For the declaration of BAR, this routine will return a different 1456 /// scope. The scope S will be the scope of the unnamed enumeration 1457 /// within S6. In C++, this routine will return the scope associated 1458 /// with S6, because the enumeration's scope is a transparent 1459 /// context but structures can contain non-field names. In C, this 1460 /// routine will return the translation unit scope, since the 1461 /// enumeration's scope is a transparent context and structures cannot 1462 /// contain non-field names. 1463 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1464 while (((S->getFlags() & Scope::DeclScope) == 0) || 1465 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1466 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1467 S = S->getParent(); 1468 return S; 1469 } 1470 1471 /// \brief Looks up the declaration of "struct objc_super" and 1472 /// saves it for later use in building builtin declaration of 1473 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1474 /// pre-existing declaration exists no action takes place. 1475 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1476 IdentifierInfo *II) { 1477 if (!II->isStr("objc_msgSendSuper")) 1478 return; 1479 ASTContext &Context = ThisSema.Context; 1480 1481 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1482 SourceLocation(), Sema::LookupTagName); 1483 ThisSema.LookupName(Result, S); 1484 if (Result.getResultKind() == LookupResult::Found) 1485 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1486 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1487 } 1488 1489 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1490 /// file scope. lazily create a decl for it. ForRedeclaration is true 1491 /// if we're creating this built-in in anticipation of redeclaring the 1492 /// built-in. 1493 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1494 Scope *S, bool ForRedeclaration, 1495 SourceLocation Loc) { 1496 LookupPredefedObjCSuperType(*this, S, II); 1497 1498 Builtin::ID BID = (Builtin::ID)bid; 1499 1500 ASTContext::GetBuiltinTypeError Error; 1501 QualType R = Context.GetBuiltinType(BID, Error); 1502 switch (Error) { 1503 case ASTContext::GE_None: 1504 // Okay 1505 break; 1506 1507 case ASTContext::GE_Missing_stdio: 1508 if (ForRedeclaration) 1509 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1510 << Context.BuiltinInfo.GetName(BID); 1511 return 0; 1512 1513 case ASTContext::GE_Missing_setjmp: 1514 if (ForRedeclaration) 1515 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1516 << Context.BuiltinInfo.GetName(BID); 1517 return 0; 1518 1519 case ASTContext::GE_Missing_ucontext: 1520 if (ForRedeclaration) 1521 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1522 << Context.BuiltinInfo.GetName(BID); 1523 return 0; 1524 } 1525 1526 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1527 Diag(Loc, diag::ext_implicit_lib_function_decl) 1528 << Context.BuiltinInfo.GetName(BID) 1529 << R; 1530 if (Context.BuiltinInfo.getHeaderName(BID) && 1531 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1532 != DiagnosticsEngine::Ignored) 1533 Diag(Loc, diag::note_please_include_header) 1534 << Context.BuiltinInfo.getHeaderName(BID) 1535 << Context.BuiltinInfo.GetName(BID); 1536 } 1537 1538 DeclContext *Parent = Context.getTranslationUnitDecl(); 1539 if (getLangOpts().CPlusPlus) { 1540 LinkageSpecDecl *CLinkageDecl = 1541 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1542 LinkageSpecDecl::lang_c, false); 1543 Parent->addDecl(CLinkageDecl); 1544 Parent = CLinkageDecl; 1545 } 1546 1547 FunctionDecl *New = FunctionDecl::Create(Context, 1548 Parent, 1549 Loc, Loc, II, R, /*TInfo=*/0, 1550 SC_Extern, 1551 false, 1552 /*hasPrototype=*/true); 1553 New->setImplicit(); 1554 1555 // Create Decl objects for each parameter, adding them to the 1556 // FunctionDecl. 1557 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1558 SmallVector<ParmVarDecl*, 16> Params; 1559 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1560 ParmVarDecl *parm = 1561 ParmVarDecl::Create(Context, New, SourceLocation(), 1562 SourceLocation(), 0, 1563 FT->getArgType(i), /*TInfo=*/0, 1564 SC_None, 0); 1565 parm->setScopeInfo(0, i); 1566 Params.push_back(parm); 1567 } 1568 New->setParams(Params); 1569 } 1570 1571 AddKnownFunctionAttributes(New); 1572 RegisterLocallyScopedExternCDecl(New, S); 1573 1574 // TUScope is the translation-unit scope to insert this function into. 1575 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1576 // relate Scopes to DeclContexts, and probably eliminate CurContext 1577 // entirely, but we're not there yet. 1578 DeclContext *SavedContext = CurContext; 1579 CurContext = Parent; 1580 PushOnScopeChains(New, TUScope); 1581 CurContext = SavedContext; 1582 return New; 1583 } 1584 1585 /// \brief Filter out any previous declarations that the given declaration 1586 /// should not consider because they are not permitted to conflict, e.g., 1587 /// because they come from hidden sub-modules and do not refer to the same 1588 /// entity. 1589 static void filterNonConflictingPreviousDecls(ASTContext &context, 1590 NamedDecl *decl, 1591 LookupResult &previous){ 1592 // This is only interesting when modules are enabled. 1593 if (!context.getLangOpts().Modules) 1594 return; 1595 1596 // Empty sets are uninteresting. 1597 if (previous.empty()) 1598 return; 1599 1600 LookupResult::Filter filter = previous.makeFilter(); 1601 while (filter.hasNext()) { 1602 NamedDecl *old = filter.next(); 1603 1604 // Non-hidden declarations are never ignored. 1605 if (!old->isHidden()) 1606 continue; 1607 1608 if (!old->isExternallyVisible()) 1609 filter.erase(); 1610 } 1611 1612 filter.done(); 1613 } 1614 1615 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1616 QualType OldType; 1617 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1618 OldType = OldTypedef->getUnderlyingType(); 1619 else 1620 OldType = Context.getTypeDeclType(Old); 1621 QualType NewType = New->getUnderlyingType(); 1622 1623 if (NewType->isVariablyModifiedType()) { 1624 // Must not redefine a typedef with a variably-modified type. 1625 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1626 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1627 << Kind << NewType; 1628 if (Old->getLocation().isValid()) 1629 Diag(Old->getLocation(), diag::note_previous_definition); 1630 New->setInvalidDecl(); 1631 return true; 1632 } 1633 1634 if (OldType != NewType && 1635 !OldType->isDependentType() && 1636 !NewType->isDependentType() && 1637 !Context.hasSameType(OldType, NewType)) { 1638 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1639 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1640 << Kind << NewType << OldType; 1641 if (Old->getLocation().isValid()) 1642 Diag(Old->getLocation(), diag::note_previous_definition); 1643 New->setInvalidDecl(); 1644 return true; 1645 } 1646 return false; 1647 } 1648 1649 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1650 /// same name and scope as a previous declaration 'Old'. Figure out 1651 /// how to resolve this situation, merging decls or emitting 1652 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1653 /// 1654 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1655 // If the new decl is known invalid already, don't bother doing any 1656 // merging checks. 1657 if (New->isInvalidDecl()) return; 1658 1659 // Allow multiple definitions for ObjC built-in typedefs. 1660 // FIXME: Verify the underlying types are equivalent! 1661 if (getLangOpts().ObjC1) { 1662 const IdentifierInfo *TypeID = New->getIdentifier(); 1663 switch (TypeID->getLength()) { 1664 default: break; 1665 case 2: 1666 { 1667 if (!TypeID->isStr("id")) 1668 break; 1669 QualType T = New->getUnderlyingType(); 1670 if (!T->isPointerType()) 1671 break; 1672 if (!T->isVoidPointerType()) { 1673 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1674 if (!PT->isStructureType()) 1675 break; 1676 } 1677 Context.setObjCIdRedefinitionType(T); 1678 // Install the built-in type for 'id', ignoring the current definition. 1679 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1680 return; 1681 } 1682 case 5: 1683 if (!TypeID->isStr("Class")) 1684 break; 1685 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1686 // Install the built-in type for 'Class', ignoring the current definition. 1687 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1688 return; 1689 case 3: 1690 if (!TypeID->isStr("SEL")) 1691 break; 1692 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1693 // Install the built-in type for 'SEL', ignoring the current definition. 1694 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1695 return; 1696 } 1697 // Fall through - the typedef name was not a builtin type. 1698 } 1699 1700 // Verify the old decl was also a type. 1701 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1702 if (!Old) { 1703 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1704 << New->getDeclName(); 1705 1706 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1707 if (OldD->getLocation().isValid()) 1708 Diag(OldD->getLocation(), diag::note_previous_definition); 1709 1710 return New->setInvalidDecl(); 1711 } 1712 1713 // If the old declaration is invalid, just give up here. 1714 if (Old->isInvalidDecl()) 1715 return New->setInvalidDecl(); 1716 1717 // If the typedef types are not identical, reject them in all languages and 1718 // with any extensions enabled. 1719 if (isIncompatibleTypedef(Old, New)) 1720 return; 1721 1722 // The types match. Link up the redeclaration chain and merge attributes if 1723 // the old declaration was a typedef. 1724 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1725 New->setPreviousDecl(Typedef); 1726 mergeDeclAttributes(New, Old); 1727 } 1728 1729 if (getLangOpts().MicrosoftExt) 1730 return; 1731 1732 if (getLangOpts().CPlusPlus) { 1733 // C++ [dcl.typedef]p2: 1734 // In a given non-class scope, a typedef specifier can be used to 1735 // redefine the name of any type declared in that scope to refer 1736 // to the type to which it already refers. 1737 if (!isa<CXXRecordDecl>(CurContext)) 1738 return; 1739 1740 // C++0x [dcl.typedef]p4: 1741 // In a given class scope, a typedef specifier can be used to redefine 1742 // any class-name declared in that scope that is not also a typedef-name 1743 // to refer to the type to which it already refers. 1744 // 1745 // This wording came in via DR424, which was a correction to the 1746 // wording in DR56, which accidentally banned code like: 1747 // 1748 // struct S { 1749 // typedef struct A { } A; 1750 // }; 1751 // 1752 // in the C++03 standard. We implement the C++0x semantics, which 1753 // allow the above but disallow 1754 // 1755 // struct S { 1756 // typedef int I; 1757 // typedef int I; 1758 // }; 1759 // 1760 // since that was the intent of DR56. 1761 if (!isa<TypedefNameDecl>(Old)) 1762 return; 1763 1764 Diag(New->getLocation(), diag::err_redefinition) 1765 << New->getDeclName(); 1766 Diag(Old->getLocation(), diag::note_previous_definition); 1767 return New->setInvalidDecl(); 1768 } 1769 1770 // Modules always permit redefinition of typedefs, as does C11. 1771 if (getLangOpts().Modules || getLangOpts().C11) 1772 return; 1773 1774 // If we have a redefinition of a typedef in C, emit a warning. This warning 1775 // is normally mapped to an error, but can be controlled with 1776 // -Wtypedef-redefinition. If either the original or the redefinition is 1777 // in a system header, don't emit this for compatibility with GCC. 1778 if (getDiagnostics().getSuppressSystemWarnings() && 1779 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1780 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1781 return; 1782 1783 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1784 << New->getDeclName(); 1785 Diag(Old->getLocation(), diag::note_previous_definition); 1786 return; 1787 } 1788 1789 /// DeclhasAttr - returns true if decl Declaration already has the target 1790 /// attribute. 1791 static bool 1792 DeclHasAttr(const Decl *D, const Attr *A) { 1793 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1794 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1795 // responsible for making sure they are consistent. 1796 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1797 if (AA) 1798 return false; 1799 1800 // The following thread safety attributes can also be duplicated. 1801 switch (A->getKind()) { 1802 case attr::ExclusiveLocksRequired: 1803 case attr::SharedLocksRequired: 1804 case attr::LocksExcluded: 1805 case attr::ExclusiveLockFunction: 1806 case attr::SharedLockFunction: 1807 case attr::UnlockFunction: 1808 case attr::ExclusiveTrylockFunction: 1809 case attr::SharedTrylockFunction: 1810 case attr::GuardedBy: 1811 case attr::PtGuardedBy: 1812 case attr::AcquiredBefore: 1813 case attr::AcquiredAfter: 1814 return false; 1815 default: 1816 ; 1817 } 1818 1819 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1820 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1821 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1822 if ((*i)->getKind() == A->getKind()) { 1823 if (Ann) { 1824 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1825 return true; 1826 continue; 1827 } 1828 // FIXME: Don't hardcode this check 1829 if (OA && isa<OwnershipAttr>(*i)) 1830 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1831 return true; 1832 } 1833 1834 return false; 1835 } 1836 1837 static bool isAttributeTargetADefinition(Decl *D) { 1838 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1839 return VD->isThisDeclarationADefinition(); 1840 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1841 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1842 return true; 1843 } 1844 1845 /// Merge alignment attributes from \p Old to \p New, taking into account the 1846 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1847 /// 1848 /// \return \c true if any attributes were added to \p New. 1849 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1850 // Look for alignas attributes on Old, and pick out whichever attribute 1851 // specifies the strictest alignment requirement. 1852 AlignedAttr *OldAlignasAttr = 0; 1853 AlignedAttr *OldStrictestAlignAttr = 0; 1854 unsigned OldAlign = 0; 1855 for (specific_attr_iterator<AlignedAttr> 1856 I = Old->specific_attr_begin<AlignedAttr>(), 1857 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1858 // FIXME: We have no way of representing inherited dependent alignments 1859 // in a case like: 1860 // template<int A, int B> struct alignas(A) X; 1861 // template<int A, int B> struct alignas(B) X {}; 1862 // For now, we just ignore any alignas attributes which are not on the 1863 // definition in such a case. 1864 if (I->isAlignmentDependent()) 1865 return false; 1866 1867 if (I->isAlignas()) 1868 OldAlignasAttr = *I; 1869 1870 unsigned Align = I->getAlignment(S.Context); 1871 if (Align > OldAlign) { 1872 OldAlign = Align; 1873 OldStrictestAlignAttr = *I; 1874 } 1875 } 1876 1877 // Look for alignas attributes on New. 1878 AlignedAttr *NewAlignasAttr = 0; 1879 unsigned NewAlign = 0; 1880 for (specific_attr_iterator<AlignedAttr> 1881 I = New->specific_attr_begin<AlignedAttr>(), 1882 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1883 if (I->isAlignmentDependent()) 1884 return false; 1885 1886 if (I->isAlignas()) 1887 NewAlignasAttr = *I; 1888 1889 unsigned Align = I->getAlignment(S.Context); 1890 if (Align > NewAlign) 1891 NewAlign = Align; 1892 } 1893 1894 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1895 // Both declarations have 'alignas' attributes. We require them to match. 1896 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1897 // fall short. (If two declarations both have alignas, they must both match 1898 // every definition, and so must match each other if there is a definition.) 1899 1900 // If either declaration only contains 'alignas(0)' specifiers, then it 1901 // specifies the natural alignment for the type. 1902 if (OldAlign == 0 || NewAlign == 0) { 1903 QualType Ty; 1904 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1905 Ty = VD->getType(); 1906 else 1907 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1908 1909 if (OldAlign == 0) 1910 OldAlign = S.Context.getTypeAlign(Ty); 1911 if (NewAlign == 0) 1912 NewAlign = S.Context.getTypeAlign(Ty); 1913 } 1914 1915 if (OldAlign != NewAlign) { 1916 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1917 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1918 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1919 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1920 } 1921 } 1922 1923 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1924 // C++11 [dcl.align]p6: 1925 // if any declaration of an entity has an alignment-specifier, 1926 // every defining declaration of that entity shall specify an 1927 // equivalent alignment. 1928 // C11 6.7.5/7: 1929 // If the definition of an object does not have an alignment 1930 // specifier, any other declaration of that object shall also 1931 // have no alignment specifier. 1932 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1933 << OldAlignasAttr->isC11(); 1934 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1935 << OldAlignasAttr->isC11(); 1936 } 1937 1938 bool AnyAdded = false; 1939 1940 // Ensure we have an attribute representing the strictest alignment. 1941 if (OldAlign > NewAlign) { 1942 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1943 Clone->setInherited(true); 1944 New->addAttr(Clone); 1945 AnyAdded = true; 1946 } 1947 1948 // Ensure we have an alignas attribute if the old declaration had one. 1949 if (OldAlignasAttr && !NewAlignasAttr && 1950 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1951 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1952 Clone->setInherited(true); 1953 New->addAttr(Clone); 1954 AnyAdded = true; 1955 } 1956 1957 return AnyAdded; 1958 } 1959 1960 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1961 bool Override) { 1962 InheritableAttr *NewAttr = NULL; 1963 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1964 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1965 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1966 AA->getIntroduced(), AA->getDeprecated(), 1967 AA->getObsoleted(), AA->getUnavailable(), 1968 AA->getMessage(), Override, 1969 AttrSpellingListIndex); 1970 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1971 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1972 AttrSpellingListIndex); 1973 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1974 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1975 AttrSpellingListIndex); 1976 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1977 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1978 AttrSpellingListIndex); 1979 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1980 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1981 AttrSpellingListIndex); 1982 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1983 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1984 FA->getFormatIdx(), FA->getFirstArg(), 1985 AttrSpellingListIndex); 1986 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1987 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1988 AttrSpellingListIndex); 1989 else if (isa<AlignedAttr>(Attr)) 1990 // AlignedAttrs are handled separately, because we need to handle all 1991 // such attributes on a declaration at the same time. 1992 NewAttr = 0; 1993 else if (!DeclHasAttr(D, Attr)) 1994 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1995 1996 if (NewAttr) { 1997 NewAttr->setInherited(true); 1998 D->addAttr(NewAttr); 1999 return true; 2000 } 2001 2002 return false; 2003 } 2004 2005 static const Decl *getDefinition(const Decl *D) { 2006 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2007 return TD->getDefinition(); 2008 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2009 const VarDecl *Def = VD->getDefinition(); 2010 if (Def) 2011 return Def; 2012 return VD->getActingDefinition(); 2013 } 2014 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2015 const FunctionDecl* Def; 2016 if (FD->isDefined(Def)) 2017 return Def; 2018 } 2019 return NULL; 2020 } 2021 2022 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2023 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2024 I != E; ++I) { 2025 Attr *Attribute = *I; 2026 if (Attribute->getKind() == Kind) 2027 return true; 2028 } 2029 return false; 2030 } 2031 2032 /// checkNewAttributesAfterDef - If we already have a definition, check that 2033 /// there are no new attributes in this declaration. 2034 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2035 if (!New->hasAttrs()) 2036 return; 2037 2038 const Decl *Def = getDefinition(Old); 2039 if (!Def || Def == New) 2040 return; 2041 2042 AttrVec &NewAttributes = New->getAttrs(); 2043 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2044 const Attr *NewAttribute = NewAttributes[I]; 2045 2046 if (isa<AliasAttr>(NewAttribute)) { 2047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2048 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2049 else { 2050 VarDecl *VD = cast<VarDecl>(New); 2051 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2052 VarDecl::TentativeDefinition 2053 ? diag::err_alias_after_tentative 2054 : diag::err_redefinition; 2055 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2056 S.Diag(Def->getLocation(), diag::note_previous_definition); 2057 VD->setInvalidDecl(); 2058 } 2059 ++I; 2060 continue; 2061 } 2062 2063 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2064 // Tentative definitions are only interesting for the alias check above. 2065 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2066 ++I; 2067 continue; 2068 } 2069 } 2070 2071 if (hasAttribute(Def, NewAttribute->getKind())) { 2072 ++I; 2073 continue; // regular attr merging will take care of validating this. 2074 } 2075 2076 if (isa<C11NoReturnAttr>(NewAttribute)) { 2077 // C's _Noreturn is allowed to be added to a function after it is defined. 2078 ++I; 2079 continue; 2080 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2081 if (AA->isAlignas()) { 2082 // C++11 [dcl.align]p6: 2083 // if any declaration of an entity has an alignment-specifier, 2084 // every defining declaration of that entity shall specify an 2085 // equivalent alignment. 2086 // C11 6.7.5/7: 2087 // If the definition of an object does not have an alignment 2088 // specifier, any other declaration of that object shall also 2089 // have no alignment specifier. 2090 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2091 << AA->isC11(); 2092 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2093 << AA->isC11(); 2094 NewAttributes.erase(NewAttributes.begin() + I); 2095 --E; 2096 continue; 2097 } 2098 } 2099 2100 S.Diag(NewAttribute->getLocation(), 2101 diag::warn_attribute_precede_definition); 2102 S.Diag(Def->getLocation(), diag::note_previous_definition); 2103 NewAttributes.erase(NewAttributes.begin() + I); 2104 --E; 2105 } 2106 } 2107 2108 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2109 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2110 AvailabilityMergeKind AMK) { 2111 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2112 UsedAttr *NewAttr = OldAttr->clone(Context); 2113 NewAttr->setInherited(true); 2114 New->addAttr(NewAttr); 2115 } 2116 2117 if (!Old->hasAttrs() && !New->hasAttrs()) 2118 return; 2119 2120 // attributes declared post-definition are currently ignored 2121 checkNewAttributesAfterDef(*this, New, Old); 2122 2123 if (!Old->hasAttrs()) 2124 return; 2125 2126 bool foundAny = New->hasAttrs(); 2127 2128 // Ensure that any moving of objects within the allocated map is done before 2129 // we process them. 2130 if (!foundAny) New->setAttrs(AttrVec()); 2131 2132 for (specific_attr_iterator<InheritableAttr> 2133 i = Old->specific_attr_begin<InheritableAttr>(), 2134 e = Old->specific_attr_end<InheritableAttr>(); 2135 i != e; ++i) { 2136 bool Override = false; 2137 // Ignore deprecated/unavailable/availability attributes if requested. 2138 if (isa<DeprecatedAttr>(*i) || 2139 isa<UnavailableAttr>(*i) || 2140 isa<AvailabilityAttr>(*i)) { 2141 switch (AMK) { 2142 case AMK_None: 2143 continue; 2144 2145 case AMK_Redeclaration: 2146 break; 2147 2148 case AMK_Override: 2149 Override = true; 2150 break; 2151 } 2152 } 2153 2154 // Already handled. 2155 if (isa<UsedAttr>(*i)) 2156 continue; 2157 2158 if (mergeDeclAttribute(*this, New, *i, Override)) 2159 foundAny = true; 2160 } 2161 2162 if (mergeAlignedAttrs(*this, New, Old)) 2163 foundAny = true; 2164 2165 if (!foundAny) New->dropAttrs(); 2166 } 2167 2168 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2169 /// to the new one. 2170 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2171 const ParmVarDecl *oldDecl, 2172 Sema &S) { 2173 // C++11 [dcl.attr.depend]p2: 2174 // The first declaration of a function shall specify the 2175 // carries_dependency attribute for its declarator-id if any declaration 2176 // of the function specifies the carries_dependency attribute. 2177 if (newDecl->hasAttr<CarriesDependencyAttr>() && 2178 !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2179 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(), 2180 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2181 // Find the first declaration of the parameter. 2182 // FIXME: Should we build redeclaration chains for function parameters? 2183 const FunctionDecl *FirstFD = 2184 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2185 const ParmVarDecl *FirstVD = 2186 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2187 S.Diag(FirstVD->getLocation(), 2188 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2189 } 2190 2191 if (!oldDecl->hasAttrs()) 2192 return; 2193 2194 bool foundAny = newDecl->hasAttrs(); 2195 2196 // Ensure that any moving of objects within the allocated map is 2197 // done before we process them. 2198 if (!foundAny) newDecl->setAttrs(AttrVec()); 2199 2200 for (specific_attr_iterator<InheritableParamAttr> 2201 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2202 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2203 if (!DeclHasAttr(newDecl, *i)) { 2204 InheritableAttr *newAttr = 2205 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2206 newAttr->setInherited(true); 2207 newDecl->addAttr(newAttr); 2208 foundAny = true; 2209 } 2210 } 2211 2212 if (!foundAny) newDecl->dropAttrs(); 2213 } 2214 2215 namespace { 2216 2217 /// Used in MergeFunctionDecl to keep track of function parameters in 2218 /// C. 2219 struct GNUCompatibleParamWarning { 2220 ParmVarDecl *OldParm; 2221 ParmVarDecl *NewParm; 2222 QualType PromotedType; 2223 }; 2224 2225 } 2226 2227 /// getSpecialMember - get the special member enum for a method. 2228 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2229 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2230 if (Ctor->isDefaultConstructor()) 2231 return Sema::CXXDefaultConstructor; 2232 2233 if (Ctor->isCopyConstructor()) 2234 return Sema::CXXCopyConstructor; 2235 2236 if (Ctor->isMoveConstructor()) 2237 return Sema::CXXMoveConstructor; 2238 } else if (isa<CXXDestructorDecl>(MD)) { 2239 return Sema::CXXDestructor; 2240 } else if (MD->isCopyAssignmentOperator()) { 2241 return Sema::CXXCopyAssignment; 2242 } else if (MD->isMoveAssignmentOperator()) { 2243 return Sema::CXXMoveAssignment; 2244 } 2245 2246 return Sema::CXXInvalid; 2247 } 2248 2249 /// canRedefineFunction - checks if a function can be redefined. Currently, 2250 /// only extern inline functions can be redefined, and even then only in 2251 /// GNU89 mode. 2252 static bool canRedefineFunction(const FunctionDecl *FD, 2253 const LangOptions& LangOpts) { 2254 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2255 !LangOpts.CPlusPlus && 2256 FD->isInlineSpecified() && 2257 FD->getStorageClass() == SC_Extern); 2258 } 2259 2260 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2261 const AttributedType *AT = T->getAs<AttributedType>(); 2262 while (AT && !AT->isCallingConv()) 2263 AT = AT->getModifiedType()->getAs<AttributedType>(); 2264 return AT; 2265 } 2266 2267 template <typename T> 2268 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2269 const DeclContext *DC = Old->getDeclContext(); 2270 if (DC->isRecord()) 2271 return false; 2272 2273 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2274 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2275 return true; 2276 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2277 return true; 2278 return false; 2279 } 2280 2281 /// MergeFunctionDecl - We just parsed a function 'New' from 2282 /// declarator D which has the same name and scope as a previous 2283 /// declaration 'Old'. Figure out how to resolve this situation, 2284 /// merging decls or emitting diagnostics as appropriate. 2285 /// 2286 /// In C++, New and Old must be declarations that are not 2287 /// overloaded. Use IsOverload to determine whether New and Old are 2288 /// overloaded, and to select the Old declaration that New should be 2289 /// merged with. 2290 /// 2291 /// Returns true if there was an error, false otherwise. 2292 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S, 2293 bool MergeTypeWithOld) { 2294 // Verify the old decl was also a function. 2295 FunctionDecl *Old = 0; 2296 if (FunctionTemplateDecl *OldFunctionTemplate 2297 = dyn_cast<FunctionTemplateDecl>(OldD)) 2298 Old = OldFunctionTemplate->getTemplatedDecl(); 2299 else 2300 Old = dyn_cast<FunctionDecl>(OldD); 2301 if (!Old) { 2302 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2303 if (New->getFriendObjectKind()) { 2304 Diag(New->getLocation(), diag::err_using_decl_friend); 2305 Diag(Shadow->getTargetDecl()->getLocation(), 2306 diag::note_using_decl_target); 2307 Diag(Shadow->getUsingDecl()->getLocation(), 2308 diag::note_using_decl) << 0; 2309 return true; 2310 } 2311 2312 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2313 Diag(Shadow->getTargetDecl()->getLocation(), 2314 diag::note_using_decl_target); 2315 Diag(Shadow->getUsingDecl()->getLocation(), 2316 diag::note_using_decl) << 0; 2317 return true; 2318 } 2319 2320 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2321 << New->getDeclName(); 2322 Diag(OldD->getLocation(), diag::note_previous_definition); 2323 return true; 2324 } 2325 2326 // If the old declaration is invalid, just give up here. 2327 if (Old->isInvalidDecl()) 2328 return true; 2329 2330 // Determine whether the previous declaration was a definition, 2331 // implicit declaration, or a declaration. 2332 diag::kind PrevDiag; 2333 if (Old->isThisDeclarationADefinition()) 2334 PrevDiag = diag::note_previous_definition; 2335 else if (Old->isImplicit()) 2336 PrevDiag = diag::note_previous_implicit_declaration; 2337 else 2338 PrevDiag = diag::note_previous_declaration; 2339 2340 // Don't complain about this if we're in GNU89 mode and the old function 2341 // is an extern inline function. 2342 // Don't complain about specializations. They are not supposed to have 2343 // storage classes. 2344 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2345 New->getStorageClass() == SC_Static && 2346 Old->hasExternalFormalLinkage() && 2347 !New->getTemplateSpecializationInfo() && 2348 !canRedefineFunction(Old, getLangOpts())) { 2349 if (getLangOpts().MicrosoftExt) { 2350 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2351 Diag(Old->getLocation(), PrevDiag); 2352 } else { 2353 Diag(New->getLocation(), diag::err_static_non_static) << New; 2354 Diag(Old->getLocation(), PrevDiag); 2355 return true; 2356 } 2357 } 2358 2359 2360 // If a function is first declared with a calling convention, but is later 2361 // declared or defined without one, all following decls assume the calling 2362 // convention of the first. 2363 // 2364 // It's OK if a function is first declared without a calling convention, 2365 // but is later declared or defined with the default calling convention. 2366 // 2367 // To test if either decl has an explicit calling convention, we look for 2368 // AttributedType sugar nodes on the type as written. If they are missing or 2369 // were canonicalized away, we assume the calling convention was implicit. 2370 // 2371 // Note also that we DO NOT return at this point, because we still have 2372 // other tests to run. 2373 QualType OldQType = Context.getCanonicalType(Old->getType()); 2374 QualType NewQType = Context.getCanonicalType(New->getType()); 2375 const FunctionType *OldType = cast<FunctionType>(OldQType); 2376 const FunctionType *NewType = cast<FunctionType>(NewQType); 2377 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2378 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2379 bool RequiresAdjustment = false; 2380 2381 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2382 FunctionDecl *First = Old->getFirstDecl(); 2383 const FunctionType *FT = 2384 First->getType().getCanonicalType()->castAs<FunctionType>(); 2385 FunctionType::ExtInfo FI = FT->getExtInfo(); 2386 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2387 if (!NewCCExplicit) { 2388 // Inherit the CC from the previous declaration if it was specified 2389 // there but not here. 2390 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2391 RequiresAdjustment = true; 2392 } else { 2393 // Calling conventions aren't compatible, so complain. 2394 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2395 Diag(New->getLocation(), diag::err_cconv_change) 2396 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2397 << !FirstCCExplicit 2398 << (!FirstCCExplicit ? "" : 2399 FunctionType::getNameForCallConv(FI.getCC())); 2400 2401 // Put the note on the first decl, since it is the one that matters. 2402 Diag(First->getLocation(), diag::note_previous_declaration); 2403 return true; 2404 } 2405 } 2406 2407 // FIXME: diagnose the other way around? 2408 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2409 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2410 RequiresAdjustment = true; 2411 } 2412 2413 // Merge regparm attribute. 2414 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2415 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2416 if (NewTypeInfo.getHasRegParm()) { 2417 Diag(New->getLocation(), diag::err_regparm_mismatch) 2418 << NewType->getRegParmType() 2419 << OldType->getRegParmType(); 2420 Diag(Old->getLocation(), diag::note_previous_declaration); 2421 return true; 2422 } 2423 2424 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2425 RequiresAdjustment = true; 2426 } 2427 2428 // Merge ns_returns_retained attribute. 2429 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2430 if (NewTypeInfo.getProducesResult()) { 2431 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2432 Diag(Old->getLocation(), diag::note_previous_declaration); 2433 return true; 2434 } 2435 2436 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2437 RequiresAdjustment = true; 2438 } 2439 2440 if (RequiresAdjustment) { 2441 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2442 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2443 New->setType(QualType(AdjustedType, 0)); 2444 NewQType = Context.getCanonicalType(New->getType()); 2445 NewType = cast<FunctionType>(NewQType); 2446 } 2447 2448 // If this redeclaration makes the function inline, we may need to add it to 2449 // UndefinedButUsed. 2450 if (!Old->isInlined() && New->isInlined() && 2451 !New->hasAttr<GNUInlineAttr>() && 2452 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2453 Old->isUsed(false) && 2454 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2455 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2456 SourceLocation())); 2457 2458 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2459 // about it. 2460 if (New->hasAttr<GNUInlineAttr>() && 2461 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2462 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2463 } 2464 2465 if (getLangOpts().CPlusPlus) { 2466 // (C++98 13.1p2): 2467 // Certain function declarations cannot be overloaded: 2468 // -- Function declarations that differ only in the return type 2469 // cannot be overloaded. 2470 2471 // Go back to the type source info to compare the declared return types, 2472 // per C++1y [dcl.type.auto]p13: 2473 // Redeclarations or specializations of a function or function template 2474 // with a declared return type that uses a placeholder type shall also 2475 // use that placeholder, not a deduced type. 2476 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo() 2477 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2478 : OldType)->getResultType(); 2479 QualType NewDeclaredReturnType = (New->getTypeSourceInfo() 2480 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2481 : NewType)->getResultType(); 2482 QualType ResQT; 2483 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2484 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2485 New->isLocalExternDecl())) { 2486 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2487 OldDeclaredReturnType->isObjCObjectPointerType()) 2488 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2489 if (ResQT.isNull()) { 2490 if (New->isCXXClassMember() && New->isOutOfLine()) 2491 Diag(New->getLocation(), 2492 diag::err_member_def_does_not_match_ret_type) << New; 2493 else 2494 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2495 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2496 return true; 2497 } 2498 else 2499 NewQType = ResQT; 2500 } 2501 2502 QualType OldReturnType = OldType->getResultType(); 2503 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2504 if (OldReturnType != NewReturnType) { 2505 // If this function has a deduced return type and has already been 2506 // defined, copy the deduced value from the old declaration. 2507 AutoType *OldAT = Old->getResultType()->getContainedAutoType(); 2508 if (OldAT && OldAT->isDeduced()) { 2509 New->setType( 2510 SubstAutoType(New->getType(), 2511 OldAT->isDependentType() ? Context.DependentTy 2512 : OldAT->getDeducedType())); 2513 NewQType = Context.getCanonicalType( 2514 SubstAutoType(NewQType, 2515 OldAT->isDependentType() ? Context.DependentTy 2516 : OldAT->getDeducedType())); 2517 } 2518 } 2519 2520 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2521 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2522 if (OldMethod && NewMethod) { 2523 // Preserve triviality. 2524 NewMethod->setTrivial(OldMethod->isTrivial()); 2525 2526 // MSVC allows explicit template specialization at class scope: 2527 // 2 CXMethodDecls referring to the same function will be injected. 2528 // We don't want a redeclartion error. 2529 bool IsClassScopeExplicitSpecialization = 2530 OldMethod->isFunctionTemplateSpecialization() && 2531 NewMethod->isFunctionTemplateSpecialization(); 2532 bool isFriend = NewMethod->getFriendObjectKind(); 2533 2534 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2535 !IsClassScopeExplicitSpecialization) { 2536 // -- Member function declarations with the same name and the 2537 // same parameter types cannot be overloaded if any of them 2538 // is a static member function declaration. 2539 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2540 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2541 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2542 return true; 2543 } 2544 2545 // C++ [class.mem]p1: 2546 // [...] A member shall not be declared twice in the 2547 // member-specification, except that a nested class or member 2548 // class template can be declared and then later defined. 2549 if (ActiveTemplateInstantiations.empty()) { 2550 unsigned NewDiag; 2551 if (isa<CXXConstructorDecl>(OldMethod)) 2552 NewDiag = diag::err_constructor_redeclared; 2553 else if (isa<CXXDestructorDecl>(NewMethod)) 2554 NewDiag = diag::err_destructor_redeclared; 2555 else if (isa<CXXConversionDecl>(NewMethod)) 2556 NewDiag = diag::err_conv_function_redeclared; 2557 else 2558 NewDiag = diag::err_member_redeclared; 2559 2560 Diag(New->getLocation(), NewDiag); 2561 } else { 2562 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2563 << New << New->getType(); 2564 } 2565 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2566 2567 // Complain if this is an explicit declaration of a special 2568 // member that was initially declared implicitly. 2569 // 2570 // As an exception, it's okay to befriend such methods in order 2571 // to permit the implicit constructor/destructor/operator calls. 2572 } else if (OldMethod->isImplicit()) { 2573 if (isFriend) { 2574 NewMethod->setImplicit(); 2575 } else { 2576 Diag(NewMethod->getLocation(), 2577 diag::err_definition_of_implicitly_declared_member) 2578 << New << getSpecialMember(OldMethod); 2579 return true; 2580 } 2581 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2582 Diag(NewMethod->getLocation(), 2583 diag::err_definition_of_explicitly_defaulted_member) 2584 << getSpecialMember(OldMethod); 2585 return true; 2586 } 2587 } 2588 2589 // C++11 [dcl.attr.noreturn]p1: 2590 // The first declaration of a function shall specify the noreturn 2591 // attribute if any declaration of that function specifies the noreturn 2592 // attribute. 2593 if (New->hasAttr<CXX11NoReturnAttr>() && 2594 !Old->hasAttr<CXX11NoReturnAttr>()) { 2595 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(), 2596 diag::err_noreturn_missing_on_first_decl); 2597 Diag(Old->getFirstDecl()->getLocation(), 2598 diag::note_noreturn_missing_first_decl); 2599 } 2600 2601 // C++11 [dcl.attr.depend]p2: 2602 // The first declaration of a function shall specify the 2603 // carries_dependency attribute for its declarator-id if any declaration 2604 // of the function specifies the carries_dependency attribute. 2605 if (New->hasAttr<CarriesDependencyAttr>() && 2606 !Old->hasAttr<CarriesDependencyAttr>()) { 2607 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(), 2608 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2609 Diag(Old->getFirstDecl()->getLocation(), 2610 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2611 } 2612 2613 // (C++98 8.3.5p3): 2614 // All declarations for a function shall agree exactly in both the 2615 // return type and the parameter-type-list. 2616 // We also want to respect all the extended bits except noreturn. 2617 2618 // noreturn should now match unless the old type info didn't have it. 2619 QualType OldQTypeForComparison = OldQType; 2620 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2621 assert(OldQType == QualType(OldType, 0)); 2622 const FunctionType *OldTypeForComparison 2623 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2624 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2625 assert(OldQTypeForComparison.isCanonical()); 2626 } 2627 2628 if (haveIncompatibleLanguageLinkages(Old, New)) { 2629 // As a special case, retain the language linkage from previous 2630 // declarations of a friend function as an extension. 2631 // 2632 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2633 // and is useful because there's otherwise no way to specify language 2634 // linkage within class scope. 2635 // 2636 // Check cautiously as the friend object kind isn't yet complete. 2637 if (New->getFriendObjectKind() != Decl::FOK_None) { 2638 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2639 Diag(Old->getLocation(), PrevDiag); 2640 } else { 2641 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2642 Diag(Old->getLocation(), PrevDiag); 2643 return true; 2644 } 2645 } 2646 2647 if (OldQTypeForComparison == NewQType) 2648 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2649 2650 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2651 New->isLocalExternDecl()) { 2652 // It's OK if we couldn't merge types for a local function declaraton 2653 // if either the old or new type is dependent. We'll merge the types 2654 // when we instantiate the function. 2655 return false; 2656 } 2657 2658 // Fall through for conflicting redeclarations and redefinitions. 2659 } 2660 2661 // C: Function types need to be compatible, not identical. This handles 2662 // duplicate function decls like "void f(int); void f(enum X);" properly. 2663 if (!getLangOpts().CPlusPlus && 2664 Context.typesAreCompatible(OldQType, NewQType)) { 2665 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2666 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2667 const FunctionProtoType *OldProto = 0; 2668 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2669 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2670 // The old declaration provided a function prototype, but the 2671 // new declaration does not. Merge in the prototype. 2672 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2673 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2674 OldProto->arg_type_end()); 2675 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2676 ParamTypes, 2677 OldProto->getExtProtoInfo()); 2678 New->setType(NewQType); 2679 New->setHasInheritedPrototype(); 2680 2681 // Synthesize a parameter for each argument type. 2682 SmallVector<ParmVarDecl*, 16> Params; 2683 for (FunctionProtoType::arg_type_iterator 2684 ParamType = OldProto->arg_type_begin(), 2685 ParamEnd = OldProto->arg_type_end(); 2686 ParamType != ParamEnd; ++ParamType) { 2687 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2688 SourceLocation(), 2689 SourceLocation(), 0, 2690 *ParamType, /*TInfo=*/0, 2691 SC_None, 2692 0); 2693 Param->setScopeInfo(0, Params.size()); 2694 Param->setImplicit(); 2695 Params.push_back(Param); 2696 } 2697 2698 New->setParams(Params); 2699 } 2700 2701 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2702 } 2703 2704 // GNU C permits a K&R definition to follow a prototype declaration 2705 // if the declared types of the parameters in the K&R definition 2706 // match the types in the prototype declaration, even when the 2707 // promoted types of the parameters from the K&R definition differ 2708 // from the types in the prototype. GCC then keeps the types from 2709 // the prototype. 2710 // 2711 // If a variadic prototype is followed by a non-variadic K&R definition, 2712 // the K&R definition becomes variadic. This is sort of an edge case, but 2713 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2714 // C99 6.9.1p8. 2715 if (!getLangOpts().CPlusPlus && 2716 Old->hasPrototype() && !New->hasPrototype() && 2717 New->getType()->getAs<FunctionProtoType>() && 2718 Old->getNumParams() == New->getNumParams()) { 2719 SmallVector<QualType, 16> ArgTypes; 2720 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2721 const FunctionProtoType *OldProto 2722 = Old->getType()->getAs<FunctionProtoType>(); 2723 const FunctionProtoType *NewProto 2724 = New->getType()->getAs<FunctionProtoType>(); 2725 2726 // Determine whether this is the GNU C extension. 2727 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2728 NewProto->getResultType()); 2729 bool LooseCompatible = !MergedReturn.isNull(); 2730 for (unsigned Idx = 0, End = Old->getNumParams(); 2731 LooseCompatible && Idx != End; ++Idx) { 2732 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2733 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2734 if (Context.typesAreCompatible(OldParm->getType(), 2735 NewProto->getArgType(Idx))) { 2736 ArgTypes.push_back(NewParm->getType()); 2737 } else if (Context.typesAreCompatible(OldParm->getType(), 2738 NewParm->getType(), 2739 /*CompareUnqualified=*/true)) { 2740 GNUCompatibleParamWarning Warn 2741 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2742 Warnings.push_back(Warn); 2743 ArgTypes.push_back(NewParm->getType()); 2744 } else 2745 LooseCompatible = false; 2746 } 2747 2748 if (LooseCompatible) { 2749 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2750 Diag(Warnings[Warn].NewParm->getLocation(), 2751 diag::ext_param_promoted_not_compatible_with_prototype) 2752 << Warnings[Warn].PromotedType 2753 << Warnings[Warn].OldParm->getType(); 2754 if (Warnings[Warn].OldParm->getLocation().isValid()) 2755 Diag(Warnings[Warn].OldParm->getLocation(), 2756 diag::note_previous_declaration); 2757 } 2758 2759 if (MergeTypeWithOld) 2760 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2761 OldProto->getExtProtoInfo())); 2762 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2763 } 2764 2765 // Fall through to diagnose conflicting types. 2766 } 2767 2768 // A function that has already been declared has been redeclared or 2769 // defined with a different type; show an appropriate diagnostic. 2770 2771 // If the previous declaration was an implicitly-generated builtin 2772 // declaration, then at the very least we should use a specialized note. 2773 unsigned BuiltinID; 2774 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2775 // If it's actually a library-defined builtin function like 'malloc' 2776 // or 'printf', just warn about the incompatible redeclaration. 2777 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2778 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2779 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2780 << Old << Old->getType(); 2781 2782 // If this is a global redeclaration, just forget hereafter 2783 // about the "builtin-ness" of the function. 2784 // 2785 // Doing this for local extern declarations is problematic. If 2786 // the builtin declaration remains visible, a second invalid 2787 // local declaration will produce a hard error; if it doesn't 2788 // remain visible, a single bogus local redeclaration (which is 2789 // actually only a warning) could break all the downstream code. 2790 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2791 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2792 2793 return false; 2794 } 2795 2796 PrevDiag = diag::note_previous_builtin_declaration; 2797 } 2798 2799 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2800 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2801 return true; 2802 } 2803 2804 /// \brief Completes the merge of two function declarations that are 2805 /// known to be compatible. 2806 /// 2807 /// This routine handles the merging of attributes and other 2808 /// properties of function declarations from the old declaration to 2809 /// the new declaration, once we know that New is in fact a 2810 /// redeclaration of Old. 2811 /// 2812 /// \returns false 2813 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2814 Scope *S, bool MergeTypeWithOld) { 2815 // Merge the attributes 2816 mergeDeclAttributes(New, Old); 2817 2818 // Merge "pure" flag. 2819 if (Old->isPure()) 2820 New->setPure(); 2821 2822 // Merge "used" flag. 2823 if (Old->getMostRecentDecl()->isUsed(false)) 2824 New->setIsUsed(); 2825 2826 // Merge attributes from the parameters. These can mismatch with K&R 2827 // declarations. 2828 if (New->getNumParams() == Old->getNumParams()) 2829 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2830 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2831 *this); 2832 2833 if (getLangOpts().CPlusPlus) 2834 return MergeCXXFunctionDecl(New, Old, S); 2835 2836 // Merge the function types so the we get the composite types for the return 2837 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2838 // was visible. 2839 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2840 if (!Merged.isNull() && MergeTypeWithOld) 2841 New->setType(Merged); 2842 2843 return false; 2844 } 2845 2846 2847 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2848 ObjCMethodDecl *oldMethod) { 2849 2850 // Merge the attributes, including deprecated/unavailable 2851 AvailabilityMergeKind MergeKind = 2852 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2853 : AMK_Override; 2854 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2855 2856 // Merge attributes from the parameters. 2857 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2858 oe = oldMethod->param_end(); 2859 for (ObjCMethodDecl::param_iterator 2860 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2861 ni != ne && oi != oe; ++ni, ++oi) 2862 mergeParamDeclAttributes(*ni, *oi, *this); 2863 2864 CheckObjCMethodOverride(newMethod, oldMethod); 2865 } 2866 2867 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2868 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2869 /// emitting diagnostics as appropriate. 2870 /// 2871 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2872 /// to here in AddInitializerToDecl. We can't check them before the initializer 2873 /// is attached. 2874 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2875 bool MergeTypeWithOld) { 2876 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2877 return; 2878 2879 QualType MergedT; 2880 if (getLangOpts().CPlusPlus) { 2881 if (New->getType()->isUndeducedType()) { 2882 // We don't know what the new type is until the initializer is attached. 2883 return; 2884 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2885 // These could still be something that needs exception specs checked. 2886 return MergeVarDeclExceptionSpecs(New, Old); 2887 } 2888 // C++ [basic.link]p10: 2889 // [...] the types specified by all declarations referring to a given 2890 // object or function shall be identical, except that declarations for an 2891 // array object can specify array types that differ by the presence or 2892 // absence of a major array bound (8.3.4). 2893 else if (Old->getType()->isIncompleteArrayType() && 2894 New->getType()->isArrayType()) { 2895 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2896 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2897 if (Context.hasSameType(OldArray->getElementType(), 2898 NewArray->getElementType())) 2899 MergedT = New->getType(); 2900 } else if (Old->getType()->isArrayType() && 2901 New->getType()->isIncompleteArrayType()) { 2902 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2903 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2904 if (Context.hasSameType(OldArray->getElementType(), 2905 NewArray->getElementType())) 2906 MergedT = Old->getType(); 2907 } else if (New->getType()->isObjCObjectPointerType() && 2908 Old->getType()->isObjCObjectPointerType()) { 2909 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2910 Old->getType()); 2911 } 2912 } else { 2913 // C 6.2.7p2: 2914 // All declarations that refer to the same object or function shall have 2915 // compatible type. 2916 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2917 } 2918 if (MergedT.isNull()) { 2919 // It's OK if we couldn't merge types if either type is dependent, for a 2920 // block-scope variable. In other cases (static data members of class 2921 // templates, variable templates, ...), we require the types to be 2922 // equivalent. 2923 // FIXME: The C++ standard doesn't say anything about this. 2924 if ((New->getType()->isDependentType() || 2925 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2926 // If the old type was dependent, we can't merge with it, so the new type 2927 // becomes dependent for now. We'll reproduce the original type when we 2928 // instantiate the TypeSourceInfo for the variable. 2929 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2930 New->setType(Context.DependentTy); 2931 return; 2932 } 2933 2934 // FIXME: Even if this merging succeeds, some other non-visible declaration 2935 // of this variable might have an incompatible type. For instance: 2936 // 2937 // extern int arr[]; 2938 // void f() { extern int arr[2]; } 2939 // void g() { extern int arr[3]; } 2940 // 2941 // Neither C nor C++ requires a diagnostic for this, but we should still try 2942 // to diagnose it. 2943 Diag(New->getLocation(), diag::err_redefinition_different_type) 2944 << New->getDeclName() << New->getType() << Old->getType(); 2945 Diag(Old->getLocation(), diag::note_previous_definition); 2946 return New->setInvalidDecl(); 2947 } 2948 2949 // Don't actually update the type on the new declaration if the old 2950 // declaration was an extern declaration in a different scope. 2951 if (MergeTypeWithOld) 2952 New->setType(MergedT); 2953 } 2954 2955 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2956 LookupResult &Previous) { 2957 // C11 6.2.7p4: 2958 // For an identifier with internal or external linkage declared 2959 // in a scope in which a prior declaration of that identifier is 2960 // visible, if the prior declaration specifies internal or 2961 // external linkage, the type of the identifier at the later 2962 // declaration becomes the composite type. 2963 // 2964 // If the variable isn't visible, we do not merge with its type. 2965 if (Previous.isShadowed()) 2966 return false; 2967 2968 if (S.getLangOpts().CPlusPlus) { 2969 // C++11 [dcl.array]p3: 2970 // If there is a preceding declaration of the entity in the same 2971 // scope in which the bound was specified, an omitted array bound 2972 // is taken to be the same as in that earlier declaration. 2973 return NewVD->isPreviousDeclInSameBlockScope() || 2974 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2975 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2976 } else { 2977 // If the old declaration was function-local, don't merge with its 2978 // type unless we're in the same function. 2979 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2980 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2981 } 2982 } 2983 2984 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2985 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2986 /// situation, merging decls or emitting diagnostics as appropriate. 2987 /// 2988 /// Tentative definition rules (C99 6.9.2p2) are checked by 2989 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2990 /// definitions here, since the initializer hasn't been attached. 2991 /// 2992 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2993 // If the new decl is already invalid, don't do any other checking. 2994 if (New->isInvalidDecl()) 2995 return; 2996 2997 // Verify the old decl was also a variable or variable template. 2998 VarDecl *Old = 0; 2999 if (Previous.isSingleResult() && 3000 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 3001 if (New->getDescribedVarTemplate()) 3002 Old = Old->getDescribedVarTemplate() ? Old : 0; 3003 else 3004 Old = Old->getDescribedVarTemplate() ? 0 : Old; 3005 } 3006 if (!Old) { 3007 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3008 << New->getDeclName(); 3009 Diag(Previous.getRepresentativeDecl()->getLocation(), 3010 diag::note_previous_definition); 3011 return New->setInvalidDecl(); 3012 } 3013 3014 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3015 return; 3016 3017 // C++ [class.mem]p1: 3018 // A member shall not be declared twice in the member-specification [...] 3019 // 3020 // Here, we need only consider static data members. 3021 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3022 Diag(New->getLocation(), diag::err_duplicate_member) 3023 << New->getIdentifier(); 3024 Diag(Old->getLocation(), diag::note_previous_declaration); 3025 New->setInvalidDecl(); 3026 } 3027 3028 mergeDeclAttributes(New, Old); 3029 // Warn if an already-declared variable is made a weak_import in a subsequent 3030 // declaration 3031 if (New->getAttr<WeakImportAttr>() && 3032 Old->getStorageClass() == SC_None && 3033 !Old->getAttr<WeakImportAttr>()) { 3034 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3035 Diag(Old->getLocation(), diag::note_previous_definition); 3036 // Remove weak_import attribute on new declaration. 3037 New->dropAttr<WeakImportAttr>(); 3038 } 3039 3040 // Merge the types. 3041 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3042 3043 if (New->isInvalidDecl()) 3044 return; 3045 3046 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3047 if (New->getStorageClass() == SC_Static && 3048 !New->isStaticDataMember() && 3049 Old->hasExternalFormalLinkage()) { 3050 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3051 Diag(Old->getLocation(), diag::note_previous_definition); 3052 return New->setInvalidDecl(); 3053 } 3054 // C99 6.2.2p4: 3055 // For an identifier declared with the storage-class specifier 3056 // extern in a scope in which a prior declaration of that 3057 // identifier is visible,23) if the prior declaration specifies 3058 // internal or external linkage, the linkage of the identifier at 3059 // the later declaration is the same as the linkage specified at 3060 // the prior declaration. If no prior declaration is visible, or 3061 // if the prior declaration specifies no linkage, then the 3062 // identifier has external linkage. 3063 if (New->hasExternalStorage() && Old->hasLinkage()) 3064 /* Okay */; 3065 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3066 !New->isStaticDataMember() && 3067 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3068 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3069 Diag(Old->getLocation(), diag::note_previous_definition); 3070 return New->setInvalidDecl(); 3071 } 3072 3073 // Check if extern is followed by non-extern and vice-versa. 3074 if (New->hasExternalStorage() && 3075 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3076 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3077 Diag(Old->getLocation(), diag::note_previous_definition); 3078 return New->setInvalidDecl(); 3079 } 3080 if (Old->hasLinkage() && New->isLocalVarDecl() && 3081 !New->hasExternalStorage()) { 3082 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3083 Diag(Old->getLocation(), diag::note_previous_definition); 3084 return New->setInvalidDecl(); 3085 } 3086 3087 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3088 3089 // FIXME: The test for external storage here seems wrong? We still 3090 // need to check for mismatches. 3091 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3092 // Don't complain about out-of-line definitions of static members. 3093 !(Old->getLexicalDeclContext()->isRecord() && 3094 !New->getLexicalDeclContext()->isRecord())) { 3095 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3096 Diag(Old->getLocation(), diag::note_previous_definition); 3097 return New->setInvalidDecl(); 3098 } 3099 3100 if (New->getTLSKind() != Old->getTLSKind()) { 3101 if (!Old->getTLSKind()) { 3102 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3103 Diag(Old->getLocation(), diag::note_previous_declaration); 3104 } else if (!New->getTLSKind()) { 3105 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3106 Diag(Old->getLocation(), diag::note_previous_declaration); 3107 } else { 3108 // Do not allow redeclaration to change the variable between requiring 3109 // static and dynamic initialization. 3110 // FIXME: GCC allows this, but uses the TLS keyword on the first 3111 // declaration to determine the kind. Do we need to be compatible here? 3112 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3113 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3114 Diag(Old->getLocation(), diag::note_previous_declaration); 3115 } 3116 } 3117 3118 // C++ doesn't have tentative definitions, so go right ahead and check here. 3119 const VarDecl *Def; 3120 if (getLangOpts().CPlusPlus && 3121 New->isThisDeclarationADefinition() == VarDecl::Definition && 3122 (Def = Old->getDefinition())) { 3123 Diag(New->getLocation(), diag::err_redefinition) << New; 3124 Diag(Def->getLocation(), diag::note_previous_definition); 3125 New->setInvalidDecl(); 3126 return; 3127 } 3128 3129 if (haveIncompatibleLanguageLinkages(Old, New)) { 3130 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3131 Diag(Old->getLocation(), diag::note_previous_definition); 3132 New->setInvalidDecl(); 3133 return; 3134 } 3135 3136 // Merge "used" flag. 3137 if (Old->getMostRecentDecl()->isUsed(false)) 3138 New->setIsUsed(); 3139 3140 // Keep a chain of previous declarations. 3141 New->setPreviousDecl(Old); 3142 3143 // Inherit access appropriately. 3144 New->setAccess(Old->getAccess()); 3145 3146 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) { 3147 if (New->isStaticDataMember() && New->isOutOfLine()) 3148 VTD->setAccess(New->getAccess()); 3149 } 3150 } 3151 3152 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3153 /// no declarator (e.g. "struct foo;") is parsed. 3154 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3155 DeclSpec &DS) { 3156 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3157 } 3158 3159 static void HandleTagNumbering(Sema &S, const TagDecl *Tag) { 3160 if (!S.Context.getLangOpts().CPlusPlus) 3161 return; 3162 3163 if (isa<CXXRecordDecl>(Tag->getParent())) { 3164 // If this tag is the direct child of a class, number it if 3165 // it is anonymous. 3166 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3167 return; 3168 MangleNumberingContext &MCtx = 3169 S.Context.getManglingNumberContext(Tag->getParent()); 3170 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag)); 3171 return; 3172 } 3173 3174 // If this tag isn't a direct child of a class, number it if it is local. 3175 Decl *ManglingContextDecl; 3176 if (MangleNumberingContext *MCtx = 3177 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3178 ManglingContextDecl)) { 3179 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag)); 3180 } 3181 } 3182 3183 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3184 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3185 /// parameters to cope with template friend declarations. 3186 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3187 DeclSpec &DS, 3188 MultiTemplateParamsArg TemplateParams, 3189 bool IsExplicitInstantiation) { 3190 Decl *TagD = 0; 3191 TagDecl *Tag = 0; 3192 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3193 DS.getTypeSpecType() == DeclSpec::TST_struct || 3194 DS.getTypeSpecType() == DeclSpec::TST_interface || 3195 DS.getTypeSpecType() == DeclSpec::TST_union || 3196 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3197 TagD = DS.getRepAsDecl(); 3198 3199 if (!TagD) // We probably had an error 3200 return 0; 3201 3202 // Note that the above type specs guarantee that the 3203 // type rep is a Decl, whereas in many of the others 3204 // it's a Type. 3205 if (isa<TagDecl>(TagD)) 3206 Tag = cast<TagDecl>(TagD); 3207 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3208 Tag = CTD->getTemplatedDecl(); 3209 } 3210 3211 if (Tag) { 3212 HandleTagNumbering(*this, Tag); 3213 Tag->setFreeStanding(); 3214 if (Tag->isInvalidDecl()) 3215 return Tag; 3216 } 3217 3218 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3219 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3220 // or incomplete types shall not be restrict-qualified." 3221 if (TypeQuals & DeclSpec::TQ_restrict) 3222 Diag(DS.getRestrictSpecLoc(), 3223 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3224 << DS.getSourceRange(); 3225 } 3226 3227 if (DS.isConstexprSpecified()) { 3228 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3229 // and definitions of functions and variables. 3230 if (Tag) 3231 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3232 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3233 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3234 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3235 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3236 else 3237 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3238 // Don't emit warnings after this error. 3239 return TagD; 3240 } 3241 3242 DiagnoseFunctionSpecifiers(DS); 3243 3244 if (DS.isFriendSpecified()) { 3245 // If we're dealing with a decl but not a TagDecl, assume that 3246 // whatever routines created it handled the friendship aspect. 3247 if (TagD && !Tag) 3248 return 0; 3249 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3250 } 3251 3252 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3253 bool IsExplicitSpecialization = 3254 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3255 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3256 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3257 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3258 // nested-name-specifier unless it is an explicit instantiation 3259 // or an explicit specialization. 3260 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3261 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3262 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3263 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3264 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3265 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3266 << SS.getRange(); 3267 return 0; 3268 } 3269 3270 // Track whether this decl-specifier declares anything. 3271 bool DeclaresAnything = true; 3272 3273 // Handle anonymous struct definitions. 3274 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3275 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3276 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3277 if (getLangOpts().CPlusPlus || 3278 Record->getDeclContext()->isRecord()) 3279 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 3280 3281 DeclaresAnything = false; 3282 } 3283 } 3284 3285 // Check for Microsoft C extension: anonymous struct member. 3286 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3287 CurContext->isRecord() && 3288 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3289 // Handle 2 kinds of anonymous struct: 3290 // struct STRUCT; 3291 // and 3292 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3293 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3294 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3295 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3296 DS.getRepAsType().get()->isStructureType())) { 3297 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3298 << DS.getSourceRange(); 3299 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3300 } 3301 } 3302 3303 // Skip all the checks below if we have a type error. 3304 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3305 (TagD && TagD->isInvalidDecl())) 3306 return TagD; 3307 3308 if (getLangOpts().CPlusPlus && 3309 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3310 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3311 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3312 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3313 DeclaresAnything = false; 3314 3315 if (!DS.isMissingDeclaratorOk()) { 3316 // Customize diagnostic for a typedef missing a name. 3317 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3318 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3319 << DS.getSourceRange(); 3320 else 3321 DeclaresAnything = false; 3322 } 3323 3324 if (DS.isModulePrivateSpecified() && 3325 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3326 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3327 << Tag->getTagKind() 3328 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3329 3330 ActOnDocumentableDecl(TagD); 3331 3332 // C 6.7/2: 3333 // A declaration [...] shall declare at least a declarator [...], a tag, 3334 // or the members of an enumeration. 3335 // C++ [dcl.dcl]p3: 3336 // [If there are no declarators], and except for the declaration of an 3337 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3338 // names into the program, or shall redeclare a name introduced by a 3339 // previous declaration. 3340 if (!DeclaresAnything) { 3341 // In C, we allow this as a (popular) extension / bug. Don't bother 3342 // producing further diagnostics for redundant qualifiers after this. 3343 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3344 return TagD; 3345 } 3346 3347 // C++ [dcl.stc]p1: 3348 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3349 // init-declarator-list of the declaration shall not be empty. 3350 // C++ [dcl.fct.spec]p1: 3351 // If a cv-qualifier appears in a decl-specifier-seq, the 3352 // init-declarator-list of the declaration shall not be empty. 3353 // 3354 // Spurious qualifiers here appear to be valid in C. 3355 unsigned DiagID = diag::warn_standalone_specifier; 3356 if (getLangOpts().CPlusPlus) 3357 DiagID = diag::ext_standalone_specifier; 3358 3359 // Note that a linkage-specification sets a storage class, but 3360 // 'extern "C" struct foo;' is actually valid and not theoretically 3361 // useless. 3362 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3363 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3364 Diag(DS.getStorageClassSpecLoc(), DiagID) 3365 << DeclSpec::getSpecifierName(SCS); 3366 3367 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3368 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3369 << DeclSpec::getSpecifierName(TSCS); 3370 if (DS.getTypeQualifiers()) { 3371 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3372 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3373 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3374 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3375 // Restrict is covered above. 3376 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3377 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3378 } 3379 3380 // Warn about ignored type attributes, for example: 3381 // __attribute__((aligned)) struct A; 3382 // Attributes should be placed after tag to apply to type declaration. 3383 if (!DS.getAttributes().empty()) { 3384 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3385 if (TypeSpecType == DeclSpec::TST_class || 3386 TypeSpecType == DeclSpec::TST_struct || 3387 TypeSpecType == DeclSpec::TST_interface || 3388 TypeSpecType == DeclSpec::TST_union || 3389 TypeSpecType == DeclSpec::TST_enum) { 3390 AttributeList* attrs = DS.getAttributes().getList(); 3391 while (attrs) { 3392 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3393 << attrs->getName() 3394 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3395 TypeSpecType == DeclSpec::TST_struct ? 1 : 3396 TypeSpecType == DeclSpec::TST_union ? 2 : 3397 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3398 attrs = attrs->getNext(); 3399 } 3400 } 3401 } 3402 3403 return TagD; 3404 } 3405 3406 /// We are trying to inject an anonymous member into the given scope; 3407 /// check if there's an existing declaration that can't be overloaded. 3408 /// 3409 /// \return true if this is a forbidden redeclaration 3410 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3411 Scope *S, 3412 DeclContext *Owner, 3413 DeclarationName Name, 3414 SourceLocation NameLoc, 3415 unsigned diagnostic) { 3416 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3417 Sema::ForRedeclaration); 3418 if (!SemaRef.LookupName(R, S)) return false; 3419 3420 if (R.getAsSingle<TagDecl>()) 3421 return false; 3422 3423 // Pick a representative declaration. 3424 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3425 assert(PrevDecl && "Expected a non-null Decl"); 3426 3427 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3428 return false; 3429 3430 SemaRef.Diag(NameLoc, diagnostic) << Name; 3431 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3432 3433 return true; 3434 } 3435 3436 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3437 /// anonymous struct or union AnonRecord into the owning context Owner 3438 /// and scope S. This routine will be invoked just after we realize 3439 /// that an unnamed union or struct is actually an anonymous union or 3440 /// struct, e.g., 3441 /// 3442 /// @code 3443 /// union { 3444 /// int i; 3445 /// float f; 3446 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3447 /// // f into the surrounding scope.x 3448 /// @endcode 3449 /// 3450 /// This routine is recursive, injecting the names of nested anonymous 3451 /// structs/unions into the owning context and scope as well. 3452 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3453 DeclContext *Owner, 3454 RecordDecl *AnonRecord, 3455 AccessSpecifier AS, 3456 SmallVectorImpl<NamedDecl *> &Chaining, 3457 bool MSAnonStruct) { 3458 unsigned diagKind 3459 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3460 : diag::err_anonymous_struct_member_redecl; 3461 3462 bool Invalid = false; 3463 3464 // Look every FieldDecl and IndirectFieldDecl with a name. 3465 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3466 DEnd = AnonRecord->decls_end(); 3467 D != DEnd; ++D) { 3468 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3469 cast<NamedDecl>(*D)->getDeclName()) { 3470 ValueDecl *VD = cast<ValueDecl>(*D); 3471 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3472 VD->getLocation(), diagKind)) { 3473 // C++ [class.union]p2: 3474 // The names of the members of an anonymous union shall be 3475 // distinct from the names of any other entity in the 3476 // scope in which the anonymous union is declared. 3477 Invalid = true; 3478 } else { 3479 // C++ [class.union]p2: 3480 // For the purpose of name lookup, after the anonymous union 3481 // definition, the members of the anonymous union are 3482 // considered to have been defined in the scope in which the 3483 // anonymous union is declared. 3484 unsigned OldChainingSize = Chaining.size(); 3485 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3486 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3487 PE = IF->chain_end(); PI != PE; ++PI) 3488 Chaining.push_back(*PI); 3489 else 3490 Chaining.push_back(VD); 3491 3492 assert(Chaining.size() >= 2); 3493 NamedDecl **NamedChain = 3494 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3495 for (unsigned i = 0; i < Chaining.size(); i++) 3496 NamedChain[i] = Chaining[i]; 3497 3498 IndirectFieldDecl* IndirectField = 3499 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3500 VD->getIdentifier(), VD->getType(), 3501 NamedChain, Chaining.size()); 3502 3503 IndirectField->setAccess(AS); 3504 IndirectField->setImplicit(); 3505 SemaRef.PushOnScopeChains(IndirectField, S); 3506 3507 // That includes picking up the appropriate access specifier. 3508 if (AS != AS_none) IndirectField->setAccess(AS); 3509 3510 Chaining.resize(OldChainingSize); 3511 } 3512 } 3513 } 3514 3515 return Invalid; 3516 } 3517 3518 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3519 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3520 /// illegal input values are mapped to SC_None. 3521 static StorageClass 3522 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3523 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3524 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3525 "Parser allowed 'typedef' as storage class VarDecl."); 3526 switch (StorageClassSpec) { 3527 case DeclSpec::SCS_unspecified: return SC_None; 3528 case DeclSpec::SCS_extern: 3529 if (DS.isExternInLinkageSpec()) 3530 return SC_None; 3531 return SC_Extern; 3532 case DeclSpec::SCS_static: return SC_Static; 3533 case DeclSpec::SCS_auto: return SC_Auto; 3534 case DeclSpec::SCS_register: return SC_Register; 3535 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3536 // Illegal SCSs map to None: error reporting is up to the caller. 3537 case DeclSpec::SCS_mutable: // Fall through. 3538 case DeclSpec::SCS_typedef: return SC_None; 3539 } 3540 llvm_unreachable("unknown storage class specifier"); 3541 } 3542 3543 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3544 /// anonymous structure or union. Anonymous unions are a C++ feature 3545 /// (C++ [class.union]) and a C11 feature; anonymous structures 3546 /// are a C11 feature and GNU C++ extension. 3547 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3548 AccessSpecifier AS, 3549 RecordDecl *Record) { 3550 DeclContext *Owner = Record->getDeclContext(); 3551 3552 // Diagnose whether this anonymous struct/union is an extension. 3553 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3554 Diag(Record->getLocation(), diag::ext_anonymous_union); 3555 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3556 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3557 else if (!Record->isUnion() && !getLangOpts().C11) 3558 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3559 3560 // C and C++ require different kinds of checks for anonymous 3561 // structs/unions. 3562 bool Invalid = false; 3563 if (getLangOpts().CPlusPlus) { 3564 const char* PrevSpec = 0; 3565 unsigned DiagID; 3566 if (Record->isUnion()) { 3567 // C++ [class.union]p6: 3568 // Anonymous unions declared in a named namespace or in the 3569 // global namespace shall be declared static. 3570 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3571 (isa<TranslationUnitDecl>(Owner) || 3572 (isa<NamespaceDecl>(Owner) && 3573 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3574 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3575 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3576 3577 // Recover by adding 'static'. 3578 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3579 PrevSpec, DiagID); 3580 } 3581 // C++ [class.union]p6: 3582 // A storage class is not allowed in a declaration of an 3583 // anonymous union in a class scope. 3584 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3585 isa<RecordDecl>(Owner)) { 3586 Diag(DS.getStorageClassSpecLoc(), 3587 diag::err_anonymous_union_with_storage_spec) 3588 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3589 3590 // Recover by removing the storage specifier. 3591 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3592 SourceLocation(), 3593 PrevSpec, DiagID); 3594 } 3595 } 3596 3597 // Ignore const/volatile/restrict qualifiers. 3598 if (DS.getTypeQualifiers()) { 3599 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3600 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3601 << Record->isUnion() << "const" 3602 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3603 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3604 Diag(DS.getVolatileSpecLoc(), 3605 diag::ext_anonymous_struct_union_qualified) 3606 << Record->isUnion() << "volatile" 3607 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3608 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3609 Diag(DS.getRestrictSpecLoc(), 3610 diag::ext_anonymous_struct_union_qualified) 3611 << Record->isUnion() << "restrict" 3612 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3613 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3614 Diag(DS.getAtomicSpecLoc(), 3615 diag::ext_anonymous_struct_union_qualified) 3616 << Record->isUnion() << "_Atomic" 3617 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3618 3619 DS.ClearTypeQualifiers(); 3620 } 3621 3622 // C++ [class.union]p2: 3623 // The member-specification of an anonymous union shall only 3624 // define non-static data members. [Note: nested types and 3625 // functions cannot be declared within an anonymous union. ] 3626 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3627 MemEnd = Record->decls_end(); 3628 Mem != MemEnd; ++Mem) { 3629 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3630 // C++ [class.union]p3: 3631 // An anonymous union shall not have private or protected 3632 // members (clause 11). 3633 assert(FD->getAccess() != AS_none); 3634 if (FD->getAccess() != AS_public) { 3635 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3636 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3637 Invalid = true; 3638 } 3639 3640 // C++ [class.union]p1 3641 // An object of a class with a non-trivial constructor, a non-trivial 3642 // copy constructor, a non-trivial destructor, or a non-trivial copy 3643 // assignment operator cannot be a member of a union, nor can an 3644 // array of such objects. 3645 if (CheckNontrivialField(FD)) 3646 Invalid = true; 3647 } else if ((*Mem)->isImplicit()) { 3648 // Any implicit members are fine. 3649 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3650 // This is a type that showed up in an 3651 // elaborated-type-specifier inside the anonymous struct or 3652 // union, but which actually declares a type outside of the 3653 // anonymous struct or union. It's okay. 3654 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3655 if (!MemRecord->isAnonymousStructOrUnion() && 3656 MemRecord->getDeclName()) { 3657 // Visual C++ allows type definition in anonymous struct or union. 3658 if (getLangOpts().MicrosoftExt) 3659 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3660 << (int)Record->isUnion(); 3661 else { 3662 // This is a nested type declaration. 3663 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3664 << (int)Record->isUnion(); 3665 Invalid = true; 3666 } 3667 } else { 3668 // This is an anonymous type definition within another anonymous type. 3669 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3670 // not part of standard C++. 3671 Diag(MemRecord->getLocation(), 3672 diag::ext_anonymous_record_with_anonymous_type) 3673 << (int)Record->isUnion(); 3674 } 3675 } else if (isa<AccessSpecDecl>(*Mem)) { 3676 // Any access specifier is fine. 3677 } else { 3678 // We have something that isn't a non-static data 3679 // member. Complain about it. 3680 unsigned DK = diag::err_anonymous_record_bad_member; 3681 if (isa<TypeDecl>(*Mem)) 3682 DK = diag::err_anonymous_record_with_type; 3683 else if (isa<FunctionDecl>(*Mem)) 3684 DK = diag::err_anonymous_record_with_function; 3685 else if (isa<VarDecl>(*Mem)) 3686 DK = diag::err_anonymous_record_with_static; 3687 3688 // Visual C++ allows type definition in anonymous struct or union. 3689 if (getLangOpts().MicrosoftExt && 3690 DK == diag::err_anonymous_record_with_type) 3691 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3692 << (int)Record->isUnion(); 3693 else { 3694 Diag((*Mem)->getLocation(), DK) 3695 << (int)Record->isUnion(); 3696 Invalid = true; 3697 } 3698 } 3699 } 3700 } 3701 3702 if (!Record->isUnion() && !Owner->isRecord()) { 3703 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3704 << (int)getLangOpts().CPlusPlus; 3705 Invalid = true; 3706 } 3707 3708 // Mock up a declarator. 3709 Declarator Dc(DS, Declarator::MemberContext); 3710 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3711 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3712 3713 // Create a declaration for this anonymous struct/union. 3714 NamedDecl *Anon = 0; 3715 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3716 Anon = FieldDecl::Create(Context, OwningClass, 3717 DS.getLocStart(), 3718 Record->getLocation(), 3719 /*IdentifierInfo=*/0, 3720 Context.getTypeDeclType(Record), 3721 TInfo, 3722 /*BitWidth=*/0, /*Mutable=*/false, 3723 /*InitStyle=*/ICIS_NoInit); 3724 Anon->setAccess(AS); 3725 if (getLangOpts().CPlusPlus) 3726 FieldCollector->Add(cast<FieldDecl>(Anon)); 3727 } else { 3728 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3729 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3730 if (SCSpec == DeclSpec::SCS_mutable) { 3731 // mutable can only appear on non-static class members, so it's always 3732 // an error here 3733 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3734 Invalid = true; 3735 SC = SC_None; 3736 } 3737 3738 Anon = VarDecl::Create(Context, Owner, 3739 DS.getLocStart(), 3740 Record->getLocation(), /*IdentifierInfo=*/0, 3741 Context.getTypeDeclType(Record), 3742 TInfo, SC); 3743 3744 // Default-initialize the implicit variable. This initialization will be 3745 // trivial in almost all cases, except if a union member has an in-class 3746 // initializer: 3747 // union { int n = 0; }; 3748 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3749 } 3750 Anon->setImplicit(); 3751 3752 // Add the anonymous struct/union object to the current 3753 // context. We'll be referencing this object when we refer to one of 3754 // its members. 3755 Owner->addDecl(Anon); 3756 3757 // Inject the members of the anonymous struct/union into the owning 3758 // context and into the identifier resolver chain for name lookup 3759 // purposes. 3760 SmallVector<NamedDecl*, 2> Chain; 3761 Chain.push_back(Anon); 3762 3763 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3764 Chain, false)) 3765 Invalid = true; 3766 3767 // Mark this as an anonymous struct/union type. Note that we do not 3768 // do this until after we have already checked and injected the 3769 // members of this anonymous struct/union type, because otherwise 3770 // the members could be injected twice: once by DeclContext when it 3771 // builds its lookup table, and once by 3772 // InjectAnonymousStructOrUnionMembers. 3773 Record->setAnonymousStructOrUnion(true); 3774 3775 if (Invalid) 3776 Anon->setInvalidDecl(); 3777 3778 return Anon; 3779 } 3780 3781 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3782 /// Microsoft C anonymous structure. 3783 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3784 /// Example: 3785 /// 3786 /// struct A { int a; }; 3787 /// struct B { struct A; int b; }; 3788 /// 3789 /// void foo() { 3790 /// B var; 3791 /// var.a = 3; 3792 /// } 3793 /// 3794 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3795 RecordDecl *Record) { 3796 3797 // If there is no Record, get the record via the typedef. 3798 if (!Record) 3799 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3800 3801 // Mock up a declarator. 3802 Declarator Dc(DS, Declarator::TypeNameContext); 3803 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3804 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3805 3806 // Create a declaration for this anonymous struct. 3807 NamedDecl* Anon = FieldDecl::Create(Context, 3808 cast<RecordDecl>(CurContext), 3809 DS.getLocStart(), 3810 DS.getLocStart(), 3811 /*IdentifierInfo=*/0, 3812 Context.getTypeDeclType(Record), 3813 TInfo, 3814 /*BitWidth=*/0, /*Mutable=*/false, 3815 /*InitStyle=*/ICIS_NoInit); 3816 Anon->setImplicit(); 3817 3818 // Add the anonymous struct object to the current context. 3819 CurContext->addDecl(Anon); 3820 3821 // Inject the members of the anonymous struct into the current 3822 // context and into the identifier resolver chain for name lookup 3823 // purposes. 3824 SmallVector<NamedDecl*, 2> Chain; 3825 Chain.push_back(Anon); 3826 3827 RecordDecl *RecordDef = Record->getDefinition(); 3828 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3829 RecordDef, AS_none, 3830 Chain, true)) 3831 Anon->setInvalidDecl(); 3832 3833 return Anon; 3834 } 3835 3836 /// GetNameForDeclarator - Determine the full declaration name for the 3837 /// given Declarator. 3838 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3839 return GetNameFromUnqualifiedId(D.getName()); 3840 } 3841 3842 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3843 DeclarationNameInfo 3844 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3845 DeclarationNameInfo NameInfo; 3846 NameInfo.setLoc(Name.StartLocation); 3847 3848 switch (Name.getKind()) { 3849 3850 case UnqualifiedId::IK_ImplicitSelfParam: 3851 case UnqualifiedId::IK_Identifier: 3852 NameInfo.setName(Name.Identifier); 3853 NameInfo.setLoc(Name.StartLocation); 3854 return NameInfo; 3855 3856 case UnqualifiedId::IK_OperatorFunctionId: 3857 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3858 Name.OperatorFunctionId.Operator)); 3859 NameInfo.setLoc(Name.StartLocation); 3860 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3861 = Name.OperatorFunctionId.SymbolLocations[0]; 3862 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3863 = Name.EndLocation.getRawEncoding(); 3864 return NameInfo; 3865 3866 case UnqualifiedId::IK_LiteralOperatorId: 3867 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3868 Name.Identifier)); 3869 NameInfo.setLoc(Name.StartLocation); 3870 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3871 return NameInfo; 3872 3873 case UnqualifiedId::IK_ConversionFunctionId: { 3874 TypeSourceInfo *TInfo; 3875 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3876 if (Ty.isNull()) 3877 return DeclarationNameInfo(); 3878 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3879 Context.getCanonicalType(Ty))); 3880 NameInfo.setLoc(Name.StartLocation); 3881 NameInfo.setNamedTypeInfo(TInfo); 3882 return NameInfo; 3883 } 3884 3885 case UnqualifiedId::IK_ConstructorName: { 3886 TypeSourceInfo *TInfo; 3887 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3888 if (Ty.isNull()) 3889 return DeclarationNameInfo(); 3890 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3891 Context.getCanonicalType(Ty))); 3892 NameInfo.setLoc(Name.StartLocation); 3893 NameInfo.setNamedTypeInfo(TInfo); 3894 return NameInfo; 3895 } 3896 3897 case UnqualifiedId::IK_ConstructorTemplateId: { 3898 // In well-formed code, we can only have a constructor 3899 // template-id that refers to the current context, so go there 3900 // to find the actual type being constructed. 3901 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3902 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3903 return DeclarationNameInfo(); 3904 3905 // Determine the type of the class being constructed. 3906 QualType CurClassType = Context.getTypeDeclType(CurClass); 3907 3908 // FIXME: Check two things: that the template-id names the same type as 3909 // CurClassType, and that the template-id does not occur when the name 3910 // was qualified. 3911 3912 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3913 Context.getCanonicalType(CurClassType))); 3914 NameInfo.setLoc(Name.StartLocation); 3915 // FIXME: should we retrieve TypeSourceInfo? 3916 NameInfo.setNamedTypeInfo(0); 3917 return NameInfo; 3918 } 3919 3920 case UnqualifiedId::IK_DestructorName: { 3921 TypeSourceInfo *TInfo; 3922 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3923 if (Ty.isNull()) 3924 return DeclarationNameInfo(); 3925 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3926 Context.getCanonicalType(Ty))); 3927 NameInfo.setLoc(Name.StartLocation); 3928 NameInfo.setNamedTypeInfo(TInfo); 3929 return NameInfo; 3930 } 3931 3932 case UnqualifiedId::IK_TemplateId: { 3933 TemplateName TName = Name.TemplateId->Template.get(); 3934 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3935 return Context.getNameForTemplate(TName, TNameLoc); 3936 } 3937 3938 } // switch (Name.getKind()) 3939 3940 llvm_unreachable("Unknown name kind"); 3941 } 3942 3943 static QualType getCoreType(QualType Ty) { 3944 do { 3945 if (Ty->isPointerType() || Ty->isReferenceType()) 3946 Ty = Ty->getPointeeType(); 3947 else if (Ty->isArrayType()) 3948 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3949 else 3950 return Ty.withoutLocalFastQualifiers(); 3951 } while (true); 3952 } 3953 3954 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3955 /// and Definition have "nearly" matching parameters. This heuristic is 3956 /// used to improve diagnostics in the case where an out-of-line function 3957 /// definition doesn't match any declaration within the class or namespace. 3958 /// Also sets Params to the list of indices to the parameters that differ 3959 /// between the declaration and the definition. If hasSimilarParameters 3960 /// returns true and Params is empty, then all of the parameters match. 3961 static bool hasSimilarParameters(ASTContext &Context, 3962 FunctionDecl *Declaration, 3963 FunctionDecl *Definition, 3964 SmallVectorImpl<unsigned> &Params) { 3965 Params.clear(); 3966 if (Declaration->param_size() != Definition->param_size()) 3967 return false; 3968 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3969 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3970 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3971 3972 // The parameter types are identical 3973 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3974 continue; 3975 3976 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3977 QualType DefParamBaseTy = getCoreType(DefParamTy); 3978 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3979 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3980 3981 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3982 (DeclTyName && DeclTyName == DefTyName)) 3983 Params.push_back(Idx); 3984 else // The two parameters aren't even close 3985 return false; 3986 } 3987 3988 return true; 3989 } 3990 3991 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3992 /// declarator needs to be rebuilt in the current instantiation. 3993 /// Any bits of declarator which appear before the name are valid for 3994 /// consideration here. That's specifically the type in the decl spec 3995 /// and the base type in any member-pointer chunks. 3996 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3997 DeclarationName Name) { 3998 // The types we specifically need to rebuild are: 3999 // - typenames, typeofs, and decltypes 4000 // - types which will become injected class names 4001 // Of course, we also need to rebuild any type referencing such a 4002 // type. It's safest to just say "dependent", but we call out a 4003 // few cases here. 4004 4005 DeclSpec &DS = D.getMutableDeclSpec(); 4006 switch (DS.getTypeSpecType()) { 4007 case DeclSpec::TST_typename: 4008 case DeclSpec::TST_typeofType: 4009 case DeclSpec::TST_underlyingType: 4010 case DeclSpec::TST_atomic: { 4011 // Grab the type from the parser. 4012 TypeSourceInfo *TSI = 0; 4013 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4014 if (T.isNull() || !T->isDependentType()) break; 4015 4016 // Make sure there's a type source info. This isn't really much 4017 // of a waste; most dependent types should have type source info 4018 // attached already. 4019 if (!TSI) 4020 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4021 4022 // Rebuild the type in the current instantiation. 4023 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4024 if (!TSI) return true; 4025 4026 // Store the new type back in the decl spec. 4027 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4028 DS.UpdateTypeRep(LocType); 4029 break; 4030 } 4031 4032 case DeclSpec::TST_decltype: 4033 case DeclSpec::TST_typeofExpr: { 4034 Expr *E = DS.getRepAsExpr(); 4035 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4036 if (Result.isInvalid()) return true; 4037 DS.UpdateExprRep(Result.get()); 4038 break; 4039 } 4040 4041 default: 4042 // Nothing to do for these decl specs. 4043 break; 4044 } 4045 4046 // It doesn't matter what order we do this in. 4047 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4048 DeclaratorChunk &Chunk = D.getTypeObject(I); 4049 4050 // The only type information in the declarator which can come 4051 // before the declaration name is the base type of a member 4052 // pointer. 4053 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4054 continue; 4055 4056 // Rebuild the scope specifier in-place. 4057 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4058 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4059 return true; 4060 } 4061 4062 return false; 4063 } 4064 4065 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4066 D.setFunctionDefinitionKind(FDK_Declaration); 4067 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4068 4069 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4070 Dcl && Dcl->getDeclContext()->isFileContext()) 4071 Dcl->setTopLevelDeclInObjCContainer(); 4072 4073 return Dcl; 4074 } 4075 4076 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4077 /// If T is the name of a class, then each of the following shall have a 4078 /// name different from T: 4079 /// - every static data member of class T; 4080 /// - every member function of class T 4081 /// - every member of class T that is itself a type; 4082 /// \returns true if the declaration name violates these rules. 4083 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4084 DeclarationNameInfo NameInfo) { 4085 DeclarationName Name = NameInfo.getName(); 4086 4087 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4088 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4089 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4090 return true; 4091 } 4092 4093 return false; 4094 } 4095 4096 /// \brief Diagnose a declaration whose declarator-id has the given 4097 /// nested-name-specifier. 4098 /// 4099 /// \param SS The nested-name-specifier of the declarator-id. 4100 /// 4101 /// \param DC The declaration context to which the nested-name-specifier 4102 /// resolves. 4103 /// 4104 /// \param Name The name of the entity being declared. 4105 /// 4106 /// \param Loc The location of the name of the entity being declared. 4107 /// 4108 /// \returns true if we cannot safely recover from this error, false otherwise. 4109 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4110 DeclarationName Name, 4111 SourceLocation Loc) { 4112 DeclContext *Cur = CurContext; 4113 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4114 Cur = Cur->getParent(); 4115 4116 // C++ [dcl.meaning]p1: 4117 // A declarator-id shall not be qualified except for the definition 4118 // of a member function (9.3) or static data member (9.4) outside of 4119 // its class, the definition or explicit instantiation of a function 4120 // or variable member of a namespace outside of its namespace, or the 4121 // definition of an explicit specialization outside of its namespace, 4122 // or the declaration of a friend function that is a member of 4123 // another class or namespace (11.3). [...] 4124 4125 // The user provided a superfluous scope specifier that refers back to the 4126 // class or namespaces in which the entity is already declared. 4127 // 4128 // class X { 4129 // void X::f(); 4130 // }; 4131 if (Cur->Equals(DC)) { 4132 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 4133 : diag::err_member_extra_qualification) 4134 << Name << FixItHint::CreateRemoval(SS.getRange()); 4135 SS.clear(); 4136 return false; 4137 } 4138 4139 // Check whether the qualifying scope encloses the scope of the original 4140 // declaration. 4141 if (!Cur->Encloses(DC)) { 4142 if (Cur->isRecord()) 4143 Diag(Loc, diag::err_member_qualification) 4144 << Name << SS.getRange(); 4145 else if (isa<TranslationUnitDecl>(DC)) 4146 Diag(Loc, diag::err_invalid_declarator_global_scope) 4147 << Name << SS.getRange(); 4148 else if (isa<FunctionDecl>(Cur)) 4149 Diag(Loc, diag::err_invalid_declarator_in_function) 4150 << Name << SS.getRange(); 4151 else if (isa<BlockDecl>(Cur)) 4152 Diag(Loc, diag::err_invalid_declarator_in_block) 4153 << Name << SS.getRange(); 4154 else 4155 Diag(Loc, diag::err_invalid_declarator_scope) 4156 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4157 4158 return true; 4159 } 4160 4161 if (Cur->isRecord()) { 4162 // Cannot qualify members within a class. 4163 Diag(Loc, diag::err_member_qualification) 4164 << Name << SS.getRange(); 4165 SS.clear(); 4166 4167 // C++ constructors and destructors with incorrect scopes can break 4168 // our AST invariants by having the wrong underlying types. If 4169 // that's the case, then drop this declaration entirely. 4170 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4171 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4172 !Context.hasSameType(Name.getCXXNameType(), 4173 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4174 return true; 4175 4176 return false; 4177 } 4178 4179 // C++11 [dcl.meaning]p1: 4180 // [...] "The nested-name-specifier of the qualified declarator-id shall 4181 // not begin with a decltype-specifer" 4182 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4183 while (SpecLoc.getPrefix()) 4184 SpecLoc = SpecLoc.getPrefix(); 4185 if (dyn_cast_or_null<DecltypeType>( 4186 SpecLoc.getNestedNameSpecifier()->getAsType())) 4187 Diag(Loc, diag::err_decltype_in_declarator) 4188 << SpecLoc.getTypeLoc().getSourceRange(); 4189 4190 return false; 4191 } 4192 4193 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4194 MultiTemplateParamsArg TemplateParamLists) { 4195 // TODO: consider using NameInfo for diagnostic. 4196 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4197 DeclarationName Name = NameInfo.getName(); 4198 4199 // All of these full declarators require an identifier. If it doesn't have 4200 // one, the ParsedFreeStandingDeclSpec action should be used. 4201 if (!Name) { 4202 if (!D.isInvalidType()) // Reject this if we think it is valid. 4203 Diag(D.getDeclSpec().getLocStart(), 4204 diag::err_declarator_need_ident) 4205 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4206 return 0; 4207 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4208 return 0; 4209 4210 // The scope passed in may not be a decl scope. Zip up the scope tree until 4211 // we find one that is. 4212 while ((S->getFlags() & Scope::DeclScope) == 0 || 4213 (S->getFlags() & Scope::TemplateParamScope) != 0) 4214 S = S->getParent(); 4215 4216 DeclContext *DC = CurContext; 4217 if (D.getCXXScopeSpec().isInvalid()) 4218 D.setInvalidType(); 4219 else if (D.getCXXScopeSpec().isSet()) { 4220 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4221 UPPC_DeclarationQualifier)) 4222 return 0; 4223 4224 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4225 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4226 if (!DC || isa<EnumDecl>(DC)) { 4227 // If we could not compute the declaration context, it's because the 4228 // declaration context is dependent but does not refer to a class, 4229 // class template, or class template partial specialization. Complain 4230 // and return early, to avoid the coming semantic disaster. 4231 Diag(D.getIdentifierLoc(), 4232 diag::err_template_qualified_declarator_no_match) 4233 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 4234 << D.getCXXScopeSpec().getRange(); 4235 return 0; 4236 } 4237 bool IsDependentContext = DC->isDependentContext(); 4238 4239 if (!IsDependentContext && 4240 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4241 return 0; 4242 4243 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4244 Diag(D.getIdentifierLoc(), 4245 diag::err_member_def_undefined_record) 4246 << Name << DC << D.getCXXScopeSpec().getRange(); 4247 D.setInvalidType(); 4248 } else if (!D.getDeclSpec().isFriendSpecified()) { 4249 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4250 Name, D.getIdentifierLoc())) { 4251 if (DC->isRecord()) 4252 return 0; 4253 4254 D.setInvalidType(); 4255 } 4256 } 4257 4258 // Check whether we need to rebuild the type of the given 4259 // declaration in the current instantiation. 4260 if (EnteringContext && IsDependentContext && 4261 TemplateParamLists.size() != 0) { 4262 ContextRAII SavedContext(*this, DC); 4263 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4264 D.setInvalidType(); 4265 } 4266 } 4267 4268 if (DiagnoseClassNameShadow(DC, NameInfo)) 4269 // If this is a typedef, we'll end up spewing multiple diagnostics. 4270 // Just return early; it's safer. 4271 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4272 return 0; 4273 4274 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4275 QualType R = TInfo->getType(); 4276 4277 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4278 UPPC_DeclarationType)) 4279 D.setInvalidType(); 4280 4281 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4282 ForRedeclaration); 4283 4284 // See if this is a redefinition of a variable in the same scope. 4285 if (!D.getCXXScopeSpec().isSet()) { 4286 bool IsLinkageLookup = false; 4287 bool CreateBuiltins = false; 4288 4289 // If the declaration we're planning to build will be a function 4290 // or object with linkage, then look for another declaration with 4291 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4292 // 4293 // If the declaration we're planning to build will be declared with 4294 // external linkage in the translation unit, create any builtin with 4295 // the same name. 4296 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4297 /* Do nothing*/; 4298 else if (CurContext->isFunctionOrMethod() && 4299 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4300 R->isFunctionType())) { 4301 IsLinkageLookup = true; 4302 CreateBuiltins = 4303 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4304 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4305 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4306 CreateBuiltins = true; 4307 4308 if (IsLinkageLookup) 4309 Previous.clear(LookupRedeclarationWithLinkage); 4310 4311 LookupName(Previous, S, CreateBuiltins); 4312 } else { // Something like "int foo::x;" 4313 LookupQualifiedName(Previous, DC); 4314 4315 // C++ [dcl.meaning]p1: 4316 // When the declarator-id is qualified, the declaration shall refer to a 4317 // previously declared member of the class or namespace to which the 4318 // qualifier refers (or, in the case of a namespace, of an element of the 4319 // inline namespace set of that namespace (7.3.1)) or to a specialization 4320 // thereof; [...] 4321 // 4322 // Note that we already checked the context above, and that we do not have 4323 // enough information to make sure that Previous contains the declaration 4324 // we want to match. For example, given: 4325 // 4326 // class X { 4327 // void f(); 4328 // void f(float); 4329 // }; 4330 // 4331 // void X::f(int) { } // ill-formed 4332 // 4333 // In this case, Previous will point to the overload set 4334 // containing the two f's declared in X, but neither of them 4335 // matches. 4336 4337 // C++ [dcl.meaning]p1: 4338 // [...] the member shall not merely have been introduced by a 4339 // using-declaration in the scope of the class or namespace nominated by 4340 // the nested-name-specifier of the declarator-id. 4341 RemoveUsingDecls(Previous); 4342 } 4343 4344 if (Previous.isSingleResult() && 4345 Previous.getFoundDecl()->isTemplateParameter()) { 4346 // Maybe we will complain about the shadowed template parameter. 4347 if (!D.isInvalidType()) 4348 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4349 Previous.getFoundDecl()); 4350 4351 // Just pretend that we didn't see the previous declaration. 4352 Previous.clear(); 4353 } 4354 4355 // In C++, the previous declaration we find might be a tag type 4356 // (class or enum). In this case, the new declaration will hide the 4357 // tag type. Note that this does does not apply if we're declaring a 4358 // typedef (C++ [dcl.typedef]p4). 4359 if (Previous.isSingleTagDecl() && 4360 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4361 Previous.clear(); 4362 4363 // Check that there are no default arguments other than in the parameters 4364 // of a function declaration (C++ only). 4365 if (getLangOpts().CPlusPlus) 4366 CheckExtraCXXDefaultArguments(D); 4367 4368 NamedDecl *New; 4369 4370 bool AddToScope = true; 4371 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4372 if (TemplateParamLists.size()) { 4373 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4374 return 0; 4375 } 4376 4377 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4378 } else if (R->isFunctionType()) { 4379 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4380 TemplateParamLists, 4381 AddToScope); 4382 } else { 4383 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4384 AddToScope); 4385 } 4386 4387 if (New == 0) 4388 return 0; 4389 4390 // If this has an identifier and is not an invalid redeclaration or 4391 // function template specialization, add it to the scope stack. 4392 if (New->getDeclName() && AddToScope && 4393 !(D.isRedeclaration() && New->isInvalidDecl())) { 4394 // Only make a locally-scoped extern declaration visible if it is the first 4395 // declaration of this entity. Qualified lookup for such an entity should 4396 // only find this declaration if there is no visible declaration of it. 4397 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4398 PushOnScopeChains(New, S, AddToContext); 4399 if (!AddToContext) 4400 CurContext->addHiddenDecl(New); 4401 } 4402 4403 return New; 4404 } 4405 4406 /// Helper method to turn variable array types into constant array 4407 /// types in certain situations which would otherwise be errors (for 4408 /// GCC compatibility). 4409 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4410 ASTContext &Context, 4411 bool &SizeIsNegative, 4412 llvm::APSInt &Oversized) { 4413 // This method tries to turn a variable array into a constant 4414 // array even when the size isn't an ICE. This is necessary 4415 // for compatibility with code that depends on gcc's buggy 4416 // constant expression folding, like struct {char x[(int)(char*)2];} 4417 SizeIsNegative = false; 4418 Oversized = 0; 4419 4420 if (T->isDependentType()) 4421 return QualType(); 4422 4423 QualifierCollector Qs; 4424 const Type *Ty = Qs.strip(T); 4425 4426 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4427 QualType Pointee = PTy->getPointeeType(); 4428 QualType FixedType = 4429 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4430 Oversized); 4431 if (FixedType.isNull()) return FixedType; 4432 FixedType = Context.getPointerType(FixedType); 4433 return Qs.apply(Context, FixedType); 4434 } 4435 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4436 QualType Inner = PTy->getInnerType(); 4437 QualType FixedType = 4438 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4439 Oversized); 4440 if (FixedType.isNull()) return FixedType; 4441 FixedType = Context.getParenType(FixedType); 4442 return Qs.apply(Context, FixedType); 4443 } 4444 4445 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4446 if (!VLATy) 4447 return QualType(); 4448 // FIXME: We should probably handle this case 4449 if (VLATy->getElementType()->isVariablyModifiedType()) 4450 return QualType(); 4451 4452 llvm::APSInt Res; 4453 if (!VLATy->getSizeExpr() || 4454 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4455 return QualType(); 4456 4457 // Check whether the array size is negative. 4458 if (Res.isSigned() && Res.isNegative()) { 4459 SizeIsNegative = true; 4460 return QualType(); 4461 } 4462 4463 // Check whether the array is too large to be addressed. 4464 unsigned ActiveSizeBits 4465 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4466 Res); 4467 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4468 Oversized = Res; 4469 return QualType(); 4470 } 4471 4472 return Context.getConstantArrayType(VLATy->getElementType(), 4473 Res, ArrayType::Normal, 0); 4474 } 4475 4476 static void 4477 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4478 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4479 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4480 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4481 DstPTL.getPointeeLoc()); 4482 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4483 return; 4484 } 4485 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4486 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4487 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4488 DstPTL.getInnerLoc()); 4489 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4490 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4491 return; 4492 } 4493 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4494 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4495 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4496 TypeLoc DstElemTL = DstATL.getElementLoc(); 4497 DstElemTL.initializeFullCopy(SrcElemTL); 4498 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4499 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4500 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4501 } 4502 4503 /// Helper method to turn variable array types into constant array 4504 /// types in certain situations which would otherwise be errors (for 4505 /// GCC compatibility). 4506 static TypeSourceInfo* 4507 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4508 ASTContext &Context, 4509 bool &SizeIsNegative, 4510 llvm::APSInt &Oversized) { 4511 QualType FixedTy 4512 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4513 SizeIsNegative, Oversized); 4514 if (FixedTy.isNull()) 4515 return 0; 4516 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4517 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4518 FixedTInfo->getTypeLoc()); 4519 return FixedTInfo; 4520 } 4521 4522 /// \brief Register the given locally-scoped extern "C" declaration so 4523 /// that it can be found later for redeclarations. We include any extern "C" 4524 /// declaration that is not visible in the translation unit here, not just 4525 /// function-scope declarations. 4526 void 4527 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4528 if (!getLangOpts().CPlusPlus && 4529 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4530 // Don't need to track declarations in the TU in C. 4531 return; 4532 4533 // Note that we have a locally-scoped external with this name. 4534 // FIXME: There can be multiple such declarations if they are functions marked 4535 // __attribute__((overloadable)) declared in function scope in C. 4536 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4537 } 4538 4539 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4540 if (ExternalSource) { 4541 // Load locally-scoped external decls from the external source. 4542 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4543 SmallVector<NamedDecl *, 4> Decls; 4544 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4545 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4546 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4547 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4548 if (Pos == LocallyScopedExternCDecls.end()) 4549 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4550 } 4551 } 4552 4553 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4554 return D ? D->getMostRecentDecl() : 0; 4555 } 4556 4557 /// \brief Diagnose function specifiers on a declaration of an identifier that 4558 /// does not identify a function. 4559 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4560 // FIXME: We should probably indicate the identifier in question to avoid 4561 // confusion for constructs like "inline int a(), b;" 4562 if (DS.isInlineSpecified()) 4563 Diag(DS.getInlineSpecLoc(), 4564 diag::err_inline_non_function); 4565 4566 if (DS.isVirtualSpecified()) 4567 Diag(DS.getVirtualSpecLoc(), 4568 diag::err_virtual_non_function); 4569 4570 if (DS.isExplicitSpecified()) 4571 Diag(DS.getExplicitSpecLoc(), 4572 diag::err_explicit_non_function); 4573 4574 if (DS.isNoreturnSpecified()) 4575 Diag(DS.getNoreturnSpecLoc(), 4576 diag::err_noreturn_non_function); 4577 } 4578 4579 NamedDecl* 4580 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4581 TypeSourceInfo *TInfo, LookupResult &Previous) { 4582 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4583 if (D.getCXXScopeSpec().isSet()) { 4584 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4585 << D.getCXXScopeSpec().getRange(); 4586 D.setInvalidType(); 4587 // Pretend we didn't see the scope specifier. 4588 DC = CurContext; 4589 Previous.clear(); 4590 } 4591 4592 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4593 4594 if (D.getDeclSpec().isConstexprSpecified()) 4595 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4596 << 1; 4597 4598 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4599 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4600 << D.getName().getSourceRange(); 4601 return 0; 4602 } 4603 4604 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4605 if (!NewTD) return 0; 4606 4607 // Handle attributes prior to checking for duplicates in MergeVarDecl 4608 ProcessDeclAttributes(S, NewTD, D); 4609 4610 CheckTypedefForVariablyModifiedType(S, NewTD); 4611 4612 bool Redeclaration = D.isRedeclaration(); 4613 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4614 D.setRedeclaration(Redeclaration); 4615 return ND; 4616 } 4617 4618 void 4619 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4620 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4621 // then it shall have block scope. 4622 // Note that variably modified types must be fixed before merging the decl so 4623 // that redeclarations will match. 4624 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4625 QualType T = TInfo->getType(); 4626 if (T->isVariablyModifiedType()) { 4627 getCurFunction()->setHasBranchProtectedScope(); 4628 4629 if (S->getFnParent() == 0) { 4630 bool SizeIsNegative; 4631 llvm::APSInt Oversized; 4632 TypeSourceInfo *FixedTInfo = 4633 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4634 SizeIsNegative, 4635 Oversized); 4636 if (FixedTInfo) { 4637 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4638 NewTD->setTypeSourceInfo(FixedTInfo); 4639 } else { 4640 if (SizeIsNegative) 4641 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4642 else if (T->isVariableArrayType()) 4643 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4644 else if (Oversized.getBoolValue()) 4645 Diag(NewTD->getLocation(), diag::err_array_too_large) 4646 << Oversized.toString(10); 4647 else 4648 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4649 NewTD->setInvalidDecl(); 4650 } 4651 } 4652 } 4653 } 4654 4655 4656 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4657 /// declares a typedef-name, either using the 'typedef' type specifier or via 4658 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4659 NamedDecl* 4660 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4661 LookupResult &Previous, bool &Redeclaration) { 4662 // Merge the decl with the existing one if appropriate. If the decl is 4663 // in an outer scope, it isn't the same thing. 4664 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4665 /*ExplicitInstantiationOrSpecialization=*/false); 4666 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4667 if (!Previous.empty()) { 4668 Redeclaration = true; 4669 MergeTypedefNameDecl(NewTD, Previous); 4670 } 4671 4672 // If this is the C FILE type, notify the AST context. 4673 if (IdentifierInfo *II = NewTD->getIdentifier()) 4674 if (!NewTD->isInvalidDecl() && 4675 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4676 if (II->isStr("FILE")) 4677 Context.setFILEDecl(NewTD); 4678 else if (II->isStr("jmp_buf")) 4679 Context.setjmp_bufDecl(NewTD); 4680 else if (II->isStr("sigjmp_buf")) 4681 Context.setsigjmp_bufDecl(NewTD); 4682 else if (II->isStr("ucontext_t")) 4683 Context.setucontext_tDecl(NewTD); 4684 } 4685 4686 return NewTD; 4687 } 4688 4689 /// \brief Determines whether the given declaration is an out-of-scope 4690 /// previous declaration. 4691 /// 4692 /// This routine should be invoked when name lookup has found a 4693 /// previous declaration (PrevDecl) that is not in the scope where a 4694 /// new declaration by the same name is being introduced. If the new 4695 /// declaration occurs in a local scope, previous declarations with 4696 /// linkage may still be considered previous declarations (C99 4697 /// 6.2.2p4-5, C++ [basic.link]p6). 4698 /// 4699 /// \param PrevDecl the previous declaration found by name 4700 /// lookup 4701 /// 4702 /// \param DC the context in which the new declaration is being 4703 /// declared. 4704 /// 4705 /// \returns true if PrevDecl is an out-of-scope previous declaration 4706 /// for a new delcaration with the same name. 4707 static bool 4708 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4709 ASTContext &Context) { 4710 if (!PrevDecl) 4711 return false; 4712 4713 if (!PrevDecl->hasLinkage()) 4714 return false; 4715 4716 if (Context.getLangOpts().CPlusPlus) { 4717 // C++ [basic.link]p6: 4718 // If there is a visible declaration of an entity with linkage 4719 // having the same name and type, ignoring entities declared 4720 // outside the innermost enclosing namespace scope, the block 4721 // scope declaration declares that same entity and receives the 4722 // linkage of the previous declaration. 4723 DeclContext *OuterContext = DC->getRedeclContext(); 4724 if (!OuterContext->isFunctionOrMethod()) 4725 // This rule only applies to block-scope declarations. 4726 return false; 4727 4728 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4729 if (PrevOuterContext->isRecord()) 4730 // We found a member function: ignore it. 4731 return false; 4732 4733 // Find the innermost enclosing namespace for the new and 4734 // previous declarations. 4735 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4736 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4737 4738 // The previous declaration is in a different namespace, so it 4739 // isn't the same function. 4740 if (!OuterContext->Equals(PrevOuterContext)) 4741 return false; 4742 } 4743 4744 return true; 4745 } 4746 4747 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4748 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4749 if (!SS.isSet()) return; 4750 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4751 } 4752 4753 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4754 QualType type = decl->getType(); 4755 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4756 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4757 // Various kinds of declaration aren't allowed to be __autoreleasing. 4758 unsigned kind = -1U; 4759 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4760 if (var->hasAttr<BlocksAttr>()) 4761 kind = 0; // __block 4762 else if (!var->hasLocalStorage()) 4763 kind = 1; // global 4764 } else if (isa<ObjCIvarDecl>(decl)) { 4765 kind = 3; // ivar 4766 } else if (isa<FieldDecl>(decl)) { 4767 kind = 2; // field 4768 } 4769 4770 if (kind != -1U) { 4771 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4772 << kind; 4773 } 4774 } else if (lifetime == Qualifiers::OCL_None) { 4775 // Try to infer lifetime. 4776 if (!type->isObjCLifetimeType()) 4777 return false; 4778 4779 lifetime = type->getObjCARCImplicitLifetime(); 4780 type = Context.getLifetimeQualifiedType(type, lifetime); 4781 decl->setType(type); 4782 } 4783 4784 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4785 // Thread-local variables cannot have lifetime. 4786 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4787 var->getTLSKind()) { 4788 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4789 << var->getType(); 4790 return true; 4791 } 4792 } 4793 4794 return false; 4795 } 4796 4797 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4798 // 'weak' only applies to declarations with external linkage. 4799 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4800 if (!ND.isExternallyVisible()) { 4801 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4802 ND.dropAttr<WeakAttr>(); 4803 } 4804 } 4805 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4806 if (ND.isExternallyVisible()) { 4807 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4808 ND.dropAttr<WeakRefAttr>(); 4809 } 4810 } 4811 4812 // 'selectany' only applies to externally visible varable declarations. 4813 // It does not apply to functions. 4814 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4815 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4816 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4817 ND.dropAttr<SelectAnyAttr>(); 4818 } 4819 } 4820 } 4821 4822 /// Given that we are within the definition of the given function, 4823 /// will that definition behave like C99's 'inline', where the 4824 /// definition is discarded except for optimization purposes? 4825 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4826 // Try to avoid calling GetGVALinkageForFunction. 4827 4828 // All cases of this require the 'inline' keyword. 4829 if (!FD->isInlined()) return false; 4830 4831 // This is only possible in C++ with the gnu_inline attribute. 4832 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4833 return false; 4834 4835 // Okay, go ahead and call the relatively-more-expensive function. 4836 4837 #ifndef NDEBUG 4838 // AST quite reasonably asserts that it's working on a function 4839 // definition. We don't really have a way to tell it that we're 4840 // currently defining the function, so just lie to it in +Asserts 4841 // builds. This is an awful hack. 4842 FD->setLazyBody(1); 4843 #endif 4844 4845 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4846 4847 #ifndef NDEBUG 4848 FD->setLazyBody(0); 4849 #endif 4850 4851 return isC99Inline; 4852 } 4853 4854 /// Determine whether a variable is extern "C" prior to attaching 4855 /// an initializer. We can't just call isExternC() here, because that 4856 /// will also compute and cache whether the declaration is externally 4857 /// visible, which might change when we attach the initializer. 4858 /// 4859 /// This can only be used if the declaration is known to not be a 4860 /// redeclaration of an internal linkage declaration. 4861 /// 4862 /// For instance: 4863 /// 4864 /// auto x = []{}; 4865 /// 4866 /// Attaching the initializer here makes this declaration not externally 4867 /// visible, because its type has internal linkage. 4868 /// 4869 /// FIXME: This is a hack. 4870 template<typename T> 4871 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4872 if (S.getLangOpts().CPlusPlus) { 4873 // In C++, the overloadable attribute negates the effects of extern "C". 4874 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4875 return false; 4876 } 4877 return D->isExternC(); 4878 } 4879 4880 static bool shouldConsiderLinkage(const VarDecl *VD) { 4881 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4882 if (DC->isFunctionOrMethod()) 4883 return VD->hasExternalStorage(); 4884 if (DC->isFileContext()) 4885 return true; 4886 if (DC->isRecord()) 4887 return false; 4888 llvm_unreachable("Unexpected context"); 4889 } 4890 4891 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4892 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4893 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4894 return true; 4895 if (DC->isRecord()) 4896 return false; 4897 llvm_unreachable("Unexpected context"); 4898 } 4899 4900 /// Adjust the \c DeclContext for a function or variable that might be a 4901 /// function-local external declaration. 4902 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 4903 if (!DC->isFunctionOrMethod()) 4904 return false; 4905 4906 // If this is a local extern function or variable declared within a function 4907 // template, don't add it into the enclosing namespace scope until it is 4908 // instantiated; it might have a dependent type right now. 4909 if (DC->isDependentContext()) 4910 return true; 4911 4912 // C++11 [basic.link]p7: 4913 // When a block scope declaration of an entity with linkage is not found to 4914 // refer to some other declaration, then that entity is a member of the 4915 // innermost enclosing namespace. 4916 // 4917 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 4918 // semantically-enclosing namespace, not a lexically-enclosing one. 4919 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 4920 DC = DC->getParent(); 4921 return true; 4922 } 4923 4924 NamedDecl * 4925 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4926 TypeSourceInfo *TInfo, LookupResult &Previous, 4927 MultiTemplateParamsArg TemplateParamLists, 4928 bool &AddToScope) { 4929 QualType R = TInfo->getType(); 4930 DeclarationName Name = GetNameForDeclarator(D).getName(); 4931 4932 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4933 VarDecl::StorageClass SC = 4934 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 4935 4936 DeclContext *OriginalDC = DC; 4937 bool IsLocalExternDecl = SC == SC_Extern && 4938 adjustContextForLocalExternDecl(DC); 4939 4940 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) { 4941 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4942 // half array type (unless the cl_khr_fp16 extension is enabled). 4943 if (Context.getBaseElementType(R)->isHalfType()) { 4944 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4945 D.setInvalidType(); 4946 } 4947 } 4948 4949 if (SCSpec == DeclSpec::SCS_mutable) { 4950 // mutable can only appear on non-static class members, so it's always 4951 // an error here 4952 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4953 D.setInvalidType(); 4954 SC = SC_None; 4955 } 4956 4957 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 4958 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 4959 D.getDeclSpec().getStorageClassSpecLoc())) { 4960 // In C++11, the 'register' storage class specifier is deprecated. 4961 // Suppress the warning in system macros, it's used in macros in some 4962 // popular C system headers, such as in glibc's htonl() macro. 4963 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4964 diag::warn_deprecated_register) 4965 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4966 } 4967 4968 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4969 if (!II) { 4970 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4971 << Name; 4972 return 0; 4973 } 4974 4975 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4976 4977 if (!DC->isRecord() && S->getFnParent() == 0) { 4978 // C99 6.9p2: The storage-class specifiers auto and register shall not 4979 // appear in the declaration specifiers in an external declaration. 4980 if (SC == SC_Auto || SC == SC_Register) { 4981 // If this is a register variable with an asm label specified, then this 4982 // is a GNU extension. 4983 if (SC == SC_Register && D.getAsmLabel()) 4984 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4985 else 4986 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4987 D.setInvalidType(); 4988 } 4989 } 4990 4991 if (getLangOpts().OpenCL) { 4992 // Set up the special work-group-local storage class for variables in the 4993 // OpenCL __local address space. 4994 if (R.getAddressSpace() == LangAS::opencl_local) { 4995 SC = SC_OpenCLWorkGroupLocal; 4996 } 4997 4998 // OpenCL v1.2 s6.9.b p4: 4999 // The sampler type cannot be used with the __local and __global address 5000 // space qualifiers. 5001 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5002 R.getAddressSpace() == LangAS::opencl_global)) { 5003 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5004 } 5005 5006 // OpenCL 1.2 spec, p6.9 r: 5007 // The event type cannot be used to declare a program scope variable. 5008 // The event type cannot be used with the __local, __constant and __global 5009 // address space qualifiers. 5010 if (R->isEventT()) { 5011 if (S->getParent() == 0) { 5012 Diag(D.getLocStart(), diag::err_event_t_global_var); 5013 D.setInvalidType(); 5014 } 5015 5016 if (R.getAddressSpace()) { 5017 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5018 D.setInvalidType(); 5019 } 5020 } 5021 } 5022 5023 bool IsExplicitSpecialization = false; 5024 bool IsVariableTemplateSpecialization = false; 5025 bool IsPartialSpecialization = false; 5026 bool IsVariableTemplate = false; 5027 VarTemplateDecl *PrevVarTemplate = 0; 5028 VarDecl *NewVD = 0; 5029 VarTemplateDecl *NewTemplate = 0; 5030 if (!getLangOpts().CPlusPlus) { 5031 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5032 D.getIdentifierLoc(), II, 5033 R, TInfo, SC); 5034 5035 if (D.isInvalidType()) 5036 NewVD->setInvalidDecl(); 5037 } else { 5038 bool Invalid = false; 5039 5040 if (DC->isRecord() && !CurContext->isRecord()) { 5041 // This is an out-of-line definition of a static data member. 5042 switch (SC) { 5043 case SC_None: 5044 break; 5045 case SC_Static: 5046 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5047 diag::err_static_out_of_line) 5048 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5049 break; 5050 case SC_Auto: 5051 case SC_Register: 5052 case SC_Extern: 5053 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5054 // to names of variables declared in a block or to function parameters. 5055 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5056 // of class members 5057 5058 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5059 diag::err_storage_class_for_static_member) 5060 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5061 break; 5062 case SC_PrivateExtern: 5063 llvm_unreachable("C storage class in c++!"); 5064 case SC_OpenCLWorkGroupLocal: 5065 llvm_unreachable("OpenCL storage class in c++!"); 5066 } 5067 } 5068 5069 if (SC == SC_Static && CurContext->isRecord()) { 5070 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5071 if (RD->isLocalClass()) 5072 Diag(D.getIdentifierLoc(), 5073 diag::err_static_data_member_not_allowed_in_local_class) 5074 << Name << RD->getDeclName(); 5075 5076 // C++98 [class.union]p1: If a union contains a static data member, 5077 // the program is ill-formed. C++11 drops this restriction. 5078 if (RD->isUnion()) 5079 Diag(D.getIdentifierLoc(), 5080 getLangOpts().CPlusPlus11 5081 ? diag::warn_cxx98_compat_static_data_member_in_union 5082 : diag::ext_static_data_member_in_union) << Name; 5083 // We conservatively disallow static data members in anonymous structs. 5084 else if (!RD->getDeclName()) 5085 Diag(D.getIdentifierLoc(), 5086 diag::err_static_data_member_not_allowed_in_anon_struct) 5087 << Name << RD->isUnion(); 5088 } 5089 } 5090 5091 NamedDecl *PrevDecl = 0; 5092 if (Previous.begin() != Previous.end()) 5093 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 5094 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl); 5095 5096 // Match up the template parameter lists with the scope specifier, then 5097 // determine whether we have a template or a template specialization. 5098 TemplateParameterList *TemplateParams = 5099 MatchTemplateParametersToScopeSpecifier( 5100 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5101 D.getCXXScopeSpec(), TemplateParamLists, 5102 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5103 if (TemplateParams) { 5104 if (!TemplateParams->size() && 5105 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5106 // There is an extraneous 'template<>' for this variable. Complain 5107 // about it, but allow the declaration of the variable. 5108 Diag(TemplateParams->getTemplateLoc(), 5109 diag::err_template_variable_noparams) 5110 << II 5111 << SourceRange(TemplateParams->getTemplateLoc(), 5112 TemplateParams->getRAngleLoc()); 5113 } else { 5114 // Only C++1y supports variable templates (N3651). 5115 Diag(D.getIdentifierLoc(), 5116 getLangOpts().CPlusPlus1y 5117 ? diag::warn_cxx11_compat_variable_template 5118 : diag::ext_variable_template); 5119 5120 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5121 // This is an explicit specialization or a partial specialization. 5122 // Check that we can declare a specialization here 5123 5124 IsVariableTemplateSpecialization = true; 5125 IsPartialSpecialization = TemplateParams->size() > 0; 5126 5127 } else { // if (TemplateParams->size() > 0) 5128 // This is a template declaration. 5129 IsVariableTemplate = true; 5130 5131 // Check that we can declare a template here. 5132 if (CheckTemplateDeclScope(S, TemplateParams)) 5133 return 0; 5134 5135 // If there is a previous declaration with the same name, check 5136 // whether this is a valid redeclaration. 5137 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S)) 5138 PrevDecl = PrevVarTemplate = 0; 5139 5140 if (PrevVarTemplate) { 5141 // Ensure that the template parameter lists are compatible. 5142 if (!TemplateParameterListsAreEqual( 5143 TemplateParams, PrevVarTemplate->getTemplateParameters(), 5144 /*Complain=*/true, TPL_TemplateMatch)) 5145 return 0; 5146 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 5147 // Maybe we will complain about the shadowed template parameter. 5148 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5149 5150 // Just pretend that we didn't see the previous declaration. 5151 PrevDecl = 0; 5152 } else if (PrevDecl) { 5153 // C++ [temp]p5: 5154 // ... a template name declared in namespace scope or in class 5155 // scope shall be unique in that scope. 5156 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind) 5157 << Name; 5158 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5159 return 0; 5160 } 5161 5162 // Check the template parameter list of this declaration, possibly 5163 // merging in the template parameter list from the previous variable 5164 // template declaration. 5165 if (CheckTemplateParameterList( 5166 TemplateParams, 5167 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5168 : 0, 5169 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5170 DC->isDependentContext()) 5171 ? TPC_ClassTemplateMember 5172 : TPC_VarTemplate)) 5173 Invalid = true; 5174 5175 if (D.getCXXScopeSpec().isSet()) { 5176 // If the name of the template was qualified, we must be defining 5177 // the template out-of-line. 5178 if (!D.getCXXScopeSpec().isInvalid() && !Invalid && 5179 !PrevVarTemplate) { 5180 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match) 5181 << Name << DC << /*IsDefinition*/true 5182 << D.getCXXScopeSpec().getRange(); 5183 Invalid = true; 5184 } 5185 } 5186 } 5187 } 5188 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5189 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5190 5191 // We have encountered something that the user meant to be a 5192 // specialization (because it has explicitly-specified template 5193 // arguments) but that was not introduced with a "template<>" (or had 5194 // too few of them). 5195 // FIXME: Differentiate between attempts for explicit instantiations 5196 // (starting with "template") and the rest. 5197 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5198 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5199 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5200 "template<> "); 5201 IsVariableTemplateSpecialization = true; 5202 } 5203 5204 if (IsVariableTemplateSpecialization) { 5205 if (!PrevVarTemplate) { 5206 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) 5207 << IsPartialSpecialization; 5208 return 0; 5209 } 5210 5211 SourceLocation TemplateKWLoc = 5212 TemplateParamLists.size() > 0 5213 ? TemplateParamLists[0]->getTemplateLoc() 5214 : SourceLocation(); 5215 DeclResult Res = ActOnVarTemplateSpecialization( 5216 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5217 IsPartialSpecialization); 5218 if (Res.isInvalid()) 5219 return 0; 5220 NewVD = cast<VarDecl>(Res.get()); 5221 AddToScope = false; 5222 } else 5223 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5224 D.getIdentifierLoc(), II, R, TInfo, SC); 5225 5226 // If this is supposed to be a variable template, create it as such. 5227 if (IsVariableTemplate) { 5228 NewTemplate = 5229 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5230 TemplateParams, NewVD, PrevVarTemplate); 5231 NewVD->setDescribedVarTemplate(NewTemplate); 5232 } 5233 5234 // If this decl has an auto type in need of deduction, make a note of the 5235 // Decl so we can diagnose uses of it in its own initializer. 5236 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5237 ParsingInitForAutoVars.insert(NewVD); 5238 5239 if (D.isInvalidType() || Invalid) { 5240 NewVD->setInvalidDecl(); 5241 if (NewTemplate) 5242 NewTemplate->setInvalidDecl(); 5243 } 5244 5245 SetNestedNameSpecifier(NewVD, D); 5246 5247 // FIXME: Do we need D.getCXXScopeSpec().isSet()? 5248 if (TemplateParams && TemplateParamLists.size() > 1 && 5249 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) { 5250 NewVD->setTemplateParameterListsInfo( 5251 Context, TemplateParamLists.size() - 1, TemplateParamLists.data()); 5252 } else if (IsVariableTemplateSpecialization || 5253 (!TemplateParams && TemplateParamLists.size() > 0 && 5254 (D.getCXXScopeSpec().isSet()))) { 5255 NewVD->setTemplateParameterListsInfo(Context, 5256 TemplateParamLists.size(), 5257 TemplateParamLists.data()); 5258 } 5259 5260 if (D.getDeclSpec().isConstexprSpecified()) 5261 NewVD->setConstexpr(true); 5262 } 5263 5264 // Set the lexical context. If the declarator has a C++ scope specifier, the 5265 // lexical context will be different from the semantic context. 5266 NewVD->setLexicalDeclContext(CurContext); 5267 if (NewTemplate) 5268 NewTemplate->setLexicalDeclContext(CurContext); 5269 5270 if (IsLocalExternDecl) 5271 NewVD->setLocalExternDecl(); 5272 5273 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5274 if (NewVD->hasLocalStorage()) { 5275 // C++11 [dcl.stc]p4: 5276 // When thread_local is applied to a variable of block scope the 5277 // storage-class-specifier static is implied if it does not appear 5278 // explicitly. 5279 // Core issue: 'static' is not implied if the variable is declared 5280 // 'extern'. 5281 if (SCSpec == DeclSpec::SCS_unspecified && 5282 TSCS == DeclSpec::TSCS_thread_local && 5283 DC->isFunctionOrMethod()) 5284 NewVD->setTSCSpec(TSCS); 5285 else 5286 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5287 diag::err_thread_non_global) 5288 << DeclSpec::getSpecifierName(TSCS); 5289 } else if (!Context.getTargetInfo().isTLSSupported()) 5290 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5291 diag::err_thread_unsupported); 5292 else 5293 NewVD->setTSCSpec(TSCS); 5294 } 5295 5296 // C99 6.7.4p3 5297 // An inline definition of a function with external linkage shall 5298 // not contain a definition of a modifiable object with static or 5299 // thread storage duration... 5300 // We only apply this when the function is required to be defined 5301 // elsewhere, i.e. when the function is not 'extern inline'. Note 5302 // that a local variable with thread storage duration still has to 5303 // be marked 'static'. Also note that it's possible to get these 5304 // semantics in C++ using __attribute__((gnu_inline)). 5305 if (SC == SC_Static && S->getFnParent() != 0 && 5306 !NewVD->getType().isConstQualified()) { 5307 FunctionDecl *CurFD = getCurFunctionDecl(); 5308 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5309 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5310 diag::warn_static_local_in_extern_inline); 5311 MaybeSuggestAddingStaticToDecl(CurFD); 5312 } 5313 } 5314 5315 if (D.getDeclSpec().isModulePrivateSpecified()) { 5316 if (IsVariableTemplateSpecialization) 5317 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5318 << (IsPartialSpecialization ? 1 : 0) 5319 << FixItHint::CreateRemoval( 5320 D.getDeclSpec().getModulePrivateSpecLoc()); 5321 else if (IsExplicitSpecialization) 5322 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5323 << 2 5324 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5325 else if (NewVD->hasLocalStorage()) 5326 Diag(NewVD->getLocation(), diag::err_module_private_local) 5327 << 0 << NewVD->getDeclName() 5328 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5329 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5330 else { 5331 NewVD->setModulePrivate(); 5332 if (NewTemplate) 5333 NewTemplate->setModulePrivate(); 5334 } 5335 } 5336 5337 // Handle attributes prior to checking for duplicates in MergeVarDecl 5338 ProcessDeclAttributes(S, NewVD, D); 5339 5340 if (NewVD->hasAttrs()) 5341 CheckAlignasUnderalignment(NewVD); 5342 5343 if (getLangOpts().CUDA) { 5344 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5345 // storage [duration]." 5346 if (SC == SC_None && S->getFnParent() != 0 && 5347 (NewVD->hasAttr<CUDASharedAttr>() || 5348 NewVD->hasAttr<CUDAConstantAttr>())) { 5349 NewVD->setStorageClass(SC_Static); 5350 } 5351 } 5352 5353 // In auto-retain/release, infer strong retension for variables of 5354 // retainable type. 5355 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5356 NewVD->setInvalidDecl(); 5357 5358 // Handle GNU asm-label extension (encoded as an attribute). 5359 if (Expr *E = (Expr*)D.getAsmLabel()) { 5360 // The parser guarantees this is a string. 5361 StringLiteral *SE = cast<StringLiteral>(E); 5362 StringRef Label = SE->getString(); 5363 if (S->getFnParent() != 0) { 5364 switch (SC) { 5365 case SC_None: 5366 case SC_Auto: 5367 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5368 break; 5369 case SC_Register: 5370 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5371 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5372 break; 5373 case SC_Static: 5374 case SC_Extern: 5375 case SC_PrivateExtern: 5376 case SC_OpenCLWorkGroupLocal: 5377 break; 5378 } 5379 } 5380 5381 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5382 Context, Label)); 5383 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5384 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5385 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5386 if (I != ExtnameUndeclaredIdentifiers.end()) { 5387 NewVD->addAttr(I->second); 5388 ExtnameUndeclaredIdentifiers.erase(I); 5389 } 5390 } 5391 5392 // Diagnose shadowed variables before filtering for scope. 5393 if (!D.getCXXScopeSpec().isSet()) 5394 CheckShadow(S, NewVD, Previous); 5395 5396 // Don't consider existing declarations that are in a different 5397 // scope and are out-of-semantic-context declarations (if the new 5398 // declaration has linkage). 5399 FilterLookupForScope( 5400 Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5401 IsExplicitSpecialization || IsVariableTemplateSpecialization); 5402 5403 // Check whether the previous declaration is in the same block scope. This 5404 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5405 if (getLangOpts().CPlusPlus && 5406 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5407 NewVD->setPreviousDeclInSameBlockScope( 5408 Previous.isSingleResult() && !Previous.isShadowed() && 5409 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5410 5411 if (!getLangOpts().CPlusPlus) { 5412 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5413 } else { 5414 // Merge the decl with the existing one if appropriate. 5415 if (!Previous.empty()) { 5416 if (Previous.isSingleResult() && 5417 isa<FieldDecl>(Previous.getFoundDecl()) && 5418 D.getCXXScopeSpec().isSet()) { 5419 // The user tried to define a non-static data member 5420 // out-of-line (C++ [dcl.meaning]p1). 5421 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5422 << D.getCXXScopeSpec().getRange(); 5423 Previous.clear(); 5424 NewVD->setInvalidDecl(); 5425 } 5426 } else if (D.getCXXScopeSpec().isSet()) { 5427 // No previous declaration in the qualifying scope. 5428 Diag(D.getIdentifierLoc(), diag::err_no_member) 5429 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5430 << D.getCXXScopeSpec().getRange(); 5431 NewVD->setInvalidDecl(); 5432 } 5433 5434 if (!IsVariableTemplateSpecialization) { 5435 if (PrevVarTemplate) { 5436 LookupResult PrevDecl(*this, GetNameForDeclarator(D), 5437 LookupOrdinaryName, ForRedeclaration); 5438 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl()); 5439 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl)); 5440 } else 5441 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5442 } 5443 5444 // This is an explicit specialization of a static data member. Check it. 5445 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5446 CheckMemberSpecialization(NewVD, Previous)) 5447 NewVD->setInvalidDecl(); 5448 } 5449 5450 ProcessPragmaWeak(S, NewVD); 5451 checkAttributesAfterMerging(*this, *NewVD); 5452 5453 // If this is the first declaration of an extern C variable, update 5454 // the map of such variables. 5455 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5456 isIncompleteDeclExternC(*this, NewVD)) 5457 RegisterLocallyScopedExternCDecl(NewVD, S); 5458 5459 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5460 Decl *ManglingContextDecl; 5461 if (MangleNumberingContext *MCtx = 5462 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5463 ManglingContextDecl)) { 5464 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD)); 5465 } 5466 } 5467 5468 // If we are providing an explicit specialization of a static variable 5469 // template, make a note of that. 5470 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5471 PrevVarTemplate->setMemberSpecialization(); 5472 5473 if (NewTemplate) { 5474 ActOnDocumentableDecl(NewTemplate); 5475 return NewTemplate; 5476 } 5477 5478 return NewVD; 5479 } 5480 5481 /// \brief Diagnose variable or built-in function shadowing. Implements 5482 /// -Wshadow. 5483 /// 5484 /// This method is called whenever a VarDecl is added to a "useful" 5485 /// scope. 5486 /// 5487 /// \param S the scope in which the shadowing name is being declared 5488 /// \param R the lookup of the name 5489 /// 5490 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5491 // Return if warning is ignored. 5492 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5493 DiagnosticsEngine::Ignored) 5494 return; 5495 5496 // Don't diagnose declarations at file scope. 5497 if (D->hasGlobalStorage()) 5498 return; 5499 5500 DeclContext *NewDC = D->getDeclContext(); 5501 5502 // Only diagnose if we're shadowing an unambiguous field or variable. 5503 if (R.getResultKind() != LookupResult::Found) 5504 return; 5505 5506 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5507 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5508 return; 5509 5510 // Fields are not shadowed by variables in C++ static methods. 5511 if (isa<FieldDecl>(ShadowedDecl)) 5512 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5513 if (MD->isStatic()) 5514 return; 5515 5516 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5517 if (shadowedVar->isExternC()) { 5518 // For shadowing external vars, make sure that we point to the global 5519 // declaration, not a locally scoped extern declaration. 5520 for (VarDecl::redecl_iterator 5521 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 5522 I != E; ++I) 5523 if (I->isFileVarDecl()) { 5524 ShadowedDecl = *I; 5525 break; 5526 } 5527 } 5528 5529 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5530 5531 // Only warn about certain kinds of shadowing for class members. 5532 if (NewDC && NewDC->isRecord()) { 5533 // In particular, don't warn about shadowing non-class members. 5534 if (!OldDC->isRecord()) 5535 return; 5536 5537 // TODO: should we warn about static data members shadowing 5538 // static data members from base classes? 5539 5540 // TODO: don't diagnose for inaccessible shadowed members. 5541 // This is hard to do perfectly because we might friend the 5542 // shadowing context, but that's just a false negative. 5543 } 5544 5545 // Determine what kind of declaration we're shadowing. 5546 unsigned Kind; 5547 if (isa<RecordDecl>(OldDC)) { 5548 if (isa<FieldDecl>(ShadowedDecl)) 5549 Kind = 3; // field 5550 else 5551 Kind = 2; // static data member 5552 } else if (OldDC->isFileContext()) 5553 Kind = 1; // global 5554 else 5555 Kind = 0; // local 5556 5557 DeclarationName Name = R.getLookupName(); 5558 5559 // Emit warning and note. 5560 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5561 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5562 } 5563 5564 /// \brief Check -Wshadow without the advantage of a previous lookup. 5565 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5566 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5567 DiagnosticsEngine::Ignored) 5568 return; 5569 5570 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5571 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5572 LookupName(R, S); 5573 CheckShadow(S, D, R); 5574 } 5575 5576 /// Check for conflict between this global or extern "C" declaration and 5577 /// previous global or extern "C" declarations. This is only used in C++. 5578 template<typename T> 5579 static bool checkGlobalOrExternCConflict( 5580 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5581 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5582 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5583 5584 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5585 // The common case: this global doesn't conflict with any extern "C" 5586 // declaration. 5587 return false; 5588 } 5589 5590 if (Prev) { 5591 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5592 // Both the old and new declarations have C language linkage. This is a 5593 // redeclaration. 5594 Previous.clear(); 5595 Previous.addDecl(Prev); 5596 return true; 5597 } 5598 5599 // This is a global, non-extern "C" declaration, and there is a previous 5600 // non-global extern "C" declaration. Diagnose if this is a variable 5601 // declaration. 5602 if (!isa<VarDecl>(ND)) 5603 return false; 5604 } else { 5605 // The declaration is extern "C". Check for any declaration in the 5606 // translation unit which might conflict. 5607 if (IsGlobal) { 5608 // We have already performed the lookup into the translation unit. 5609 IsGlobal = false; 5610 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5611 I != E; ++I) { 5612 if (isa<VarDecl>(*I)) { 5613 Prev = *I; 5614 break; 5615 } 5616 } 5617 } else { 5618 DeclContext::lookup_result R = 5619 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5620 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5621 I != E; ++I) { 5622 if (isa<VarDecl>(*I)) { 5623 Prev = *I; 5624 break; 5625 } 5626 // FIXME: If we have any other entity with this name in global scope, 5627 // the declaration is ill-formed, but that is a defect: it breaks the 5628 // 'stat' hack, for instance. Only variables can have mangled name 5629 // clashes with extern "C" declarations, so only they deserve a 5630 // diagnostic. 5631 } 5632 } 5633 5634 if (!Prev) 5635 return false; 5636 } 5637 5638 // Use the first declaration's location to ensure we point at something which 5639 // is lexically inside an extern "C" linkage-spec. 5640 assert(Prev && "should have found a previous declaration to diagnose"); 5641 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5642 Prev = FD->getFirstDecl(); 5643 else 5644 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5645 5646 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5647 << IsGlobal << ND; 5648 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5649 << IsGlobal; 5650 return false; 5651 } 5652 5653 /// Apply special rules for handling extern "C" declarations. Returns \c true 5654 /// if we have found that this is a redeclaration of some prior entity. 5655 /// 5656 /// Per C++ [dcl.link]p6: 5657 /// Two declarations [for a function or variable] with C language linkage 5658 /// with the same name that appear in different scopes refer to the same 5659 /// [entity]. An entity with C language linkage shall not be declared with 5660 /// the same name as an entity in global scope. 5661 template<typename T> 5662 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5663 LookupResult &Previous) { 5664 if (!S.getLangOpts().CPlusPlus) { 5665 // In C, when declaring a global variable, look for a corresponding 'extern' 5666 // variable declared in function scope. We don't need this in C++, because 5667 // we find local extern decls in the surrounding file-scope DeclContext. 5668 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5669 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5670 Previous.clear(); 5671 Previous.addDecl(Prev); 5672 return true; 5673 } 5674 } 5675 return false; 5676 } 5677 5678 // A declaration in the translation unit can conflict with an extern "C" 5679 // declaration. 5680 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5681 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5682 5683 // An extern "C" declaration can conflict with a declaration in the 5684 // translation unit or can be a redeclaration of an extern "C" declaration 5685 // in another scope. 5686 if (isIncompleteDeclExternC(S,ND)) 5687 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5688 5689 // Neither global nor extern "C": nothing to do. 5690 return false; 5691 } 5692 5693 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5694 // If the decl is already known invalid, don't check it. 5695 if (NewVD->isInvalidDecl()) 5696 return; 5697 5698 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5699 QualType T = TInfo->getType(); 5700 5701 // Defer checking an 'auto' type until its initializer is attached. 5702 if (T->isUndeducedType()) 5703 return; 5704 5705 if (T->isObjCObjectType()) { 5706 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5707 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5708 T = Context.getObjCObjectPointerType(T); 5709 NewVD->setType(T); 5710 } 5711 5712 // Emit an error if an address space was applied to decl with local storage. 5713 // This includes arrays of objects with address space qualifiers, but not 5714 // automatic variables that point to other address spaces. 5715 // ISO/IEC TR 18037 S5.1.2 5716 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5717 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5718 NewVD->setInvalidDecl(); 5719 return; 5720 } 5721 5722 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5723 // __constant address space. 5724 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5725 && T.getAddressSpace() != LangAS::opencl_constant 5726 && !T->isSamplerT()){ 5727 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5728 NewVD->setInvalidDecl(); 5729 return; 5730 } 5731 5732 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5733 // scope. 5734 if ((getLangOpts().OpenCLVersion >= 120) 5735 && NewVD->isStaticLocal()) { 5736 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5737 NewVD->setInvalidDecl(); 5738 return; 5739 } 5740 5741 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5742 && !NewVD->hasAttr<BlocksAttr>()) { 5743 if (getLangOpts().getGC() != LangOptions::NonGC) 5744 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5745 else { 5746 assert(!getLangOpts().ObjCAutoRefCount); 5747 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5748 } 5749 } 5750 5751 bool isVM = T->isVariablyModifiedType(); 5752 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5753 NewVD->hasAttr<BlocksAttr>()) 5754 getCurFunction()->setHasBranchProtectedScope(); 5755 5756 if ((isVM && NewVD->hasLinkage()) || 5757 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5758 bool SizeIsNegative; 5759 llvm::APSInt Oversized; 5760 TypeSourceInfo *FixedTInfo = 5761 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5762 SizeIsNegative, Oversized); 5763 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5764 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5765 // FIXME: This won't give the correct result for 5766 // int a[10][n]; 5767 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5768 5769 if (NewVD->isFileVarDecl()) 5770 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5771 << SizeRange; 5772 else if (NewVD->isStaticLocal()) 5773 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5774 << SizeRange; 5775 else 5776 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5777 << SizeRange; 5778 NewVD->setInvalidDecl(); 5779 return; 5780 } 5781 5782 if (FixedTInfo == 0) { 5783 if (NewVD->isFileVarDecl()) 5784 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5785 else 5786 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5787 NewVD->setInvalidDecl(); 5788 return; 5789 } 5790 5791 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5792 NewVD->setType(FixedTInfo->getType()); 5793 NewVD->setTypeSourceInfo(FixedTInfo); 5794 } 5795 5796 if (T->isVoidType()) { 5797 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5798 // of objects and functions. 5799 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5800 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5801 << T; 5802 NewVD->setInvalidDecl(); 5803 return; 5804 } 5805 } 5806 5807 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5808 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5809 NewVD->setInvalidDecl(); 5810 return; 5811 } 5812 5813 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5814 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5815 NewVD->setInvalidDecl(); 5816 return; 5817 } 5818 5819 if (NewVD->isConstexpr() && !T->isDependentType() && 5820 RequireLiteralType(NewVD->getLocation(), T, 5821 diag::err_constexpr_var_non_literal)) { 5822 // Can't perform this check until the type is deduced. 5823 NewVD->setInvalidDecl(); 5824 return; 5825 } 5826 } 5827 5828 /// \brief Perform semantic checking on a newly-created variable 5829 /// declaration. 5830 /// 5831 /// This routine performs all of the type-checking required for a 5832 /// variable declaration once it has been built. It is used both to 5833 /// check variables after they have been parsed and their declarators 5834 /// have been translated into a declaration, and to check variables 5835 /// that have been instantiated from a template. 5836 /// 5837 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5838 /// 5839 /// Returns true if the variable declaration is a redeclaration. 5840 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5841 CheckVariableDeclarationType(NewVD); 5842 5843 // If the decl is already known invalid, don't check it. 5844 if (NewVD->isInvalidDecl()) 5845 return false; 5846 5847 // If we did not find anything by this name, look for a non-visible 5848 // extern "C" declaration with the same name. 5849 if (Previous.empty() && 5850 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5851 Previous.setShadowed(); 5852 5853 // Filter out any non-conflicting previous declarations. 5854 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5855 5856 if (!Previous.empty()) { 5857 MergeVarDecl(NewVD, Previous); 5858 return true; 5859 } 5860 return false; 5861 } 5862 5863 /// \brief Data used with FindOverriddenMethod 5864 struct FindOverriddenMethodData { 5865 Sema *S; 5866 CXXMethodDecl *Method; 5867 }; 5868 5869 /// \brief Member lookup function that determines whether a given C++ 5870 /// method overrides a method in a base class, to be used with 5871 /// CXXRecordDecl::lookupInBases(). 5872 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5873 CXXBasePath &Path, 5874 void *UserData) { 5875 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5876 5877 FindOverriddenMethodData *Data 5878 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5879 5880 DeclarationName Name = Data->Method->getDeclName(); 5881 5882 // FIXME: Do we care about other names here too? 5883 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5884 // We really want to find the base class destructor here. 5885 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5886 CanQualType CT = Data->S->Context.getCanonicalType(T); 5887 5888 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5889 } 5890 5891 for (Path.Decls = BaseRecord->lookup(Name); 5892 !Path.Decls.empty(); 5893 Path.Decls = Path.Decls.slice(1)) { 5894 NamedDecl *D = Path.Decls.front(); 5895 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5896 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5897 return true; 5898 } 5899 } 5900 5901 return false; 5902 } 5903 5904 namespace { 5905 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5906 } 5907 /// \brief Report an error regarding overriding, along with any relevant 5908 /// overriden methods. 5909 /// 5910 /// \param DiagID the primary error to report. 5911 /// \param MD the overriding method. 5912 /// \param OEK which overrides to include as notes. 5913 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5914 OverrideErrorKind OEK = OEK_All) { 5915 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5916 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5917 E = MD->end_overridden_methods(); 5918 I != E; ++I) { 5919 // This check (& the OEK parameter) could be replaced by a predicate, but 5920 // without lambdas that would be overkill. This is still nicer than writing 5921 // out the diag loop 3 times. 5922 if ((OEK == OEK_All) || 5923 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5924 (OEK == OEK_Deleted && (*I)->isDeleted())) 5925 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5926 } 5927 } 5928 5929 /// AddOverriddenMethods - See if a method overrides any in the base classes, 5930 /// and if so, check that it's a valid override and remember it. 5931 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5932 // Look for virtual methods in base classes that this method might override. 5933 CXXBasePaths Paths; 5934 FindOverriddenMethodData Data; 5935 Data.Method = MD; 5936 Data.S = this; 5937 bool hasDeletedOverridenMethods = false; 5938 bool hasNonDeletedOverridenMethods = false; 5939 bool AddedAny = false; 5940 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5941 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5942 E = Paths.found_decls_end(); I != E; ++I) { 5943 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5944 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5945 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5946 !CheckOverridingFunctionAttributes(MD, OldMD) && 5947 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5948 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5949 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5950 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5951 AddedAny = true; 5952 } 5953 } 5954 } 5955 } 5956 5957 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5958 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5959 } 5960 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5961 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5962 } 5963 5964 return AddedAny; 5965 } 5966 5967 namespace { 5968 // Struct for holding all of the extra arguments needed by 5969 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5970 struct ActOnFDArgs { 5971 Scope *S; 5972 Declarator &D; 5973 MultiTemplateParamsArg TemplateParamLists; 5974 bool AddToScope; 5975 }; 5976 } 5977 5978 namespace { 5979 5980 // Callback to only accept typo corrections that have a non-zero edit distance. 5981 // Also only accept corrections that have the same parent decl. 5982 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5983 public: 5984 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5985 CXXRecordDecl *Parent) 5986 : Context(Context), OriginalFD(TypoFD), 5987 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5988 5989 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5990 if (candidate.getEditDistance() == 0) 5991 return false; 5992 5993 SmallVector<unsigned, 1> MismatchedParams; 5994 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5995 CDeclEnd = candidate.end(); 5996 CDecl != CDeclEnd; ++CDecl) { 5997 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5998 5999 if (FD && !FD->hasBody() && 6000 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6001 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6002 CXXRecordDecl *Parent = MD->getParent(); 6003 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6004 return true; 6005 } else if (!ExpectedParent) { 6006 return true; 6007 } 6008 } 6009 } 6010 6011 return false; 6012 } 6013 6014 private: 6015 ASTContext &Context; 6016 FunctionDecl *OriginalFD; 6017 CXXRecordDecl *ExpectedParent; 6018 }; 6019 6020 } 6021 6022 /// \brief Generate diagnostics for an invalid function redeclaration. 6023 /// 6024 /// This routine handles generating the diagnostic messages for an invalid 6025 /// function redeclaration, including finding possible similar declarations 6026 /// or performing typo correction if there are no previous declarations with 6027 /// the same name. 6028 /// 6029 /// Returns a NamedDecl iff typo correction was performed and substituting in 6030 /// the new declaration name does not cause new errors. 6031 static NamedDecl *DiagnoseInvalidRedeclaration( 6032 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6033 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6034 DeclarationName Name = NewFD->getDeclName(); 6035 DeclContext *NewDC = NewFD->getDeclContext(); 6036 SmallVector<unsigned, 1> MismatchedParams; 6037 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6038 TypoCorrection Correction; 6039 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6040 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6041 : diag::err_member_decl_does_not_match; 6042 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6043 IsLocalFriend ? Sema::LookupLocalFriendName 6044 : Sema::LookupOrdinaryName, 6045 Sema::ForRedeclaration); 6046 6047 NewFD->setInvalidDecl(); 6048 if (IsLocalFriend) 6049 SemaRef.LookupName(Prev, S); 6050 else 6051 SemaRef.LookupQualifiedName(Prev, NewDC); 6052 assert(!Prev.isAmbiguous() && 6053 "Cannot have an ambiguity in previous-declaration lookup"); 6054 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6055 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6056 MD ? MD->getParent() : 0); 6057 if (!Prev.empty()) { 6058 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6059 Func != FuncEnd; ++Func) { 6060 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6061 if (FD && 6062 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6063 // Add 1 to the index so that 0 can mean the mismatch didn't 6064 // involve a parameter 6065 unsigned ParamNum = 6066 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6067 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6068 } 6069 } 6070 // If the qualified name lookup yielded nothing, try typo correction 6071 } else if ((Correction = SemaRef.CorrectTypo( 6072 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6073 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6074 IsLocalFriend ? 0 : NewDC))) { 6075 // Set up everything for the call to ActOnFunctionDeclarator 6076 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6077 ExtraArgs.D.getIdentifierLoc()); 6078 Previous.clear(); 6079 Previous.setLookupName(Correction.getCorrection()); 6080 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6081 CDeclEnd = Correction.end(); 6082 CDecl != CDeclEnd; ++CDecl) { 6083 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6084 if (FD && !FD->hasBody() && 6085 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6086 Previous.addDecl(FD); 6087 } 6088 } 6089 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6090 6091 NamedDecl *Result; 6092 // Retry building the function declaration with the new previous 6093 // declarations, and with errors suppressed. 6094 { 6095 // Trap errors. 6096 Sema::SFINAETrap Trap(SemaRef); 6097 6098 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6099 // pieces need to verify the typo-corrected C++ declaration and hopefully 6100 // eliminate the need for the parameter pack ExtraArgs. 6101 Result = SemaRef.ActOnFunctionDeclarator( 6102 ExtraArgs.S, ExtraArgs.D, 6103 Correction.getCorrectionDecl()->getDeclContext(), 6104 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6105 ExtraArgs.AddToScope); 6106 6107 if (Trap.hasErrorOccurred()) 6108 Result = 0; 6109 } 6110 6111 if (Result) { 6112 // Determine which correction we picked. 6113 Decl *Canonical = Result->getCanonicalDecl(); 6114 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6115 I != E; ++I) 6116 if ((*I)->getCanonicalDecl() == Canonical) 6117 Correction.setCorrectionDecl(*I); 6118 6119 SemaRef.diagnoseTypo( 6120 Correction, 6121 SemaRef.PDiag(IsLocalFriend 6122 ? diag::err_no_matching_local_friend_suggest 6123 : diag::err_member_decl_does_not_match_suggest) 6124 << Name << NewDC << IsDefinition); 6125 return Result; 6126 } 6127 6128 // Pretend the typo correction never occurred 6129 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6130 ExtraArgs.D.getIdentifierLoc()); 6131 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6132 Previous.clear(); 6133 Previous.setLookupName(Name); 6134 } 6135 6136 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6137 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6138 6139 bool NewFDisConst = false; 6140 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6141 NewFDisConst = NewMD->isConst(); 6142 6143 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6144 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6145 NearMatch != NearMatchEnd; ++NearMatch) { 6146 FunctionDecl *FD = NearMatch->first; 6147 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6148 bool FDisConst = MD && MD->isConst(); 6149 bool IsMember = MD || !IsLocalFriend; 6150 6151 // FIXME: These notes are poorly worded for the local friend case. 6152 if (unsigned Idx = NearMatch->second) { 6153 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6154 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6155 if (Loc.isInvalid()) Loc = FD->getLocation(); 6156 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6157 : diag::note_local_decl_close_param_match) 6158 << Idx << FDParam->getType() 6159 << NewFD->getParamDecl(Idx - 1)->getType(); 6160 } else if (FDisConst != NewFDisConst) { 6161 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6162 << NewFDisConst << FD->getSourceRange().getEnd(); 6163 } else 6164 SemaRef.Diag(FD->getLocation(), 6165 IsMember ? diag::note_member_def_close_match 6166 : diag::note_local_decl_close_match); 6167 } 6168 return 0; 6169 } 6170 6171 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6172 Declarator &D) { 6173 switch (D.getDeclSpec().getStorageClassSpec()) { 6174 default: llvm_unreachable("Unknown storage class!"); 6175 case DeclSpec::SCS_auto: 6176 case DeclSpec::SCS_register: 6177 case DeclSpec::SCS_mutable: 6178 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6179 diag::err_typecheck_sclass_func); 6180 D.setInvalidType(); 6181 break; 6182 case DeclSpec::SCS_unspecified: break; 6183 case DeclSpec::SCS_extern: 6184 if (D.getDeclSpec().isExternInLinkageSpec()) 6185 return SC_None; 6186 return SC_Extern; 6187 case DeclSpec::SCS_static: { 6188 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6189 // C99 6.7.1p5: 6190 // The declaration of an identifier for a function that has 6191 // block scope shall have no explicit storage-class specifier 6192 // other than extern 6193 // See also (C++ [dcl.stc]p4). 6194 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6195 diag::err_static_block_func); 6196 break; 6197 } else 6198 return SC_Static; 6199 } 6200 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6201 } 6202 6203 // No explicit storage class has already been returned 6204 return SC_None; 6205 } 6206 6207 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6208 DeclContext *DC, QualType &R, 6209 TypeSourceInfo *TInfo, 6210 FunctionDecl::StorageClass SC, 6211 bool &IsVirtualOkay) { 6212 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6213 DeclarationName Name = NameInfo.getName(); 6214 6215 FunctionDecl *NewFD = 0; 6216 bool isInline = D.getDeclSpec().isInlineSpecified(); 6217 6218 if (!SemaRef.getLangOpts().CPlusPlus) { 6219 // Determine whether the function was written with a 6220 // prototype. This true when: 6221 // - there is a prototype in the declarator, or 6222 // - the type R of the function is some kind of typedef or other reference 6223 // to a type name (which eventually refers to a function type). 6224 bool HasPrototype = 6225 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6226 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6227 6228 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6229 D.getLocStart(), NameInfo, R, 6230 TInfo, SC, isInline, 6231 HasPrototype, false); 6232 if (D.isInvalidType()) 6233 NewFD->setInvalidDecl(); 6234 6235 // Set the lexical context. 6236 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6237 6238 return NewFD; 6239 } 6240 6241 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6242 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6243 6244 // Check that the return type is not an abstract class type. 6245 // For record types, this is done by the AbstractClassUsageDiagnoser once 6246 // the class has been completely parsed. 6247 if (!DC->isRecord() && 6248 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 6249 R->getAs<FunctionType>()->getResultType(), 6250 diag::err_abstract_type_in_decl, 6251 SemaRef.AbstractReturnType)) 6252 D.setInvalidType(); 6253 6254 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6255 // This is a C++ constructor declaration. 6256 assert(DC->isRecord() && 6257 "Constructors can only be declared in a member context"); 6258 6259 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6260 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6261 D.getLocStart(), NameInfo, 6262 R, TInfo, isExplicit, isInline, 6263 /*isImplicitlyDeclared=*/false, 6264 isConstexpr); 6265 6266 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6267 // This is a C++ destructor declaration. 6268 if (DC->isRecord()) { 6269 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6270 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6271 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6272 SemaRef.Context, Record, 6273 D.getLocStart(), 6274 NameInfo, R, TInfo, isInline, 6275 /*isImplicitlyDeclared=*/false); 6276 6277 // If the class is complete, then we now create the implicit exception 6278 // specification. If the class is incomplete or dependent, we can't do 6279 // it yet. 6280 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6281 Record->getDefinition() && !Record->isBeingDefined() && 6282 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6283 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6284 } 6285 6286 // The Microsoft ABI requires that we perform the destructor body 6287 // checks (i.e. operator delete() lookup) at every declaration, as 6288 // any translation unit may need to emit a deleting destructor. 6289 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() && 6290 !Record->isDependentType() && Record->getDefinition() && 6291 !Record->isBeingDefined()) { 6292 SemaRef.CheckDestructor(NewDD); 6293 } 6294 6295 IsVirtualOkay = true; 6296 return NewDD; 6297 6298 } else { 6299 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6300 D.setInvalidType(); 6301 6302 // Create a FunctionDecl to satisfy the function definition parsing 6303 // code path. 6304 return FunctionDecl::Create(SemaRef.Context, DC, 6305 D.getLocStart(), 6306 D.getIdentifierLoc(), Name, R, TInfo, 6307 SC, isInline, 6308 /*hasPrototype=*/true, isConstexpr); 6309 } 6310 6311 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6312 if (!DC->isRecord()) { 6313 SemaRef.Diag(D.getIdentifierLoc(), 6314 diag::err_conv_function_not_member); 6315 return 0; 6316 } 6317 6318 SemaRef.CheckConversionDeclarator(D, R, SC); 6319 IsVirtualOkay = true; 6320 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6321 D.getLocStart(), NameInfo, 6322 R, TInfo, isInline, isExplicit, 6323 isConstexpr, SourceLocation()); 6324 6325 } else if (DC->isRecord()) { 6326 // If the name of the function is the same as the name of the record, 6327 // then this must be an invalid constructor that has a return type. 6328 // (The parser checks for a return type and makes the declarator a 6329 // constructor if it has no return type). 6330 if (Name.getAsIdentifierInfo() && 6331 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6332 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6333 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6334 << SourceRange(D.getIdentifierLoc()); 6335 return 0; 6336 } 6337 6338 // This is a C++ method declaration. 6339 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6340 cast<CXXRecordDecl>(DC), 6341 D.getLocStart(), NameInfo, R, 6342 TInfo, SC, isInline, 6343 isConstexpr, SourceLocation()); 6344 IsVirtualOkay = !Ret->isStatic(); 6345 return Ret; 6346 } else { 6347 // Determine whether the function was written with a 6348 // prototype. This true when: 6349 // - we're in C++ (where every function has a prototype), 6350 return FunctionDecl::Create(SemaRef.Context, DC, 6351 D.getLocStart(), 6352 NameInfo, R, TInfo, SC, isInline, 6353 true/*HasPrototype*/, isConstexpr); 6354 } 6355 } 6356 6357 void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 6358 // In C++, the empty parameter-type-list must be spelled "void"; a 6359 // typedef of void is not permitted. 6360 if (getLangOpts().CPlusPlus && 6361 Param->getType().getUnqualifiedType() != Context.VoidTy) { 6362 bool IsTypeAlias = false; 6363 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 6364 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 6365 else if (const TemplateSpecializationType *TST = 6366 Param->getType()->getAs<TemplateSpecializationType>()) 6367 IsTypeAlias = TST->isTypeAlias(); 6368 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 6369 << IsTypeAlias; 6370 } 6371 } 6372 6373 enum OpenCLParamType { 6374 ValidKernelParam, 6375 PtrPtrKernelParam, 6376 PtrKernelParam, 6377 InvalidKernelParam, 6378 RecordKernelParam 6379 }; 6380 6381 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6382 if (PT->isPointerType()) { 6383 QualType PointeeType = PT->getPointeeType(); 6384 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam; 6385 } 6386 6387 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6388 // be used as builtin types. 6389 6390 if (PT->isImageType()) 6391 return PtrKernelParam; 6392 6393 if (PT->isBooleanType()) 6394 return InvalidKernelParam; 6395 6396 if (PT->isEventT()) 6397 return InvalidKernelParam; 6398 6399 if (PT->isHalfType()) 6400 return InvalidKernelParam; 6401 6402 if (PT->isRecordType()) 6403 return RecordKernelParam; 6404 6405 return ValidKernelParam; 6406 } 6407 6408 static void checkIsValidOpenCLKernelParameter( 6409 Sema &S, 6410 Declarator &D, 6411 ParmVarDecl *Param, 6412 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6413 QualType PT = Param->getType(); 6414 6415 // Cache the valid types we encounter to avoid rechecking structs that are 6416 // used again 6417 if (ValidTypes.count(PT.getTypePtr())) 6418 return; 6419 6420 switch (getOpenCLKernelParameterType(PT)) { 6421 case PtrPtrKernelParam: 6422 // OpenCL v1.2 s6.9.a: 6423 // A kernel function argument cannot be declared as a 6424 // pointer to a pointer type. 6425 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6426 D.setInvalidType(); 6427 return; 6428 6429 // OpenCL v1.2 s6.9.k: 6430 // Arguments to kernel functions in a program cannot be declared with the 6431 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6432 // uintptr_t or a struct and/or union that contain fields declared to be 6433 // one of these built-in scalar types. 6434 6435 case InvalidKernelParam: 6436 // OpenCL v1.2 s6.8 n: 6437 // A kernel function argument cannot be declared 6438 // of event_t type. 6439 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6440 D.setInvalidType(); 6441 return; 6442 6443 case PtrKernelParam: 6444 case ValidKernelParam: 6445 ValidTypes.insert(PT.getTypePtr()); 6446 return; 6447 6448 case RecordKernelParam: 6449 break; 6450 } 6451 6452 // Track nested structs we will inspect 6453 SmallVector<const Decl *, 4> VisitStack; 6454 6455 // Track where we are in the nested structs. Items will migrate from 6456 // VisitStack to HistoryStack as we do the DFS for bad field. 6457 SmallVector<const FieldDecl *, 4> HistoryStack; 6458 HistoryStack.push_back((const FieldDecl *) 0); 6459 6460 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6461 VisitStack.push_back(PD); 6462 6463 assert(VisitStack.back() && "First decl null?"); 6464 6465 do { 6466 const Decl *Next = VisitStack.pop_back_val(); 6467 if (!Next) { 6468 assert(!HistoryStack.empty()); 6469 // Found a marker, we have gone up a level 6470 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6471 ValidTypes.insert(Hist->getType().getTypePtr()); 6472 6473 continue; 6474 } 6475 6476 // Adds everything except the original parameter declaration (which is not a 6477 // field itself) to the history stack. 6478 const RecordDecl *RD; 6479 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6480 HistoryStack.push_back(Field); 6481 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6482 } else { 6483 RD = cast<RecordDecl>(Next); 6484 } 6485 6486 // Add a null marker so we know when we've gone back up a level 6487 VisitStack.push_back((const Decl *) 0); 6488 6489 for (RecordDecl::field_iterator I = RD->field_begin(), 6490 E = RD->field_end(); I != E; ++I) { 6491 const FieldDecl *FD = *I; 6492 QualType QT = FD->getType(); 6493 6494 if (ValidTypes.count(QT.getTypePtr())) 6495 continue; 6496 6497 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6498 if (ParamType == ValidKernelParam) 6499 continue; 6500 6501 if (ParamType == RecordKernelParam) { 6502 VisitStack.push_back(FD); 6503 continue; 6504 } 6505 6506 // OpenCL v1.2 s6.9.p: 6507 // Arguments to kernel functions that are declared to be a struct or union 6508 // do not allow OpenCL objects to be passed as elements of the struct or 6509 // union. 6510 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) { 6511 S.Diag(Param->getLocation(), 6512 diag::err_record_with_pointers_kernel_param) 6513 << PT->isUnionType() 6514 << PT; 6515 } else { 6516 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6517 } 6518 6519 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6520 << PD->getDeclName(); 6521 6522 // We have an error, now let's go back up through history and show where 6523 // the offending field came from 6524 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6525 E = HistoryStack.end(); I != E; ++I) { 6526 const FieldDecl *OuterField = *I; 6527 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6528 << OuterField->getType(); 6529 } 6530 6531 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6532 << QT->isPointerType() 6533 << QT; 6534 D.setInvalidType(); 6535 return; 6536 } 6537 } while (!VisitStack.empty()); 6538 } 6539 6540 NamedDecl* 6541 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6542 TypeSourceInfo *TInfo, LookupResult &Previous, 6543 MultiTemplateParamsArg TemplateParamLists, 6544 bool &AddToScope) { 6545 QualType R = TInfo->getType(); 6546 6547 assert(R.getTypePtr()->isFunctionType()); 6548 6549 // TODO: consider using NameInfo for diagnostic. 6550 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6551 DeclarationName Name = NameInfo.getName(); 6552 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6553 6554 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6555 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6556 diag::err_invalid_thread) 6557 << DeclSpec::getSpecifierName(TSCS); 6558 6559 if (D.isFirstDeclarationOfMember()) 6560 adjustMemberFunctionCC(R, D.isStaticMember()); 6561 6562 bool isFriend = false; 6563 FunctionTemplateDecl *FunctionTemplate = 0; 6564 bool isExplicitSpecialization = false; 6565 bool isFunctionTemplateSpecialization = false; 6566 6567 bool isDependentClassScopeExplicitSpecialization = false; 6568 bool HasExplicitTemplateArgs = false; 6569 TemplateArgumentListInfo TemplateArgs; 6570 6571 bool isVirtualOkay = false; 6572 6573 DeclContext *OriginalDC = DC; 6574 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6575 6576 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6577 isVirtualOkay); 6578 if (!NewFD) return 0; 6579 6580 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6581 NewFD->setTopLevelDeclInObjCContainer(); 6582 6583 // Set the lexical context. If this is a function-scope declaration, or has a 6584 // C++ scope specifier, or is the object of a friend declaration, the lexical 6585 // context will be different from the semantic context. 6586 NewFD->setLexicalDeclContext(CurContext); 6587 6588 if (IsLocalExternDecl) 6589 NewFD->setLocalExternDecl(); 6590 6591 if (getLangOpts().CPlusPlus) { 6592 bool isInline = D.getDeclSpec().isInlineSpecified(); 6593 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6594 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6595 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6596 isFriend = D.getDeclSpec().isFriendSpecified(); 6597 if (isFriend && !isInline && D.isFunctionDefinition()) { 6598 // C++ [class.friend]p5 6599 // A function can be defined in a friend declaration of a 6600 // class . . . . Such a function is implicitly inline. 6601 NewFD->setImplicitlyInline(); 6602 } 6603 6604 // If this is a method defined in an __interface, and is not a constructor 6605 // or an overloaded operator, then set the pure flag (isVirtual will already 6606 // return true). 6607 if (const CXXRecordDecl *Parent = 6608 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6609 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6610 NewFD->setPure(true); 6611 } 6612 6613 SetNestedNameSpecifier(NewFD, D); 6614 isExplicitSpecialization = false; 6615 isFunctionTemplateSpecialization = false; 6616 if (D.isInvalidType()) 6617 NewFD->setInvalidDecl(); 6618 6619 // Match up the template parameter lists with the scope specifier, then 6620 // determine whether we have a template or a template specialization. 6621 bool Invalid = false; 6622 if (TemplateParameterList *TemplateParams = 6623 MatchTemplateParametersToScopeSpecifier( 6624 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6625 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6626 isExplicitSpecialization, Invalid)) { 6627 if (TemplateParams->size() > 0) { 6628 // This is a function template 6629 6630 // Check that we can declare a template here. 6631 if (CheckTemplateDeclScope(S, TemplateParams)) 6632 return 0; 6633 6634 // A destructor cannot be a template. 6635 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6636 Diag(NewFD->getLocation(), diag::err_destructor_template); 6637 return 0; 6638 } 6639 6640 // If we're adding a template to a dependent context, we may need to 6641 // rebuilding some of the types used within the template parameter list, 6642 // now that we know what the current instantiation is. 6643 if (DC->isDependentContext()) { 6644 ContextRAII SavedContext(*this, DC); 6645 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6646 Invalid = true; 6647 } 6648 6649 6650 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6651 NewFD->getLocation(), 6652 Name, TemplateParams, 6653 NewFD); 6654 FunctionTemplate->setLexicalDeclContext(CurContext); 6655 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6656 6657 // For source fidelity, store the other template param lists. 6658 if (TemplateParamLists.size() > 1) { 6659 NewFD->setTemplateParameterListsInfo(Context, 6660 TemplateParamLists.size() - 1, 6661 TemplateParamLists.data()); 6662 } 6663 } else { 6664 // This is a function template specialization. 6665 isFunctionTemplateSpecialization = true; 6666 // For source fidelity, store all the template param lists. 6667 NewFD->setTemplateParameterListsInfo(Context, 6668 TemplateParamLists.size(), 6669 TemplateParamLists.data()); 6670 6671 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6672 if (isFriend) { 6673 // We want to remove the "template<>", found here. 6674 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6675 6676 // If we remove the template<> and the name is not a 6677 // template-id, we're actually silently creating a problem: 6678 // the friend declaration will refer to an untemplated decl, 6679 // and clearly the user wants a template specialization. So 6680 // we need to insert '<>' after the name. 6681 SourceLocation InsertLoc; 6682 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6683 InsertLoc = D.getName().getSourceRange().getEnd(); 6684 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6685 } 6686 6687 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6688 << Name << RemoveRange 6689 << FixItHint::CreateRemoval(RemoveRange) 6690 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6691 } 6692 } 6693 } 6694 else { 6695 // All template param lists were matched against the scope specifier: 6696 // this is NOT (an explicit specialization of) a template. 6697 if (TemplateParamLists.size() > 0) 6698 // For source fidelity, store all the template param lists. 6699 NewFD->setTemplateParameterListsInfo(Context, 6700 TemplateParamLists.size(), 6701 TemplateParamLists.data()); 6702 } 6703 6704 if (Invalid) { 6705 NewFD->setInvalidDecl(); 6706 if (FunctionTemplate) 6707 FunctionTemplate->setInvalidDecl(); 6708 } 6709 6710 // C++ [dcl.fct.spec]p5: 6711 // The virtual specifier shall only be used in declarations of 6712 // nonstatic class member functions that appear within a 6713 // member-specification of a class declaration; see 10.3. 6714 // 6715 if (isVirtual && !NewFD->isInvalidDecl()) { 6716 if (!isVirtualOkay) { 6717 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6718 diag::err_virtual_non_function); 6719 } else if (!CurContext->isRecord()) { 6720 // 'virtual' was specified outside of the class. 6721 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6722 diag::err_virtual_out_of_class) 6723 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6724 } else if (NewFD->getDescribedFunctionTemplate()) { 6725 // C++ [temp.mem]p3: 6726 // A member function template shall not be virtual. 6727 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6728 diag::err_virtual_member_function_template) 6729 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6730 } else { 6731 // Okay: Add virtual to the method. 6732 NewFD->setVirtualAsWritten(true); 6733 } 6734 6735 if (getLangOpts().CPlusPlus1y && 6736 NewFD->getResultType()->isUndeducedType()) 6737 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6738 } 6739 6740 if (getLangOpts().CPlusPlus1y && 6741 (NewFD->isDependentContext() || 6742 (isFriend && CurContext->isDependentContext())) && 6743 NewFD->getResultType()->isUndeducedType()) { 6744 // If the function template is referenced directly (for instance, as a 6745 // member of the current instantiation), pretend it has a dependent type. 6746 // This is not really justified by the standard, but is the only sane 6747 // thing to do. 6748 // FIXME: For a friend function, we have not marked the function as being 6749 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6750 const FunctionProtoType *FPT = 6751 NewFD->getType()->castAs<FunctionProtoType>(); 6752 QualType Result = SubstAutoType(FPT->getResultType(), 6753 Context.DependentTy); 6754 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(), 6755 FPT->getExtProtoInfo())); 6756 } 6757 6758 // C++ [dcl.fct.spec]p3: 6759 // The inline specifier shall not appear on a block scope function 6760 // declaration. 6761 if (isInline && !NewFD->isInvalidDecl()) { 6762 if (CurContext->isFunctionOrMethod()) { 6763 // 'inline' is not allowed on block scope function declaration. 6764 Diag(D.getDeclSpec().getInlineSpecLoc(), 6765 diag::err_inline_declaration_block_scope) << Name 6766 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6767 } 6768 } 6769 6770 // C++ [dcl.fct.spec]p6: 6771 // The explicit specifier shall be used only in the declaration of a 6772 // constructor or conversion function within its class definition; 6773 // see 12.3.1 and 12.3.2. 6774 if (isExplicit && !NewFD->isInvalidDecl()) { 6775 if (!CurContext->isRecord()) { 6776 // 'explicit' was specified outside of the class. 6777 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6778 diag::err_explicit_out_of_class) 6779 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6780 } else if (!isa<CXXConstructorDecl>(NewFD) && 6781 !isa<CXXConversionDecl>(NewFD)) { 6782 // 'explicit' was specified on a function that wasn't a constructor 6783 // or conversion function. 6784 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6785 diag::err_explicit_non_ctor_or_conv_function) 6786 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6787 } 6788 } 6789 6790 if (isConstexpr) { 6791 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6792 // are implicitly inline. 6793 NewFD->setImplicitlyInline(); 6794 6795 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6796 // be either constructors or to return a literal type. Therefore, 6797 // destructors cannot be declared constexpr. 6798 if (isa<CXXDestructorDecl>(NewFD)) 6799 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6800 } 6801 6802 // If __module_private__ was specified, mark the function accordingly. 6803 if (D.getDeclSpec().isModulePrivateSpecified()) { 6804 if (isFunctionTemplateSpecialization) { 6805 SourceLocation ModulePrivateLoc 6806 = D.getDeclSpec().getModulePrivateSpecLoc(); 6807 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6808 << 0 6809 << FixItHint::CreateRemoval(ModulePrivateLoc); 6810 } else { 6811 NewFD->setModulePrivate(); 6812 if (FunctionTemplate) 6813 FunctionTemplate->setModulePrivate(); 6814 } 6815 } 6816 6817 if (isFriend) { 6818 if (FunctionTemplate) { 6819 FunctionTemplate->setObjectOfFriendDecl(); 6820 FunctionTemplate->setAccess(AS_public); 6821 } 6822 NewFD->setObjectOfFriendDecl(); 6823 NewFD->setAccess(AS_public); 6824 } 6825 6826 // If a function is defined as defaulted or deleted, mark it as such now. 6827 switch (D.getFunctionDefinitionKind()) { 6828 case FDK_Declaration: 6829 case FDK_Definition: 6830 break; 6831 6832 case FDK_Defaulted: 6833 NewFD->setDefaulted(); 6834 break; 6835 6836 case FDK_Deleted: 6837 NewFD->setDeletedAsWritten(); 6838 break; 6839 } 6840 6841 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6842 D.isFunctionDefinition()) { 6843 // C++ [class.mfct]p2: 6844 // A member function may be defined (8.4) in its class definition, in 6845 // which case it is an inline member function (7.1.2) 6846 NewFD->setImplicitlyInline(); 6847 } 6848 6849 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6850 !CurContext->isRecord()) { 6851 // C++ [class.static]p1: 6852 // A data or function member of a class may be declared static 6853 // in a class definition, in which case it is a static member of 6854 // the class. 6855 6856 // Complain about the 'static' specifier if it's on an out-of-line 6857 // member function definition. 6858 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6859 diag::err_static_out_of_line) 6860 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6861 } 6862 6863 // C++11 [except.spec]p15: 6864 // A deallocation function with no exception-specification is treated 6865 // as if it were specified with noexcept(true). 6866 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6867 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6868 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6869 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6870 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6871 EPI.ExceptionSpecType = EST_BasicNoexcept; 6872 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 6873 FPT->getArgTypes(), EPI)); 6874 } 6875 } 6876 6877 // Filter out previous declarations that don't match the scope. 6878 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6879 isExplicitSpecialization || 6880 isFunctionTemplateSpecialization); 6881 6882 // Handle GNU asm-label extension (encoded as an attribute). 6883 if (Expr *E = (Expr*) D.getAsmLabel()) { 6884 // The parser guarantees this is a string. 6885 StringLiteral *SE = cast<StringLiteral>(E); 6886 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6887 SE->getString())); 6888 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6889 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6890 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6891 if (I != ExtnameUndeclaredIdentifiers.end()) { 6892 NewFD->addAttr(I->second); 6893 ExtnameUndeclaredIdentifiers.erase(I); 6894 } 6895 } 6896 6897 // Copy the parameter declarations from the declarator D to the function 6898 // declaration NewFD, if they are available. First scavenge them into Params. 6899 SmallVector<ParmVarDecl*, 16> Params; 6900 if (D.isFunctionDeclarator()) { 6901 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6902 6903 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6904 // function that takes no arguments, not a function that takes a 6905 // single void argument. 6906 // We let through "const void" here because Sema::GetTypeForDeclarator 6907 // already checks for that case. 6908 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6909 FTI.ArgInfo[0].Param && 6910 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6911 // Empty arg list, don't push any params. 6912 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6913 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6914 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6915 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6916 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6917 Param->setDeclContext(NewFD); 6918 Params.push_back(Param); 6919 6920 if (Param->isInvalidDecl()) 6921 NewFD->setInvalidDecl(); 6922 } 6923 } 6924 6925 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6926 // When we're declaring a function with a typedef, typeof, etc as in the 6927 // following example, we'll need to synthesize (unnamed) 6928 // parameters for use in the declaration. 6929 // 6930 // @code 6931 // typedef void fn(int); 6932 // fn f; 6933 // @endcode 6934 6935 // Synthesize a parameter for each argument type. 6936 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 6937 AE = FT->arg_type_end(); AI != AE; ++AI) { 6938 ParmVarDecl *Param = 6939 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6940 Param->setScopeInfo(0, Params.size()); 6941 Params.push_back(Param); 6942 } 6943 } else { 6944 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6945 "Should not need args for typedef of non-prototype fn"); 6946 } 6947 6948 // Finally, we know we have the right number of parameters, install them. 6949 NewFD->setParams(Params); 6950 6951 // Find all anonymous symbols defined during the declaration of this function 6952 // and add to NewFD. This lets us track decls such 'enum Y' in: 6953 // 6954 // void f(enum Y {AA} x) {} 6955 // 6956 // which would otherwise incorrectly end up in the translation unit scope. 6957 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6958 DeclsInPrototypeScope.clear(); 6959 6960 if (D.getDeclSpec().isNoreturnSpecified()) 6961 NewFD->addAttr( 6962 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6963 Context)); 6964 6965 // Functions returning a variably modified type violate C99 6.7.5.2p2 6966 // because all functions have linkage. 6967 if (!NewFD->isInvalidDecl() && 6968 NewFD->getResultType()->isVariablyModifiedType()) { 6969 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6970 NewFD->setInvalidDecl(); 6971 } 6972 6973 // Handle attributes. 6974 ProcessDeclAttributes(S, NewFD, D); 6975 6976 QualType RetType = NewFD->getResultType(); 6977 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6978 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6979 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6980 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6981 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6982 // Attach the attribute to the new decl. Don't apply the attribute if it 6983 // returns an instance of the class (e.g. assignment operators). 6984 if (!MD || MD->getParent() != Ret) { 6985 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 6986 Context)); 6987 } 6988 } 6989 6990 if (!getLangOpts().CPlusPlus) { 6991 // Perform semantic checking on the function declaration. 6992 bool isExplicitSpecialization=false; 6993 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 6994 CheckMain(NewFD, D.getDeclSpec()); 6995 6996 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 6997 CheckMSVCRTEntryPoint(NewFD); 6998 6999 if (!NewFD->isInvalidDecl()) 7000 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7001 isExplicitSpecialization)); 7002 else if (!Previous.empty()) 7003 // Make graceful recovery from an invalid redeclaration. 7004 D.setRedeclaration(true); 7005 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7006 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7007 "previous declaration set still overloaded"); 7008 } else { 7009 // C++11 [replacement.functions]p3: 7010 // The program's definitions shall not be specified as inline. 7011 // 7012 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7013 // 7014 // Suppress the diagnostic if the function is __attribute__((used)), since 7015 // that forces an external definition to be emitted. 7016 if (D.getDeclSpec().isInlineSpecified() && 7017 NewFD->isReplaceableGlobalAllocationFunction() && 7018 !NewFD->hasAttr<UsedAttr>()) 7019 Diag(D.getDeclSpec().getInlineSpecLoc(), 7020 diag::ext_operator_new_delete_declared_inline) 7021 << NewFD->getDeclName(); 7022 7023 // If the declarator is a template-id, translate the parser's template 7024 // argument list into our AST format. 7025 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7026 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7027 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7028 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7029 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7030 TemplateId->NumArgs); 7031 translateTemplateArguments(TemplateArgsPtr, 7032 TemplateArgs); 7033 7034 HasExplicitTemplateArgs = true; 7035 7036 if (NewFD->isInvalidDecl()) { 7037 HasExplicitTemplateArgs = false; 7038 } else if (FunctionTemplate) { 7039 // Function template with explicit template arguments. 7040 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7041 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7042 7043 HasExplicitTemplateArgs = false; 7044 } else if (!isFunctionTemplateSpecialization && 7045 !D.getDeclSpec().isFriendSpecified()) { 7046 // We have encountered something that the user meant to be a 7047 // specialization (because it has explicitly-specified template 7048 // arguments) but that was not introduced with a "template<>" (or had 7049 // too few of them). 7050 // FIXME: Differentiate between attempts for explicit instantiations 7051 // (starting with "template") and the rest. 7052 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7053 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7054 << FixItHint::CreateInsertion( 7055 D.getDeclSpec().getLocStart(), 7056 "template<> "); 7057 isFunctionTemplateSpecialization = true; 7058 } else { 7059 // "friend void foo<>(int);" is an implicit specialization decl. 7060 isFunctionTemplateSpecialization = true; 7061 } 7062 } else if (isFriend && isFunctionTemplateSpecialization) { 7063 // This combination is only possible in a recovery case; the user 7064 // wrote something like: 7065 // template <> friend void foo(int); 7066 // which we're recovering from as if the user had written: 7067 // friend void foo<>(int); 7068 // Go ahead and fake up a template id. 7069 HasExplicitTemplateArgs = true; 7070 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7071 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7072 } 7073 7074 // If it's a friend (and only if it's a friend), it's possible 7075 // that either the specialized function type or the specialized 7076 // template is dependent, and therefore matching will fail. In 7077 // this case, don't check the specialization yet. 7078 bool InstantiationDependent = false; 7079 if (isFunctionTemplateSpecialization && isFriend && 7080 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7081 TemplateSpecializationType::anyDependentTemplateArguments( 7082 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7083 InstantiationDependent))) { 7084 assert(HasExplicitTemplateArgs && 7085 "friend function specialization without template args"); 7086 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7087 Previous)) 7088 NewFD->setInvalidDecl(); 7089 } else if (isFunctionTemplateSpecialization) { 7090 if (CurContext->isDependentContext() && CurContext->isRecord() 7091 && !isFriend) { 7092 isDependentClassScopeExplicitSpecialization = true; 7093 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7094 diag::ext_function_specialization_in_class : 7095 diag::err_function_specialization_in_class) 7096 << NewFD->getDeclName(); 7097 } else if (CheckFunctionTemplateSpecialization(NewFD, 7098 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7099 Previous)) 7100 NewFD->setInvalidDecl(); 7101 7102 // C++ [dcl.stc]p1: 7103 // A storage-class-specifier shall not be specified in an explicit 7104 // specialization (14.7.3) 7105 FunctionTemplateSpecializationInfo *Info = 7106 NewFD->getTemplateSpecializationInfo(); 7107 if (Info && SC != SC_None) { 7108 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7109 Diag(NewFD->getLocation(), 7110 diag::err_explicit_specialization_inconsistent_storage_class) 7111 << SC 7112 << FixItHint::CreateRemoval( 7113 D.getDeclSpec().getStorageClassSpecLoc()); 7114 7115 else 7116 Diag(NewFD->getLocation(), 7117 diag::ext_explicit_specialization_storage_class) 7118 << FixItHint::CreateRemoval( 7119 D.getDeclSpec().getStorageClassSpecLoc()); 7120 } 7121 7122 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7123 if (CheckMemberSpecialization(NewFD, Previous)) 7124 NewFD->setInvalidDecl(); 7125 } 7126 7127 // Perform semantic checking on the function declaration. 7128 if (!isDependentClassScopeExplicitSpecialization) { 7129 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7130 CheckMain(NewFD, D.getDeclSpec()); 7131 7132 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7133 CheckMSVCRTEntryPoint(NewFD); 7134 7135 if (NewFD->isInvalidDecl()) { 7136 // If this is a class member, mark the class invalid immediately. 7137 // This avoids some consistency errors later. 7138 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 7139 methodDecl->getParent()->setInvalidDecl(); 7140 } else 7141 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7142 isExplicitSpecialization)); 7143 } 7144 7145 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7146 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7147 "previous declaration set still overloaded"); 7148 7149 NamedDecl *PrincipalDecl = (FunctionTemplate 7150 ? cast<NamedDecl>(FunctionTemplate) 7151 : NewFD); 7152 7153 if (isFriend && D.isRedeclaration()) { 7154 AccessSpecifier Access = AS_public; 7155 if (!NewFD->isInvalidDecl()) 7156 Access = NewFD->getPreviousDecl()->getAccess(); 7157 7158 NewFD->setAccess(Access); 7159 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7160 } 7161 7162 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7163 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7164 PrincipalDecl->setNonMemberOperator(); 7165 7166 // If we have a function template, check the template parameter 7167 // list. This will check and merge default template arguments. 7168 if (FunctionTemplate) { 7169 FunctionTemplateDecl *PrevTemplate = 7170 FunctionTemplate->getPreviousDecl(); 7171 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7172 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7173 D.getDeclSpec().isFriendSpecified() 7174 ? (D.isFunctionDefinition() 7175 ? TPC_FriendFunctionTemplateDefinition 7176 : TPC_FriendFunctionTemplate) 7177 : (D.getCXXScopeSpec().isSet() && 7178 DC && DC->isRecord() && 7179 DC->isDependentContext()) 7180 ? TPC_ClassTemplateMember 7181 : TPC_FunctionTemplate); 7182 } 7183 7184 if (NewFD->isInvalidDecl()) { 7185 // Ignore all the rest of this. 7186 } else if (!D.isRedeclaration()) { 7187 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7188 AddToScope }; 7189 // Fake up an access specifier if it's supposed to be a class member. 7190 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7191 NewFD->setAccess(AS_public); 7192 7193 // Qualified decls generally require a previous declaration. 7194 if (D.getCXXScopeSpec().isSet()) { 7195 // ...with the major exception of templated-scope or 7196 // dependent-scope friend declarations. 7197 7198 // TODO: we currently also suppress this check in dependent 7199 // contexts because (1) the parameter depth will be off when 7200 // matching friend templates and (2) we might actually be 7201 // selecting a friend based on a dependent factor. But there 7202 // are situations where these conditions don't apply and we 7203 // can actually do this check immediately. 7204 if (isFriend && 7205 (TemplateParamLists.size() || 7206 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7207 CurContext->isDependentContext())) { 7208 // ignore these 7209 } else { 7210 // The user tried to provide an out-of-line definition for a 7211 // function that is a member of a class or namespace, but there 7212 // was no such member function declared (C++ [class.mfct]p2, 7213 // C++ [namespace.memdef]p2). For example: 7214 // 7215 // class X { 7216 // void f() const; 7217 // }; 7218 // 7219 // void X::f() { } // ill-formed 7220 // 7221 // Complain about this problem, and attempt to suggest close 7222 // matches (e.g., those that differ only in cv-qualifiers and 7223 // whether the parameter types are references). 7224 7225 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7226 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7227 AddToScope = ExtraArgs.AddToScope; 7228 return Result; 7229 } 7230 } 7231 7232 // Unqualified local friend declarations are required to resolve 7233 // to something. 7234 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7235 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7236 *this, Previous, NewFD, ExtraArgs, true, S)) { 7237 AddToScope = ExtraArgs.AddToScope; 7238 return Result; 7239 } 7240 } 7241 7242 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 7243 !isFriend && !isFunctionTemplateSpecialization && 7244 !isExplicitSpecialization) { 7245 // An out-of-line member function declaration must also be a 7246 // definition (C++ [dcl.meaning]p1). 7247 // Note that this is not the case for explicit specializations of 7248 // function templates or member functions of class templates, per 7249 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7250 // extension for compatibility with old SWIG code which likes to 7251 // generate them. 7252 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7253 << D.getCXXScopeSpec().getRange(); 7254 } 7255 } 7256 7257 ProcessPragmaWeak(S, NewFD); 7258 checkAttributesAfterMerging(*this, *NewFD); 7259 7260 AddKnownFunctionAttributes(NewFD); 7261 7262 if (NewFD->hasAttr<OverloadableAttr>() && 7263 !NewFD->getType()->getAs<FunctionProtoType>()) { 7264 Diag(NewFD->getLocation(), 7265 diag::err_attribute_overloadable_no_prototype) 7266 << NewFD; 7267 7268 // Turn this into a variadic function with no parameters. 7269 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7270 FunctionProtoType::ExtProtoInfo EPI( 7271 Context.getDefaultCallingConvention(true, false)); 7272 EPI.Variadic = true; 7273 EPI.ExtInfo = FT->getExtInfo(); 7274 7275 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI); 7276 NewFD->setType(R); 7277 } 7278 7279 // If there's a #pragma GCC visibility in scope, and this isn't a class 7280 // member, set the visibility of this function. 7281 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7282 AddPushedVisibilityAttribute(NewFD); 7283 7284 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7285 // marking the function. 7286 AddCFAuditedAttribute(NewFD); 7287 7288 // If this is the first declaration of an extern C variable, update 7289 // the map of such variables. 7290 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7291 isIncompleteDeclExternC(*this, NewFD)) 7292 RegisterLocallyScopedExternCDecl(NewFD, S); 7293 7294 // Set this FunctionDecl's range up to the right paren. 7295 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7296 7297 if (getLangOpts().CPlusPlus) { 7298 if (FunctionTemplate) { 7299 if (NewFD->isInvalidDecl()) 7300 FunctionTemplate->setInvalidDecl(); 7301 return FunctionTemplate; 7302 } 7303 } 7304 7305 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7306 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7307 if ((getLangOpts().OpenCLVersion >= 120) 7308 && (SC == SC_Static)) { 7309 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7310 D.setInvalidType(); 7311 } 7312 7313 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7314 if (!NewFD->getResultType()->isVoidType()) { 7315 Diag(D.getIdentifierLoc(), 7316 diag::err_expected_kernel_void_return_type); 7317 D.setInvalidType(); 7318 } 7319 7320 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7321 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 7322 PE = NewFD->param_end(); PI != PE; ++PI) { 7323 ParmVarDecl *Param = *PI; 7324 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7325 } 7326 } 7327 7328 MarkUnusedFileScopedDecl(NewFD); 7329 7330 if (getLangOpts().CUDA) 7331 if (IdentifierInfo *II = NewFD->getIdentifier()) 7332 if (!NewFD->isInvalidDecl() && 7333 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7334 if (II->isStr("cudaConfigureCall")) { 7335 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 7336 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7337 7338 Context.setcudaConfigureCallDecl(NewFD); 7339 } 7340 } 7341 7342 // Here we have an function template explicit specialization at class scope. 7343 // The actually specialization will be postponed to template instatiation 7344 // time via the ClassScopeFunctionSpecializationDecl node. 7345 if (isDependentClassScopeExplicitSpecialization) { 7346 ClassScopeFunctionSpecializationDecl *NewSpec = 7347 ClassScopeFunctionSpecializationDecl::Create( 7348 Context, CurContext, SourceLocation(), 7349 cast<CXXMethodDecl>(NewFD), 7350 HasExplicitTemplateArgs, TemplateArgs); 7351 CurContext->addDecl(NewSpec); 7352 AddToScope = false; 7353 } 7354 7355 return NewFD; 7356 } 7357 7358 /// \brief Perform semantic checking of a new function declaration. 7359 /// 7360 /// Performs semantic analysis of the new function declaration 7361 /// NewFD. This routine performs all semantic checking that does not 7362 /// require the actual declarator involved in the declaration, and is 7363 /// used both for the declaration of functions as they are parsed 7364 /// (called via ActOnDeclarator) and for the declaration of functions 7365 /// that have been instantiated via C++ template instantiation (called 7366 /// via InstantiateDecl). 7367 /// 7368 /// \param IsExplicitSpecialization whether this new function declaration is 7369 /// an explicit specialization of the previous declaration. 7370 /// 7371 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7372 /// 7373 /// \returns true if the function declaration is a redeclaration. 7374 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7375 LookupResult &Previous, 7376 bool IsExplicitSpecialization) { 7377 assert(!NewFD->getResultType()->isVariablyModifiedType() 7378 && "Variably modified return types are not handled here"); 7379 7380 // Determine whether the type of this function should be merged with 7381 // a previous visible declaration. This never happens for functions in C++, 7382 // and always happens in C if the previous declaration was visible. 7383 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7384 !Previous.isShadowed(); 7385 7386 // Filter out any non-conflicting previous declarations. 7387 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7388 7389 bool Redeclaration = false; 7390 NamedDecl *OldDecl = 0; 7391 7392 // Merge or overload the declaration with an existing declaration of 7393 // the same name, if appropriate. 7394 if (!Previous.empty()) { 7395 // Determine whether NewFD is an overload of PrevDecl or 7396 // a declaration that requires merging. If it's an overload, 7397 // there's no more work to do here; we'll just add the new 7398 // function to the scope. 7399 if (!AllowOverloadingOfFunction(Previous, Context)) { 7400 NamedDecl *Candidate = Previous.getFoundDecl(); 7401 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7402 Redeclaration = true; 7403 OldDecl = Candidate; 7404 } 7405 } else { 7406 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7407 /*NewIsUsingDecl*/ false)) { 7408 case Ovl_Match: 7409 Redeclaration = true; 7410 break; 7411 7412 case Ovl_NonFunction: 7413 Redeclaration = true; 7414 break; 7415 7416 case Ovl_Overload: 7417 Redeclaration = false; 7418 break; 7419 } 7420 7421 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7422 // If a function name is overloadable in C, then every function 7423 // with that name must be marked "overloadable". 7424 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7425 << Redeclaration << NewFD; 7426 NamedDecl *OverloadedDecl = 0; 7427 if (Redeclaration) 7428 OverloadedDecl = OldDecl; 7429 else if (!Previous.empty()) 7430 OverloadedDecl = Previous.getRepresentativeDecl(); 7431 if (OverloadedDecl) 7432 Diag(OverloadedDecl->getLocation(), 7433 diag::note_attribute_overloadable_prev_overload); 7434 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 7435 Context)); 7436 } 7437 } 7438 } 7439 7440 // Check for a previous extern "C" declaration with this name. 7441 if (!Redeclaration && 7442 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7443 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7444 if (!Previous.empty()) { 7445 // This is an extern "C" declaration with the same name as a previous 7446 // declaration, and thus redeclares that entity... 7447 Redeclaration = true; 7448 OldDecl = Previous.getFoundDecl(); 7449 MergeTypeWithPrevious = false; 7450 7451 // ... except in the presence of __attribute__((overloadable)). 7452 if (OldDecl->hasAttr<OverloadableAttr>()) { 7453 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7454 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7455 << Redeclaration << NewFD; 7456 Diag(Previous.getFoundDecl()->getLocation(), 7457 diag::note_attribute_overloadable_prev_overload); 7458 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 7459 Context)); 7460 } 7461 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7462 Redeclaration = false; 7463 OldDecl = 0; 7464 } 7465 } 7466 } 7467 } 7468 7469 // C++11 [dcl.constexpr]p8: 7470 // A constexpr specifier for a non-static member function that is not 7471 // a constructor declares that member function to be const. 7472 // 7473 // This needs to be delayed until we know whether this is an out-of-line 7474 // definition of a static member function. 7475 // 7476 // This rule is not present in C++1y, so we produce a backwards 7477 // compatibility warning whenever it happens in C++11. 7478 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7479 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7480 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7481 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7482 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl); 7483 if (FunctionTemplateDecl *OldTD = 7484 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl)) 7485 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl()); 7486 if (!OldMD || !OldMD->isStatic()) { 7487 const FunctionProtoType *FPT = 7488 MD->getType()->castAs<FunctionProtoType>(); 7489 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7490 EPI.TypeQuals |= Qualifiers::Const; 7491 MD->setType(Context.getFunctionType(FPT->getResultType(), 7492 FPT->getArgTypes(), EPI)); 7493 7494 // Warn that we did this, if we're not performing template instantiation. 7495 // In that case, we'll have warned already when the template was defined. 7496 if (ActiveTemplateInstantiations.empty()) { 7497 SourceLocation AddConstLoc; 7498 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7499 .IgnoreParens().getAs<FunctionTypeLoc>()) 7500 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7501 7502 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7503 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7504 } 7505 } 7506 } 7507 7508 if (Redeclaration) { 7509 // NewFD and OldDecl represent declarations that need to be 7510 // merged. 7511 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7512 NewFD->setInvalidDecl(); 7513 return Redeclaration; 7514 } 7515 7516 Previous.clear(); 7517 Previous.addDecl(OldDecl); 7518 7519 if (FunctionTemplateDecl *OldTemplateDecl 7520 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7521 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7522 FunctionTemplateDecl *NewTemplateDecl 7523 = NewFD->getDescribedFunctionTemplate(); 7524 assert(NewTemplateDecl && "Template/non-template mismatch"); 7525 if (CXXMethodDecl *Method 7526 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7527 Method->setAccess(OldTemplateDecl->getAccess()); 7528 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7529 } 7530 7531 // If this is an explicit specialization of a member that is a function 7532 // template, mark it as a member specialization. 7533 if (IsExplicitSpecialization && 7534 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7535 NewTemplateDecl->setMemberSpecialization(); 7536 assert(OldTemplateDecl->isMemberSpecialization()); 7537 } 7538 7539 } else { 7540 // This needs to happen first so that 'inline' propagates. 7541 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7542 7543 if (isa<CXXMethodDecl>(NewFD)) { 7544 // A valid redeclaration of a C++ method must be out-of-line, 7545 // but (unfortunately) it's not necessarily a definition 7546 // because of templates, which means that the previous 7547 // declaration is not necessarily from the class definition. 7548 7549 // For just setting the access, that doesn't matter. 7550 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7551 NewFD->setAccess(oldMethod->getAccess()); 7552 7553 // Update the key-function state if necessary for this ABI. 7554 if (NewFD->isInlined() && 7555 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7556 // setNonKeyFunction needs to work with the original 7557 // declaration from the class definition, and isVirtual() is 7558 // just faster in that case, so map back to that now. 7559 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7560 if (oldMethod->isVirtual()) { 7561 Context.setNonKeyFunction(oldMethod); 7562 } 7563 } 7564 } 7565 } 7566 } 7567 7568 // Semantic checking for this function declaration (in isolation). 7569 if (getLangOpts().CPlusPlus) { 7570 // C++-specific checks. 7571 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7572 CheckConstructor(Constructor); 7573 } else if (CXXDestructorDecl *Destructor = 7574 dyn_cast<CXXDestructorDecl>(NewFD)) { 7575 CXXRecordDecl *Record = Destructor->getParent(); 7576 QualType ClassType = Context.getTypeDeclType(Record); 7577 7578 // FIXME: Shouldn't we be able to perform this check even when the class 7579 // type is dependent? Both gcc and edg can handle that. 7580 if (!ClassType->isDependentType()) { 7581 DeclarationName Name 7582 = Context.DeclarationNames.getCXXDestructorName( 7583 Context.getCanonicalType(ClassType)); 7584 if (NewFD->getDeclName() != Name) { 7585 Diag(NewFD->getLocation(), diag::err_destructor_name); 7586 NewFD->setInvalidDecl(); 7587 return Redeclaration; 7588 } 7589 } 7590 } else if (CXXConversionDecl *Conversion 7591 = dyn_cast<CXXConversionDecl>(NewFD)) { 7592 ActOnConversionDeclarator(Conversion); 7593 } 7594 7595 // Find any virtual functions that this function overrides. 7596 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7597 if (!Method->isFunctionTemplateSpecialization() && 7598 !Method->getDescribedFunctionTemplate() && 7599 Method->isCanonicalDecl()) { 7600 if (AddOverriddenMethods(Method->getParent(), Method)) { 7601 // If the function was marked as "static", we have a problem. 7602 if (NewFD->getStorageClass() == SC_Static) { 7603 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7604 } 7605 } 7606 } 7607 7608 if (Method->isStatic()) 7609 checkThisInStaticMemberFunctionType(Method); 7610 } 7611 7612 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7613 if (NewFD->isOverloadedOperator() && 7614 CheckOverloadedOperatorDeclaration(NewFD)) { 7615 NewFD->setInvalidDecl(); 7616 return Redeclaration; 7617 } 7618 7619 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7620 if (NewFD->getLiteralIdentifier() && 7621 CheckLiteralOperatorDeclaration(NewFD)) { 7622 NewFD->setInvalidDecl(); 7623 return Redeclaration; 7624 } 7625 7626 // In C++, check default arguments now that we have merged decls. Unless 7627 // the lexical context is the class, because in this case this is done 7628 // during delayed parsing anyway. 7629 if (!CurContext->isRecord()) 7630 CheckCXXDefaultArguments(NewFD); 7631 7632 // If this function declares a builtin function, check the type of this 7633 // declaration against the expected type for the builtin. 7634 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7635 ASTContext::GetBuiltinTypeError Error; 7636 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7637 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7638 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7639 // The type of this function differs from the type of the builtin, 7640 // so forget about the builtin entirely. 7641 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7642 } 7643 } 7644 7645 // If this function is declared as being extern "C", then check to see if 7646 // the function returns a UDT (class, struct, or union type) that is not C 7647 // compatible, and if it does, warn the user. 7648 // But, issue any diagnostic on the first declaration only. 7649 if (NewFD->isExternC() && Previous.empty()) { 7650 QualType R = NewFD->getResultType(); 7651 if (R->isIncompleteType() && !R->isVoidType()) 7652 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7653 << NewFD << R; 7654 else if (!R.isPODType(Context) && !R->isVoidType() && 7655 !R->isObjCObjectPointerType()) 7656 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7657 } 7658 } 7659 return Redeclaration; 7660 } 7661 7662 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7663 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7664 if (!TSI) 7665 return SourceRange(); 7666 7667 TypeLoc TL = TSI->getTypeLoc(); 7668 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7669 if (!FunctionTL) 7670 return SourceRange(); 7671 7672 TypeLoc ResultTL = FunctionTL.getResultLoc(); 7673 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7674 return ResultTL.getSourceRange(); 7675 7676 return SourceRange(); 7677 } 7678 7679 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7680 // C++11 [basic.start.main]p3: A program that declares main to be inline, 7681 // static or constexpr is ill-formed. 7682 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7683 // appear in a declaration of main. 7684 // static main is not an error under C99, but we should warn about it. 7685 // We accept _Noreturn main as an extension. 7686 if (FD->getStorageClass() == SC_Static) 7687 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7688 ? diag::err_static_main : diag::warn_static_main) 7689 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7690 if (FD->isInlineSpecified()) 7691 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7692 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7693 if (DS.isNoreturnSpecified()) { 7694 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7695 SourceRange NoreturnRange(NoreturnLoc, 7696 PP.getLocForEndOfToken(NoreturnLoc)); 7697 Diag(NoreturnLoc, diag::ext_noreturn_main); 7698 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7699 << FixItHint::CreateRemoval(NoreturnRange); 7700 } 7701 if (FD->isConstexpr()) { 7702 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7703 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7704 FD->setConstexpr(false); 7705 } 7706 7707 if (getLangOpts().OpenCL) { 7708 Diag(FD->getLocation(), diag::err_opencl_no_main) 7709 << FD->hasAttr<OpenCLKernelAttr>(); 7710 FD->setInvalidDecl(); 7711 return; 7712 } 7713 7714 QualType T = FD->getType(); 7715 assert(T->isFunctionType() && "function decl is not of function type"); 7716 const FunctionType* FT = T->castAs<FunctionType>(); 7717 7718 // All the standards say that main() should should return 'int'. 7719 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 7720 // In C and C++, main magically returns 0 if you fall off the end; 7721 // set the flag which tells us that. 7722 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7723 FD->setHasImplicitReturnZero(true); 7724 7725 // In C with GNU extensions we allow main() to have non-integer return 7726 // type, but we should warn about the extension, and we disable the 7727 // implicit-return-zero rule. 7728 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7729 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7730 7731 SourceRange ResultRange = getResultSourceRange(FD); 7732 if (ResultRange.isValid()) 7733 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7734 << FixItHint::CreateReplacement(ResultRange, "int"); 7735 7736 // Otherwise, this is just a flat-out error. 7737 } else { 7738 SourceRange ResultRange = getResultSourceRange(FD); 7739 if (ResultRange.isValid()) 7740 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7741 << FixItHint::CreateReplacement(ResultRange, "int"); 7742 else 7743 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7744 7745 FD->setInvalidDecl(true); 7746 } 7747 7748 // Treat protoless main() as nullary. 7749 if (isa<FunctionNoProtoType>(FT)) return; 7750 7751 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7752 unsigned nparams = FTP->getNumArgs(); 7753 assert(FD->getNumParams() == nparams); 7754 7755 bool HasExtraParameters = (nparams > 3); 7756 7757 // Darwin passes an undocumented fourth argument of type char**. If 7758 // other platforms start sprouting these, the logic below will start 7759 // getting shifty. 7760 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7761 HasExtraParameters = false; 7762 7763 if (HasExtraParameters) { 7764 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7765 FD->setInvalidDecl(true); 7766 nparams = 3; 7767 } 7768 7769 // FIXME: a lot of the following diagnostics would be improved 7770 // if we had some location information about types. 7771 7772 QualType CharPP = 7773 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7774 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7775 7776 for (unsigned i = 0; i < nparams; ++i) { 7777 QualType AT = FTP->getArgType(i); 7778 7779 bool mismatch = true; 7780 7781 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7782 mismatch = false; 7783 else if (Expected[i] == CharPP) { 7784 // As an extension, the following forms are okay: 7785 // char const ** 7786 // char const * const * 7787 // char * const * 7788 7789 QualifierCollector qs; 7790 const PointerType* PT; 7791 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7792 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7793 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7794 Context.CharTy)) { 7795 qs.removeConst(); 7796 mismatch = !qs.empty(); 7797 } 7798 } 7799 7800 if (mismatch) { 7801 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7802 // TODO: suggest replacing given type with expected type 7803 FD->setInvalidDecl(true); 7804 } 7805 } 7806 7807 if (nparams == 1 && !FD->isInvalidDecl()) { 7808 Diag(FD->getLocation(), diag::warn_main_one_arg); 7809 } 7810 7811 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7812 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName(); 7813 FD->setInvalidDecl(); 7814 } 7815 } 7816 7817 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7818 QualType T = FD->getType(); 7819 assert(T->isFunctionType() && "function decl is not of function type"); 7820 const FunctionType *FT = T->castAs<FunctionType>(); 7821 7822 // Set an implicit return of 'zero' if the function can return some integral, 7823 // enumeration, pointer or nullptr type. 7824 if (FT->getResultType()->isIntegralOrEnumerationType() || 7825 FT->getResultType()->isAnyPointerType() || 7826 FT->getResultType()->isNullPtrType()) 7827 // DllMain is exempt because a return value of zero means it failed. 7828 if (FD->getName() != "DllMain") 7829 FD->setHasImplicitReturnZero(true); 7830 7831 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7832 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName(); 7833 FD->setInvalidDecl(); 7834 } 7835 } 7836 7837 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7838 // FIXME: Need strict checking. In C89, we need to check for 7839 // any assignment, increment, decrement, function-calls, or 7840 // commas outside of a sizeof. In C99, it's the same list, 7841 // except that the aforementioned are allowed in unevaluated 7842 // expressions. Everything else falls under the 7843 // "may accept other forms of constant expressions" exception. 7844 // (We never end up here for C++, so the constant expression 7845 // rules there don't matter.) 7846 if (Init->isConstantInitializer(Context, false)) 7847 return false; 7848 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7849 << Init->getSourceRange(); 7850 return true; 7851 } 7852 7853 namespace { 7854 // Visits an initialization expression to see if OrigDecl is evaluated in 7855 // its own initialization and throws a warning if it does. 7856 class SelfReferenceChecker 7857 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7858 Sema &S; 7859 Decl *OrigDecl; 7860 bool isRecordType; 7861 bool isPODType; 7862 bool isReferenceType; 7863 7864 public: 7865 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7866 7867 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7868 S(S), OrigDecl(OrigDecl) { 7869 isPODType = false; 7870 isRecordType = false; 7871 isReferenceType = false; 7872 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7873 isPODType = VD->getType().isPODType(S.Context); 7874 isRecordType = VD->getType()->isRecordType(); 7875 isReferenceType = VD->getType()->isReferenceType(); 7876 } 7877 } 7878 7879 // For most expressions, the cast is directly above the DeclRefExpr. 7880 // For conditional operators, the cast can be outside the conditional 7881 // operator if both expressions are DeclRefExpr's. 7882 void HandleValue(Expr *E) { 7883 if (isReferenceType) 7884 return; 7885 E = E->IgnoreParenImpCasts(); 7886 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7887 HandleDeclRefExpr(DRE); 7888 return; 7889 } 7890 7891 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7892 HandleValue(CO->getTrueExpr()); 7893 HandleValue(CO->getFalseExpr()); 7894 return; 7895 } 7896 7897 if (isa<MemberExpr>(E)) { 7898 Expr *Base = E->IgnoreParenImpCasts(); 7899 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7900 // Check for static member variables and don't warn on them. 7901 if (!isa<FieldDecl>(ME->getMemberDecl())) 7902 return; 7903 Base = ME->getBase()->IgnoreParenImpCasts(); 7904 } 7905 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7906 HandleDeclRefExpr(DRE); 7907 return; 7908 } 7909 } 7910 7911 // Reference types are handled here since all uses of references are 7912 // bad, not just r-value uses. 7913 void VisitDeclRefExpr(DeclRefExpr *E) { 7914 if (isReferenceType) 7915 HandleDeclRefExpr(E); 7916 } 7917 7918 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7919 if (E->getCastKind() == CK_LValueToRValue || 7920 (isRecordType && E->getCastKind() == CK_NoOp)) 7921 HandleValue(E->getSubExpr()); 7922 7923 Inherited::VisitImplicitCastExpr(E); 7924 } 7925 7926 void VisitMemberExpr(MemberExpr *E) { 7927 // Don't warn on arrays since they can be treated as pointers. 7928 if (E->getType()->canDecayToPointerType()) return; 7929 7930 // Warn when a non-static method call is followed by non-static member 7931 // field accesses, which is followed by a DeclRefExpr. 7932 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7933 bool Warn = (MD && !MD->isStatic()); 7934 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7935 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7936 if (!isa<FieldDecl>(ME->getMemberDecl())) 7937 Warn = false; 7938 Base = ME->getBase()->IgnoreParenImpCasts(); 7939 } 7940 7941 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7942 if (Warn) 7943 HandleDeclRefExpr(DRE); 7944 return; 7945 } 7946 7947 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7948 // Visit that expression. 7949 Visit(Base); 7950 } 7951 7952 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7953 if (E->getNumArgs() > 0) 7954 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7955 HandleDeclRefExpr(DRE); 7956 7957 Inherited::VisitCXXOperatorCallExpr(E); 7958 } 7959 7960 void VisitUnaryOperator(UnaryOperator *E) { 7961 // For POD record types, addresses of its own members are well-defined. 7962 if (E->getOpcode() == UO_AddrOf && isRecordType && 7963 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7964 if (!isPODType) 7965 HandleValue(E->getSubExpr()); 7966 return; 7967 } 7968 Inherited::VisitUnaryOperator(E); 7969 } 7970 7971 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7972 7973 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7974 Decl* ReferenceDecl = DRE->getDecl(); 7975 if (OrigDecl != ReferenceDecl) return; 7976 unsigned diag; 7977 if (isReferenceType) { 7978 diag = diag::warn_uninit_self_reference_in_reference_init; 7979 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7980 diag = diag::warn_static_self_reference_in_init; 7981 } else { 7982 diag = diag::warn_uninit_self_reference_in_init; 7983 } 7984 7985 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7986 S.PDiag(diag) 7987 << DRE->getNameInfo().getName() 7988 << OrigDecl->getLocation() 7989 << DRE->getSourceRange()); 7990 } 7991 }; 7992 7993 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 7994 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 7995 bool DirectInit) { 7996 // Parameters arguments are occassionially constructed with itself, 7997 // for instance, in recursive functions. Skip them. 7998 if (isa<ParmVarDecl>(OrigDecl)) 7999 return; 8000 8001 E = E->IgnoreParens(); 8002 8003 // Skip checking T a = a where T is not a record or reference type. 8004 // Doing so is a way to silence uninitialized warnings. 8005 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8006 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8007 if (ICE->getCastKind() == CK_LValueToRValue) 8008 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8009 if (DRE->getDecl() == OrigDecl) 8010 return; 8011 8012 SelfReferenceChecker(S, OrigDecl).Visit(E); 8013 } 8014 } 8015 8016 /// AddInitializerToDecl - Adds the initializer Init to the 8017 /// declaration dcl. If DirectInit is true, this is C++ direct 8018 /// initialization rather than copy initialization. 8019 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8020 bool DirectInit, bool TypeMayContainAuto) { 8021 // If there is no declaration, there was an error parsing it. Just ignore 8022 // the initializer. 8023 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8024 return; 8025 8026 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8027 // With declarators parsed the way they are, the parser cannot 8028 // distinguish between a normal initializer and a pure-specifier. 8029 // Thus this grotesque test. 8030 IntegerLiteral *IL; 8031 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8032 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8033 CheckPureMethod(Method, Init->getSourceRange()); 8034 else { 8035 Diag(Method->getLocation(), diag::err_member_function_initialization) 8036 << Method->getDeclName() << Init->getSourceRange(); 8037 Method->setInvalidDecl(); 8038 } 8039 return; 8040 } 8041 8042 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8043 if (!VDecl) { 8044 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8045 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8046 RealDecl->setInvalidDecl(); 8047 return; 8048 } 8049 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8050 8051 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8052 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8053 Expr *DeduceInit = Init; 8054 // Initializer could be a C++ direct-initializer. Deduction only works if it 8055 // contains exactly one expression. 8056 if (CXXDirectInit) { 8057 if (CXXDirectInit->getNumExprs() == 0) { 8058 // It isn't possible to write this directly, but it is possible to 8059 // end up in this situation with "auto x(some_pack...);" 8060 Diag(CXXDirectInit->getLocStart(), 8061 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8062 : diag::err_auto_var_init_no_expression) 8063 << VDecl->getDeclName() << VDecl->getType() 8064 << VDecl->getSourceRange(); 8065 RealDecl->setInvalidDecl(); 8066 return; 8067 } else if (CXXDirectInit->getNumExprs() > 1) { 8068 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8069 VDecl->isInitCapture() 8070 ? diag::err_init_capture_multiple_expressions 8071 : diag::err_auto_var_init_multiple_expressions) 8072 << VDecl->getDeclName() << VDecl->getType() 8073 << VDecl->getSourceRange(); 8074 RealDecl->setInvalidDecl(); 8075 return; 8076 } else { 8077 DeduceInit = CXXDirectInit->getExpr(0); 8078 } 8079 } 8080 8081 // Expressions default to 'id' when we're in a debugger. 8082 bool DefaultedToAuto = false; 8083 if (getLangOpts().DebuggerCastResultToId && 8084 Init->getType() == Context.UnknownAnyTy) { 8085 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8086 if (Result.isInvalid()) { 8087 VDecl->setInvalidDecl(); 8088 return; 8089 } 8090 Init = Result.take(); 8091 DefaultedToAuto = true; 8092 } 8093 8094 QualType DeducedType; 8095 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8096 DAR_Failed) 8097 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8098 if (DeducedType.isNull()) { 8099 RealDecl->setInvalidDecl(); 8100 return; 8101 } 8102 VDecl->setType(DeducedType); 8103 assert(VDecl->isLinkageValid()); 8104 8105 // In ARC, infer lifetime. 8106 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8107 VDecl->setInvalidDecl(); 8108 8109 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8110 // 'id' instead of a specific object type prevents most of our usual checks. 8111 // We only want to warn outside of template instantiations, though: 8112 // inside a template, the 'id' could have come from a parameter. 8113 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8114 DeducedType->isObjCIdType()) { 8115 SourceLocation Loc = 8116 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8117 Diag(Loc, diag::warn_auto_var_is_id) 8118 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8119 } 8120 8121 // If this is a redeclaration, check that the type we just deduced matches 8122 // the previously declared type. 8123 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8124 // We never need to merge the type, because we cannot form an incomplete 8125 // array of auto, nor deduce such a type. 8126 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8127 } 8128 8129 // Check the deduced type is valid for a variable declaration. 8130 CheckVariableDeclarationType(VDecl); 8131 if (VDecl->isInvalidDecl()) 8132 return; 8133 } 8134 8135 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8136 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8137 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8138 VDecl->setInvalidDecl(); 8139 return; 8140 } 8141 8142 if (!VDecl->getType()->isDependentType()) { 8143 // A definition must end up with a complete type, which means it must be 8144 // complete with the restriction that an array type might be completed by 8145 // the initializer; note that later code assumes this restriction. 8146 QualType BaseDeclType = VDecl->getType(); 8147 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8148 BaseDeclType = Array->getElementType(); 8149 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8150 diag::err_typecheck_decl_incomplete_type)) { 8151 RealDecl->setInvalidDecl(); 8152 return; 8153 } 8154 8155 // The variable can not have an abstract class type. 8156 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8157 diag::err_abstract_type_in_decl, 8158 AbstractVariableType)) 8159 VDecl->setInvalidDecl(); 8160 } 8161 8162 const VarDecl *Def; 8163 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8164 Diag(VDecl->getLocation(), diag::err_redefinition) 8165 << VDecl->getDeclName(); 8166 Diag(Def->getLocation(), diag::note_previous_definition); 8167 VDecl->setInvalidDecl(); 8168 return; 8169 } 8170 8171 const VarDecl* PrevInit = 0; 8172 if (getLangOpts().CPlusPlus) { 8173 // C++ [class.static.data]p4 8174 // If a static data member is of const integral or const 8175 // enumeration type, its declaration in the class definition can 8176 // specify a constant-initializer which shall be an integral 8177 // constant expression (5.19). In that case, the member can appear 8178 // in integral constant expressions. The member shall still be 8179 // defined in a namespace scope if it is used in the program and the 8180 // namespace scope definition shall not contain an initializer. 8181 // 8182 // We already performed a redefinition check above, but for static 8183 // data members we also need to check whether there was an in-class 8184 // declaration with an initializer. 8185 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8186 Diag(VDecl->getLocation(), diag::err_redefinition) 8187 << VDecl->getDeclName(); 8188 Diag(PrevInit->getLocation(), diag::note_previous_definition); 8189 return; 8190 } 8191 8192 if (VDecl->hasLocalStorage()) 8193 getCurFunction()->setHasBranchProtectedScope(); 8194 8195 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8196 VDecl->setInvalidDecl(); 8197 return; 8198 } 8199 } 8200 8201 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8202 // a kernel function cannot be initialized." 8203 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8204 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8205 VDecl->setInvalidDecl(); 8206 return; 8207 } 8208 8209 // Get the decls type and save a reference for later, since 8210 // CheckInitializerTypes may change it. 8211 QualType DclT = VDecl->getType(), SavT = DclT; 8212 8213 // Expressions default to 'id' when we're in a debugger 8214 // and we are assigning it to a variable of Objective-C pointer type. 8215 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8216 Init->getType() == Context.UnknownAnyTy) { 8217 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8218 if (Result.isInvalid()) { 8219 VDecl->setInvalidDecl(); 8220 return; 8221 } 8222 Init = Result.take(); 8223 } 8224 8225 // Perform the initialization. 8226 if (!VDecl->isInvalidDecl()) { 8227 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8228 InitializationKind Kind 8229 = DirectInit ? 8230 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8231 Init->getLocStart(), 8232 Init->getLocEnd()) 8233 : InitializationKind::CreateDirectList( 8234 VDecl->getLocation()) 8235 : InitializationKind::CreateCopy(VDecl->getLocation(), 8236 Init->getLocStart()); 8237 8238 MultiExprArg Args = Init; 8239 if (CXXDirectInit) 8240 Args = MultiExprArg(CXXDirectInit->getExprs(), 8241 CXXDirectInit->getNumExprs()); 8242 8243 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8244 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8245 if (Result.isInvalid()) { 8246 VDecl->setInvalidDecl(); 8247 return; 8248 } 8249 8250 Init = Result.takeAs<Expr>(); 8251 } 8252 8253 // Check for self-references within variable initializers. 8254 // Variables declared within a function/method body (except for references) 8255 // are handled by a dataflow analysis. 8256 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8257 VDecl->getType()->isReferenceType()) { 8258 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8259 } 8260 8261 // If the type changed, it means we had an incomplete type that was 8262 // completed by the initializer. For example: 8263 // int ary[] = { 1, 3, 5 }; 8264 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8265 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8266 VDecl->setType(DclT); 8267 8268 if (!VDecl->isInvalidDecl()) { 8269 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8270 8271 if (VDecl->hasAttr<BlocksAttr>()) 8272 checkRetainCycles(VDecl, Init); 8273 8274 // It is safe to assign a weak reference into a strong variable. 8275 // Although this code can still have problems: 8276 // id x = self.weakProp; 8277 // id y = self.weakProp; 8278 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8279 // paths through the function. This should be revisited if 8280 // -Wrepeated-use-of-weak is made flow-sensitive. 8281 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8282 DiagnosticsEngine::Level Level = 8283 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8284 Init->getLocStart()); 8285 if (Level != DiagnosticsEngine::Ignored) 8286 getCurFunction()->markSafeWeakUse(Init); 8287 } 8288 } 8289 8290 // The initialization is usually a full-expression. 8291 // 8292 // FIXME: If this is a braced initialization of an aggregate, it is not 8293 // an expression, and each individual field initializer is a separate 8294 // full-expression. For instance, in: 8295 // 8296 // struct Temp { ~Temp(); }; 8297 // struct S { S(Temp); }; 8298 // struct T { S a, b; } t = { Temp(), Temp() } 8299 // 8300 // we should destroy the first Temp before constructing the second. 8301 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8302 false, 8303 VDecl->isConstexpr()); 8304 if (Result.isInvalid()) { 8305 VDecl->setInvalidDecl(); 8306 return; 8307 } 8308 Init = Result.take(); 8309 8310 // Attach the initializer to the decl. 8311 VDecl->setInit(Init); 8312 8313 if (VDecl->isLocalVarDecl()) { 8314 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8315 // static storage duration shall be constant expressions or string literals. 8316 // C++ does not have this restriction. 8317 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8318 if (VDecl->getStorageClass() == SC_Static) 8319 CheckForConstantInitializer(Init, DclT); 8320 // C89 is stricter than C99 for non-static aggregate types. 8321 // C89 6.5.7p3: All the expressions [...] in an initializer list 8322 // for an object that has aggregate or union type shall be 8323 // constant expressions. 8324 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8325 isa<InitListExpr>(Init) && 8326 !Init->isConstantInitializer(Context, false)) 8327 Diag(Init->getExprLoc(), 8328 diag::ext_aggregate_init_not_constant) 8329 << Init->getSourceRange(); 8330 } 8331 } else if (VDecl->isStaticDataMember() && 8332 VDecl->getLexicalDeclContext()->isRecord()) { 8333 // This is an in-class initialization for a static data member, e.g., 8334 // 8335 // struct S { 8336 // static const int value = 17; 8337 // }; 8338 8339 // C++ [class.mem]p4: 8340 // A member-declarator can contain a constant-initializer only 8341 // if it declares a static member (9.4) of const integral or 8342 // const enumeration type, see 9.4.2. 8343 // 8344 // C++11 [class.static.data]p3: 8345 // If a non-volatile const static data member is of integral or 8346 // enumeration type, its declaration in the class definition can 8347 // specify a brace-or-equal-initializer in which every initalizer-clause 8348 // that is an assignment-expression is a constant expression. A static 8349 // data member of literal type can be declared in the class definition 8350 // with the constexpr specifier; if so, its declaration shall specify a 8351 // brace-or-equal-initializer in which every initializer-clause that is 8352 // an assignment-expression is a constant expression. 8353 8354 // Do nothing on dependent types. 8355 if (DclT->isDependentType()) { 8356 8357 // Allow any 'static constexpr' members, whether or not they are of literal 8358 // type. We separately check that every constexpr variable is of literal 8359 // type. 8360 } else if (VDecl->isConstexpr()) { 8361 8362 // Require constness. 8363 } else if (!DclT.isConstQualified()) { 8364 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8365 << Init->getSourceRange(); 8366 VDecl->setInvalidDecl(); 8367 8368 // We allow integer constant expressions in all cases. 8369 } else if (DclT->isIntegralOrEnumerationType()) { 8370 // Check whether the expression is a constant expression. 8371 SourceLocation Loc; 8372 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8373 // In C++11, a non-constexpr const static data member with an 8374 // in-class initializer cannot be volatile. 8375 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8376 else if (Init->isValueDependent()) 8377 ; // Nothing to check. 8378 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8379 ; // Ok, it's an ICE! 8380 else if (Init->isEvaluatable(Context)) { 8381 // If we can constant fold the initializer through heroics, accept it, 8382 // but report this as a use of an extension for -pedantic. 8383 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8384 << Init->getSourceRange(); 8385 } else { 8386 // Otherwise, this is some crazy unknown case. Report the issue at the 8387 // location provided by the isIntegerConstantExpr failed check. 8388 Diag(Loc, diag::err_in_class_initializer_non_constant) 8389 << Init->getSourceRange(); 8390 VDecl->setInvalidDecl(); 8391 } 8392 8393 // We allow foldable floating-point constants as an extension. 8394 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8395 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8396 // it anyway and provide a fixit to add the 'constexpr'. 8397 if (getLangOpts().CPlusPlus11) { 8398 Diag(VDecl->getLocation(), 8399 diag::ext_in_class_initializer_float_type_cxx11) 8400 << DclT << Init->getSourceRange(); 8401 Diag(VDecl->getLocStart(), 8402 diag::note_in_class_initializer_float_type_cxx11) 8403 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8404 } else { 8405 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8406 << DclT << Init->getSourceRange(); 8407 8408 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8409 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8410 << Init->getSourceRange(); 8411 VDecl->setInvalidDecl(); 8412 } 8413 } 8414 8415 // Suggest adding 'constexpr' in C++11 for literal types. 8416 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8417 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8418 << DclT << Init->getSourceRange() 8419 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8420 VDecl->setConstexpr(true); 8421 8422 } else { 8423 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8424 << DclT << Init->getSourceRange(); 8425 VDecl->setInvalidDecl(); 8426 } 8427 } else if (VDecl->isFileVarDecl()) { 8428 if (VDecl->getStorageClass() == SC_Extern && 8429 (!getLangOpts().CPlusPlus || 8430 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8431 VDecl->isExternC())) && 8432 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8433 Diag(VDecl->getLocation(), diag::warn_extern_init); 8434 8435 // C99 6.7.8p4. All file scoped initializers need to be constant. 8436 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8437 CheckForConstantInitializer(Init, DclT); 8438 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8439 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8440 !Init->isValueDependent() && !VDecl->isConstexpr() && 8441 !Init->isConstantInitializer( 8442 Context, VDecl->getType()->isReferenceType())) { 8443 // GNU C++98 edits for __thread, [basic.start.init]p4: 8444 // An object of thread storage duration shall not require dynamic 8445 // initialization. 8446 // FIXME: Need strict checking here. 8447 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8448 if (getLangOpts().CPlusPlus11) 8449 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8450 } 8451 } 8452 8453 // We will represent direct-initialization similarly to copy-initialization: 8454 // int x(1); -as-> int x = 1; 8455 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8456 // 8457 // Clients that want to distinguish between the two forms, can check for 8458 // direct initializer using VarDecl::getInitStyle(). 8459 // A major benefit is that clients that don't particularly care about which 8460 // exactly form was it (like the CodeGen) can handle both cases without 8461 // special case code. 8462 8463 // C++ 8.5p11: 8464 // The form of initialization (using parentheses or '=') is generally 8465 // insignificant, but does matter when the entity being initialized has a 8466 // class type. 8467 if (CXXDirectInit) { 8468 assert(DirectInit && "Call-style initializer must be direct init."); 8469 VDecl->setInitStyle(VarDecl::CallInit); 8470 } else if (DirectInit) { 8471 // This must be list-initialization. No other way is direct-initialization. 8472 VDecl->setInitStyle(VarDecl::ListInit); 8473 } 8474 8475 CheckCompleteVariableDeclaration(VDecl); 8476 } 8477 8478 /// ActOnInitializerError - Given that there was an error parsing an 8479 /// initializer for the given declaration, try to return to some form 8480 /// of sanity. 8481 void Sema::ActOnInitializerError(Decl *D) { 8482 // Our main concern here is re-establishing invariants like "a 8483 // variable's type is either dependent or complete". 8484 if (!D || D->isInvalidDecl()) return; 8485 8486 VarDecl *VD = dyn_cast<VarDecl>(D); 8487 if (!VD) return; 8488 8489 // Auto types are meaningless if we can't make sense of the initializer. 8490 if (ParsingInitForAutoVars.count(D)) { 8491 D->setInvalidDecl(); 8492 return; 8493 } 8494 8495 QualType Ty = VD->getType(); 8496 if (Ty->isDependentType()) return; 8497 8498 // Require a complete type. 8499 if (RequireCompleteType(VD->getLocation(), 8500 Context.getBaseElementType(Ty), 8501 diag::err_typecheck_decl_incomplete_type)) { 8502 VD->setInvalidDecl(); 8503 return; 8504 } 8505 8506 // Require an abstract type. 8507 if (RequireNonAbstractType(VD->getLocation(), Ty, 8508 diag::err_abstract_type_in_decl, 8509 AbstractVariableType)) { 8510 VD->setInvalidDecl(); 8511 return; 8512 } 8513 8514 // Don't bother complaining about constructors or destructors, 8515 // though. 8516 } 8517 8518 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8519 bool TypeMayContainAuto) { 8520 // If there is no declaration, there was an error parsing it. Just ignore it. 8521 if (RealDecl == 0) 8522 return; 8523 8524 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8525 QualType Type = Var->getType(); 8526 8527 // C++11 [dcl.spec.auto]p3 8528 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8529 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8530 << Var->getDeclName() << Type; 8531 Var->setInvalidDecl(); 8532 return; 8533 } 8534 8535 // C++11 [class.static.data]p3: A static data member can be declared with 8536 // the constexpr specifier; if so, its declaration shall specify 8537 // a brace-or-equal-initializer. 8538 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8539 // the definition of a variable [...] or the declaration of a static data 8540 // member. 8541 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8542 if (Var->isStaticDataMember()) 8543 Diag(Var->getLocation(), 8544 diag::err_constexpr_static_mem_var_requires_init) 8545 << Var->getDeclName(); 8546 else 8547 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8548 Var->setInvalidDecl(); 8549 return; 8550 } 8551 8552 switch (Var->isThisDeclarationADefinition()) { 8553 case VarDecl::Definition: 8554 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8555 break; 8556 8557 // We have an out-of-line definition of a static data member 8558 // that has an in-class initializer, so we type-check this like 8559 // a declaration. 8560 // 8561 // Fall through 8562 8563 case VarDecl::DeclarationOnly: 8564 // It's only a declaration. 8565 8566 // Block scope. C99 6.7p7: If an identifier for an object is 8567 // declared with no linkage (C99 6.2.2p6), the type for the 8568 // object shall be complete. 8569 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8570 !Var->hasLinkage() && !Var->isInvalidDecl() && 8571 RequireCompleteType(Var->getLocation(), Type, 8572 diag::err_typecheck_decl_incomplete_type)) 8573 Var->setInvalidDecl(); 8574 8575 // Make sure that the type is not abstract. 8576 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8577 RequireNonAbstractType(Var->getLocation(), Type, 8578 diag::err_abstract_type_in_decl, 8579 AbstractVariableType)) 8580 Var->setInvalidDecl(); 8581 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8582 Var->getStorageClass() == SC_PrivateExtern) { 8583 Diag(Var->getLocation(), diag::warn_private_extern); 8584 Diag(Var->getLocation(), diag::note_private_extern); 8585 } 8586 8587 return; 8588 8589 case VarDecl::TentativeDefinition: 8590 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8591 // object that has file scope without an initializer, and without a 8592 // storage-class specifier or with the storage-class specifier "static", 8593 // constitutes a tentative definition. Note: A tentative definition with 8594 // external linkage is valid (C99 6.2.2p5). 8595 if (!Var->isInvalidDecl()) { 8596 if (const IncompleteArrayType *ArrayT 8597 = Context.getAsIncompleteArrayType(Type)) { 8598 if (RequireCompleteType(Var->getLocation(), 8599 ArrayT->getElementType(), 8600 diag::err_illegal_decl_array_incomplete_type)) 8601 Var->setInvalidDecl(); 8602 } else if (Var->getStorageClass() == SC_Static) { 8603 // C99 6.9.2p3: If the declaration of an identifier for an object is 8604 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8605 // declared type shall not be an incomplete type. 8606 // NOTE: code such as the following 8607 // static struct s; 8608 // struct s { int a; }; 8609 // is accepted by gcc. Hence here we issue a warning instead of 8610 // an error and we do not invalidate the static declaration. 8611 // NOTE: to avoid multiple warnings, only check the first declaration. 8612 if (Var->isFirstDecl()) 8613 RequireCompleteType(Var->getLocation(), Type, 8614 diag::ext_typecheck_decl_incomplete_type); 8615 } 8616 } 8617 8618 // Record the tentative definition; we're done. 8619 if (!Var->isInvalidDecl()) 8620 TentativeDefinitions.push_back(Var); 8621 return; 8622 } 8623 8624 // Provide a specific diagnostic for uninitialized variable 8625 // definitions with incomplete array type. 8626 if (Type->isIncompleteArrayType()) { 8627 Diag(Var->getLocation(), 8628 diag::err_typecheck_incomplete_array_needs_initializer); 8629 Var->setInvalidDecl(); 8630 return; 8631 } 8632 8633 // Provide a specific diagnostic for uninitialized variable 8634 // definitions with reference type. 8635 if (Type->isReferenceType()) { 8636 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8637 << Var->getDeclName() 8638 << SourceRange(Var->getLocation(), Var->getLocation()); 8639 Var->setInvalidDecl(); 8640 return; 8641 } 8642 8643 // Do not attempt to type-check the default initializer for a 8644 // variable with dependent type. 8645 if (Type->isDependentType()) 8646 return; 8647 8648 if (Var->isInvalidDecl()) 8649 return; 8650 8651 if (RequireCompleteType(Var->getLocation(), 8652 Context.getBaseElementType(Type), 8653 diag::err_typecheck_decl_incomplete_type)) { 8654 Var->setInvalidDecl(); 8655 return; 8656 } 8657 8658 // The variable can not have an abstract class type. 8659 if (RequireNonAbstractType(Var->getLocation(), Type, 8660 diag::err_abstract_type_in_decl, 8661 AbstractVariableType)) { 8662 Var->setInvalidDecl(); 8663 return; 8664 } 8665 8666 // Check for jumps past the implicit initializer. C++0x 8667 // clarifies that this applies to a "variable with automatic 8668 // storage duration", not a "local variable". 8669 // C++11 [stmt.dcl]p3 8670 // A program that jumps from a point where a variable with automatic 8671 // storage duration is not in scope to a point where it is in scope is 8672 // ill-formed unless the variable has scalar type, class type with a 8673 // trivial default constructor and a trivial destructor, a cv-qualified 8674 // version of one of these types, or an array of one of the preceding 8675 // types and is declared without an initializer. 8676 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8677 if (const RecordType *Record 8678 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8679 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8680 // Mark the function for further checking even if the looser rules of 8681 // C++11 do not require such checks, so that we can diagnose 8682 // incompatibilities with C++98. 8683 if (!CXXRecord->isPOD()) 8684 getCurFunction()->setHasBranchProtectedScope(); 8685 } 8686 } 8687 8688 // C++03 [dcl.init]p9: 8689 // If no initializer is specified for an object, and the 8690 // object is of (possibly cv-qualified) non-POD class type (or 8691 // array thereof), the object shall be default-initialized; if 8692 // the object is of const-qualified type, the underlying class 8693 // type shall have a user-declared default 8694 // constructor. Otherwise, if no initializer is specified for 8695 // a non- static object, the object and its subobjects, if 8696 // any, have an indeterminate initial value); if the object 8697 // or any of its subobjects are of const-qualified type, the 8698 // program is ill-formed. 8699 // C++0x [dcl.init]p11: 8700 // If no initializer is specified for an object, the object is 8701 // default-initialized; [...]. 8702 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8703 InitializationKind Kind 8704 = InitializationKind::CreateDefault(Var->getLocation()); 8705 8706 InitializationSequence InitSeq(*this, Entity, Kind, None); 8707 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8708 if (Init.isInvalid()) 8709 Var->setInvalidDecl(); 8710 else if (Init.get()) { 8711 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8712 // This is important for template substitution. 8713 Var->setInitStyle(VarDecl::CallInit); 8714 } 8715 8716 CheckCompleteVariableDeclaration(Var); 8717 } 8718 } 8719 8720 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8721 VarDecl *VD = dyn_cast<VarDecl>(D); 8722 if (!VD) { 8723 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8724 D->setInvalidDecl(); 8725 return; 8726 } 8727 8728 VD->setCXXForRangeDecl(true); 8729 8730 // for-range-declaration cannot be given a storage class specifier. 8731 int Error = -1; 8732 switch (VD->getStorageClass()) { 8733 case SC_None: 8734 break; 8735 case SC_Extern: 8736 Error = 0; 8737 break; 8738 case SC_Static: 8739 Error = 1; 8740 break; 8741 case SC_PrivateExtern: 8742 Error = 2; 8743 break; 8744 case SC_Auto: 8745 Error = 3; 8746 break; 8747 case SC_Register: 8748 Error = 4; 8749 break; 8750 case SC_OpenCLWorkGroupLocal: 8751 llvm_unreachable("Unexpected storage class"); 8752 } 8753 if (VD->isConstexpr()) 8754 Error = 5; 8755 if (Error != -1) { 8756 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8757 << VD->getDeclName() << Error; 8758 D->setInvalidDecl(); 8759 } 8760 } 8761 8762 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8763 if (var->isInvalidDecl()) return; 8764 8765 // In ARC, don't allow jumps past the implicit initialization of a 8766 // local retaining variable. 8767 if (getLangOpts().ObjCAutoRefCount && 8768 var->hasLocalStorage()) { 8769 switch (var->getType().getObjCLifetime()) { 8770 case Qualifiers::OCL_None: 8771 case Qualifiers::OCL_ExplicitNone: 8772 case Qualifiers::OCL_Autoreleasing: 8773 break; 8774 8775 case Qualifiers::OCL_Weak: 8776 case Qualifiers::OCL_Strong: 8777 getCurFunction()->setHasBranchProtectedScope(); 8778 break; 8779 } 8780 } 8781 8782 if (var->isThisDeclarationADefinition() && 8783 var->isExternallyVisible() && var->hasLinkage() && 8784 getDiagnostics().getDiagnosticLevel( 8785 diag::warn_missing_variable_declarations, 8786 var->getLocation())) { 8787 // Find a previous declaration that's not a definition. 8788 VarDecl *prev = var->getPreviousDecl(); 8789 while (prev && prev->isThisDeclarationADefinition()) 8790 prev = prev->getPreviousDecl(); 8791 8792 if (!prev) 8793 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8794 } 8795 8796 if (var->getTLSKind() == VarDecl::TLS_Static && 8797 var->getType().isDestructedType()) { 8798 // GNU C++98 edits for __thread, [basic.start.term]p3: 8799 // The type of an object with thread storage duration shall not 8800 // have a non-trivial destructor. 8801 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8802 if (getLangOpts().CPlusPlus11) 8803 Diag(var->getLocation(), diag::note_use_thread_local); 8804 } 8805 8806 // All the following checks are C++ only. 8807 if (!getLangOpts().CPlusPlus) return; 8808 8809 QualType type = var->getType(); 8810 if (type->isDependentType()) return; 8811 8812 // __block variables might require us to capture a copy-initializer. 8813 if (var->hasAttr<BlocksAttr>()) { 8814 // It's currently invalid to ever have a __block variable with an 8815 // array type; should we diagnose that here? 8816 8817 // Regardless, we don't want to ignore array nesting when 8818 // constructing this copy. 8819 if (type->isStructureOrClassType()) { 8820 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8821 SourceLocation poi = var->getLocation(); 8822 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8823 ExprResult result 8824 = PerformMoveOrCopyInitialization( 8825 InitializedEntity::InitializeBlock(poi, type, false), 8826 var, var->getType(), varRef, /*AllowNRVO=*/true); 8827 if (!result.isInvalid()) { 8828 result = MaybeCreateExprWithCleanups(result); 8829 Expr *init = result.takeAs<Expr>(); 8830 Context.setBlockVarCopyInits(var, init); 8831 } 8832 } 8833 } 8834 8835 Expr *Init = var->getInit(); 8836 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8837 QualType baseType = Context.getBaseElementType(type); 8838 8839 if (!var->getDeclContext()->isDependentContext() && 8840 Init && !Init->isValueDependent()) { 8841 if (IsGlobal && !var->isConstexpr() && 8842 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8843 var->getLocation()) 8844 != DiagnosticsEngine::Ignored) { 8845 // Warn about globals which don't have a constant initializer. Don't 8846 // warn about globals with a non-trivial destructor because we already 8847 // warned about them. 8848 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8849 if (!(RD && !RD->hasTrivialDestructor()) && 8850 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8851 Diag(var->getLocation(), diag::warn_global_constructor) 8852 << Init->getSourceRange(); 8853 } 8854 8855 if (var->isConstexpr()) { 8856 SmallVector<PartialDiagnosticAt, 8> Notes; 8857 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8858 SourceLocation DiagLoc = var->getLocation(); 8859 // If the note doesn't add any useful information other than a source 8860 // location, fold it into the primary diagnostic. 8861 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 8862 diag::note_invalid_subexpr_in_const_expr) { 8863 DiagLoc = Notes[0].first; 8864 Notes.clear(); 8865 } 8866 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 8867 << var << Init->getSourceRange(); 8868 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 8869 Diag(Notes[I].first, Notes[I].second); 8870 } 8871 } else if (var->isUsableInConstantExpressions(Context)) { 8872 // Check whether the initializer of a const variable of integral or 8873 // enumeration type is an ICE now, since we can't tell whether it was 8874 // initialized by a constant expression if we check later. 8875 var->checkInitIsICE(); 8876 } 8877 } 8878 8879 // Require the destructor. 8880 if (const RecordType *recordType = baseType->getAs<RecordType>()) 8881 FinalizeVarWithDestructor(var, recordType); 8882 } 8883 8884 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 8885 /// any semantic actions necessary after any initializer has been attached. 8886 void 8887 Sema::FinalizeDeclaration(Decl *ThisDecl) { 8888 // Note that we are no longer parsing the initializer for this declaration. 8889 ParsingInitForAutoVars.erase(ThisDecl); 8890 8891 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 8892 if (!VD) 8893 return; 8894 8895 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 8896 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 8897 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used"; 8898 VD->dropAttr<UsedAttr>(); 8899 } 8900 } 8901 8902 if (!VD->isInvalidDecl() && 8903 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 8904 if (const VarDecl *Def = VD->getDefinition()) { 8905 if (Def->hasAttr<AliasAttr>()) { 8906 Diag(VD->getLocation(), diag::err_tentative_after_alias) 8907 << VD->getDeclName(); 8908 Diag(Def->getLocation(), diag::note_previous_definition); 8909 VD->setInvalidDecl(); 8910 } 8911 } 8912 } 8913 8914 const DeclContext *DC = VD->getDeclContext(); 8915 // If there's a #pragma GCC visibility in scope, and this isn't a class 8916 // member, set the visibility of this variable. 8917 if (!DC->isRecord() && VD->isExternallyVisible()) 8918 AddPushedVisibilityAttribute(VD); 8919 8920 if (VD->isFileVarDecl()) 8921 MarkUnusedFileScopedDecl(VD); 8922 8923 // Now we have parsed the initializer and can update the table of magic 8924 // tag values. 8925 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8926 !VD->getType()->isIntegralOrEnumerationType()) 8927 return; 8928 8929 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8930 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8931 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8932 I != E; ++I) { 8933 const Expr *MagicValueExpr = VD->getInit(); 8934 if (!MagicValueExpr) { 8935 continue; 8936 } 8937 llvm::APSInt MagicValueInt; 8938 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8939 Diag(I->getRange().getBegin(), 8940 diag::err_type_tag_for_datatype_not_ice) 8941 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8942 continue; 8943 } 8944 if (MagicValueInt.getActiveBits() > 64) { 8945 Diag(I->getRange().getBegin(), 8946 diag::err_type_tag_for_datatype_too_large) 8947 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8948 continue; 8949 } 8950 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8951 RegisterTypeTagForDatatype(I->getArgumentKind(), 8952 MagicValue, 8953 I->getMatchingCType(), 8954 I->getLayoutCompatible(), 8955 I->getMustBeNull()); 8956 } 8957 } 8958 8959 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8960 ArrayRef<Decl *> Group) { 8961 SmallVector<Decl*, 8> Decls; 8962 8963 if (DS.isTypeSpecOwned()) 8964 Decls.push_back(DS.getRepAsDecl()); 8965 8966 DeclaratorDecl *FirstDeclaratorInGroup = 0; 8967 for (unsigned i = 0, e = Group.size(); i != e; ++i) 8968 if (Decl *D = Group[i]) { 8969 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 8970 if (!FirstDeclaratorInGroup) 8971 FirstDeclaratorInGroup = DD; 8972 Decls.push_back(D); 8973 } 8974 8975 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 8976 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 8977 HandleTagNumbering(*this, Tag); 8978 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 8979 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 8980 } 8981 } 8982 8983 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 8984 } 8985 8986 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 8987 /// group, performing any necessary semantic checking. 8988 Sema::DeclGroupPtrTy 8989 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 8990 bool TypeMayContainAuto) { 8991 // C++0x [dcl.spec.auto]p7: 8992 // If the type deduced for the template parameter U is not the same in each 8993 // deduction, the program is ill-formed. 8994 // FIXME: When initializer-list support is added, a distinction is needed 8995 // between the deduced type U and the deduced type which 'auto' stands for. 8996 // auto a = 0, b = { 1, 2, 3 }; 8997 // is legal because the deduced type U is 'int' in both cases. 8998 if (TypeMayContainAuto && Group.size() > 1) { 8999 QualType Deduced; 9000 CanQualType DeducedCanon; 9001 VarDecl *DeducedDecl = 0; 9002 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9003 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9004 AutoType *AT = D->getType()->getContainedAutoType(); 9005 // Don't reissue diagnostics when instantiating a template. 9006 if (AT && D->isInvalidDecl()) 9007 break; 9008 QualType U = AT ? AT->getDeducedType() : QualType(); 9009 if (!U.isNull()) { 9010 CanQualType UCanon = Context.getCanonicalType(U); 9011 if (Deduced.isNull()) { 9012 Deduced = U; 9013 DeducedCanon = UCanon; 9014 DeducedDecl = D; 9015 } else if (DeducedCanon != UCanon) { 9016 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9017 diag::err_auto_different_deductions) 9018 << (AT->isDecltypeAuto() ? 1 : 0) 9019 << Deduced << DeducedDecl->getDeclName() 9020 << U << D->getDeclName() 9021 << DeducedDecl->getInit()->getSourceRange() 9022 << D->getInit()->getSourceRange(); 9023 D->setInvalidDecl(); 9024 break; 9025 } 9026 } 9027 } 9028 } 9029 } 9030 9031 ActOnDocumentableDecls(Group); 9032 9033 return DeclGroupPtrTy::make( 9034 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9035 } 9036 9037 void Sema::ActOnDocumentableDecl(Decl *D) { 9038 ActOnDocumentableDecls(D); 9039 } 9040 9041 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9042 // Don't parse the comment if Doxygen diagnostics are ignored. 9043 if (Group.empty() || !Group[0]) 9044 return; 9045 9046 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9047 Group[0]->getLocation()) 9048 == DiagnosticsEngine::Ignored) 9049 return; 9050 9051 if (Group.size() >= 2) { 9052 // This is a decl group. Normally it will contain only declarations 9053 // produced from declarator list. But in case we have any definitions or 9054 // additional declaration references: 9055 // 'typedef struct S {} S;' 9056 // 'typedef struct S *S;' 9057 // 'struct S *pS;' 9058 // FinalizeDeclaratorGroup adds these as separate declarations. 9059 Decl *MaybeTagDecl = Group[0]; 9060 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9061 Group = Group.slice(1); 9062 } 9063 } 9064 9065 // See if there are any new comments that are not attached to a decl. 9066 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9067 if (!Comments.empty() && 9068 !Comments.back()->isAttached()) { 9069 // There is at least one comment that not attached to a decl. 9070 // Maybe it should be attached to one of these decls? 9071 // 9072 // Note that this way we pick up not only comments that precede the 9073 // declaration, but also comments that *follow* the declaration -- thanks to 9074 // the lookahead in the lexer: we've consumed the semicolon and looked 9075 // ahead through comments. 9076 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9077 Context.getCommentForDecl(Group[i], &PP); 9078 } 9079 } 9080 9081 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9082 /// to introduce parameters into function prototype scope. 9083 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9084 const DeclSpec &DS = D.getDeclSpec(); 9085 9086 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9087 9088 // C++03 [dcl.stc]p2 also permits 'auto'. 9089 VarDecl::StorageClass StorageClass = SC_None; 9090 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9091 StorageClass = SC_Register; 9092 } else if (getLangOpts().CPlusPlus && 9093 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9094 StorageClass = SC_Auto; 9095 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9096 Diag(DS.getStorageClassSpecLoc(), 9097 diag::err_invalid_storage_class_in_func_decl); 9098 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9099 } 9100 9101 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9102 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9103 << DeclSpec::getSpecifierName(TSCS); 9104 if (DS.isConstexprSpecified()) 9105 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9106 << 0; 9107 9108 DiagnoseFunctionSpecifiers(DS); 9109 9110 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9111 QualType parmDeclType = TInfo->getType(); 9112 9113 if (getLangOpts().CPlusPlus) { 9114 // Check that there are no default arguments inside the type of this 9115 // parameter. 9116 CheckExtraCXXDefaultArguments(D); 9117 9118 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9119 if (D.getCXXScopeSpec().isSet()) { 9120 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9121 << D.getCXXScopeSpec().getRange(); 9122 D.getCXXScopeSpec().clear(); 9123 } 9124 } 9125 9126 // Ensure we have a valid name 9127 IdentifierInfo *II = 0; 9128 if (D.hasName()) { 9129 II = D.getIdentifier(); 9130 if (!II) { 9131 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9132 << GetNameForDeclarator(D).getName().getAsString(); 9133 D.setInvalidType(true); 9134 } 9135 } 9136 9137 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9138 if (II) { 9139 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9140 ForRedeclaration); 9141 LookupName(R, S); 9142 if (R.isSingleResult()) { 9143 NamedDecl *PrevDecl = R.getFoundDecl(); 9144 if (PrevDecl->isTemplateParameter()) { 9145 // Maybe we will complain about the shadowed template parameter. 9146 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9147 // Just pretend that we didn't see the previous declaration. 9148 PrevDecl = 0; 9149 } else if (S->isDeclScope(PrevDecl)) { 9150 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9151 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9152 9153 // Recover by removing the name 9154 II = 0; 9155 D.SetIdentifier(0, D.getIdentifierLoc()); 9156 D.setInvalidType(true); 9157 } 9158 } 9159 } 9160 9161 // Temporarily put parameter variables in the translation unit, not 9162 // the enclosing context. This prevents them from accidentally 9163 // looking like class members in C++. 9164 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9165 D.getLocStart(), 9166 D.getIdentifierLoc(), II, 9167 parmDeclType, TInfo, 9168 StorageClass); 9169 9170 if (D.isInvalidType()) 9171 New->setInvalidDecl(); 9172 9173 assert(S->isFunctionPrototypeScope()); 9174 assert(S->getFunctionPrototypeDepth() >= 1); 9175 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9176 S->getNextFunctionPrototypeIndex()); 9177 9178 // Add the parameter declaration into this scope. 9179 S->AddDecl(New); 9180 if (II) 9181 IdResolver.AddDecl(New); 9182 9183 ProcessDeclAttributes(S, New, D); 9184 9185 if (D.getDeclSpec().isModulePrivateSpecified()) 9186 Diag(New->getLocation(), diag::err_module_private_local) 9187 << 1 << New->getDeclName() 9188 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9189 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9190 9191 if (New->hasAttr<BlocksAttr>()) { 9192 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9193 } 9194 return New; 9195 } 9196 9197 /// \brief Synthesizes a variable for a parameter arising from a 9198 /// typedef. 9199 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9200 SourceLocation Loc, 9201 QualType T) { 9202 /* FIXME: setting StartLoc == Loc. 9203 Would it be worth to modify callers so as to provide proper source 9204 location for the unnamed parameters, embedding the parameter's type? */ 9205 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9206 T, Context.getTrivialTypeSourceInfo(T, Loc), 9207 SC_None, 0); 9208 Param->setImplicit(); 9209 return Param; 9210 } 9211 9212 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9213 ParmVarDecl * const *ParamEnd) { 9214 // Don't diagnose unused-parameter errors in template instantiations; we 9215 // will already have done so in the template itself. 9216 if (!ActiveTemplateInstantiations.empty()) 9217 return; 9218 9219 for (; Param != ParamEnd; ++Param) { 9220 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9221 !(*Param)->hasAttr<UnusedAttr>()) { 9222 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9223 << (*Param)->getDeclName(); 9224 } 9225 } 9226 } 9227 9228 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9229 ParmVarDecl * const *ParamEnd, 9230 QualType ReturnTy, 9231 NamedDecl *D) { 9232 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9233 return; 9234 9235 // Warn if the return value is pass-by-value and larger than the specified 9236 // threshold. 9237 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9238 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9239 if (Size > LangOpts.NumLargeByValueCopy) 9240 Diag(D->getLocation(), diag::warn_return_value_size) 9241 << D->getDeclName() << Size; 9242 } 9243 9244 // Warn if any parameter is pass-by-value and larger than the specified 9245 // threshold. 9246 for (; Param != ParamEnd; ++Param) { 9247 QualType T = (*Param)->getType(); 9248 if (T->isDependentType() || !T.isPODType(Context)) 9249 continue; 9250 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9251 if (Size > LangOpts.NumLargeByValueCopy) 9252 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9253 << (*Param)->getDeclName() << Size; 9254 } 9255 } 9256 9257 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9258 SourceLocation NameLoc, IdentifierInfo *Name, 9259 QualType T, TypeSourceInfo *TSInfo, 9260 VarDecl::StorageClass StorageClass) { 9261 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9262 if (getLangOpts().ObjCAutoRefCount && 9263 T.getObjCLifetime() == Qualifiers::OCL_None && 9264 T->isObjCLifetimeType()) { 9265 9266 Qualifiers::ObjCLifetime lifetime; 9267 9268 // Special cases for arrays: 9269 // - if it's const, use __unsafe_unretained 9270 // - otherwise, it's an error 9271 if (T->isArrayType()) { 9272 if (!T.isConstQualified()) { 9273 DelayedDiagnostics.add( 9274 sema::DelayedDiagnostic::makeForbiddenType( 9275 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9276 } 9277 lifetime = Qualifiers::OCL_ExplicitNone; 9278 } else { 9279 lifetime = T->getObjCARCImplicitLifetime(); 9280 } 9281 T = Context.getLifetimeQualifiedType(T, lifetime); 9282 } 9283 9284 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9285 Context.getAdjustedParameterType(T), 9286 TSInfo, 9287 StorageClass, 0); 9288 9289 // Parameters can not be abstract class types. 9290 // For record types, this is done by the AbstractClassUsageDiagnoser once 9291 // the class has been completely parsed. 9292 if (!CurContext->isRecord() && 9293 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9294 AbstractParamType)) 9295 New->setInvalidDecl(); 9296 9297 // Parameter declarators cannot be interface types. All ObjC objects are 9298 // passed by reference. 9299 if (T->isObjCObjectType()) { 9300 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9301 Diag(NameLoc, 9302 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9303 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9304 T = Context.getObjCObjectPointerType(T); 9305 New->setType(T); 9306 } 9307 9308 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9309 // duration shall not be qualified by an address-space qualifier." 9310 // Since all parameters have automatic store duration, they can not have 9311 // an address space. 9312 if (T.getAddressSpace() != 0) { 9313 Diag(NameLoc, diag::err_arg_with_address_space); 9314 New->setInvalidDecl(); 9315 } 9316 9317 return New; 9318 } 9319 9320 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9321 SourceLocation LocAfterDecls) { 9322 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9323 9324 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9325 // for a K&R function. 9326 if (!FTI.hasPrototype) { 9327 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 9328 --i; 9329 if (FTI.ArgInfo[i].Param == 0) { 9330 SmallString<256> Code; 9331 llvm::raw_svector_ostream(Code) << " int " 9332 << FTI.ArgInfo[i].Ident->getName() 9333 << ";\n"; 9334 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 9335 << FTI.ArgInfo[i].Ident 9336 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9337 9338 // Implicitly declare the argument as type 'int' for lack of a better 9339 // type. 9340 AttributeFactory attrs; 9341 DeclSpec DS(attrs); 9342 const char* PrevSpec; // unused 9343 unsigned DiagID; // unused 9344 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 9345 PrevSpec, DiagID); 9346 // Use the identifier location for the type source range. 9347 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 9348 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 9349 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9350 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 9351 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 9352 } 9353 } 9354 } 9355 } 9356 9357 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9358 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9359 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9360 Scope *ParentScope = FnBodyScope->getParent(); 9361 9362 D.setFunctionDefinitionKind(FDK_Definition); 9363 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9364 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9365 } 9366 9367 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9368 const FunctionDecl*& PossibleZeroParamPrototype) { 9369 // Don't warn about invalid declarations. 9370 if (FD->isInvalidDecl()) 9371 return false; 9372 9373 // Or declarations that aren't global. 9374 if (!FD->isGlobal()) 9375 return false; 9376 9377 // Don't warn about C++ member functions. 9378 if (isa<CXXMethodDecl>(FD)) 9379 return false; 9380 9381 // Don't warn about 'main'. 9382 if (FD->isMain()) 9383 return false; 9384 9385 // Don't warn about inline functions. 9386 if (FD->isInlined()) 9387 return false; 9388 9389 // Don't warn about function templates. 9390 if (FD->getDescribedFunctionTemplate()) 9391 return false; 9392 9393 // Don't warn about function template specializations. 9394 if (FD->isFunctionTemplateSpecialization()) 9395 return false; 9396 9397 // Don't warn for OpenCL kernels. 9398 if (FD->hasAttr<OpenCLKernelAttr>()) 9399 return false; 9400 9401 bool MissingPrototype = true; 9402 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9403 Prev; Prev = Prev->getPreviousDecl()) { 9404 // Ignore any declarations that occur in function or method 9405 // scope, because they aren't visible from the header. 9406 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9407 continue; 9408 9409 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9410 if (FD->getNumParams() == 0) 9411 PossibleZeroParamPrototype = Prev; 9412 break; 9413 } 9414 9415 return MissingPrototype; 9416 } 9417 9418 void 9419 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9420 const FunctionDecl *EffectiveDefinition) { 9421 // Don't complain if we're in GNU89 mode and the previous definition 9422 // was an extern inline function. 9423 const FunctionDecl *Definition = EffectiveDefinition; 9424 if (!Definition) 9425 if (!FD->isDefined(Definition)) 9426 return; 9427 9428 if (canRedefineFunction(Definition, getLangOpts())) 9429 return; 9430 9431 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9432 Definition->getStorageClass() == SC_Extern) 9433 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9434 << FD->getDeclName() << getLangOpts().CPlusPlus; 9435 else 9436 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9437 9438 Diag(Definition->getLocation(), diag::note_previous_definition); 9439 FD->setInvalidDecl(); 9440 } 9441 9442 9443 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9444 Sema &S) { 9445 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9446 9447 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9448 LSI->CallOperator = CallOperator; 9449 LSI->Lambda = LambdaClass; 9450 LSI->ReturnType = CallOperator->getResultType(); 9451 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9452 9453 if (LCD == LCD_None) 9454 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9455 else if (LCD == LCD_ByCopy) 9456 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9457 else if (LCD == LCD_ByRef) 9458 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9459 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9460 9461 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9462 LSI->Mutable = !CallOperator->isConst(); 9463 9464 // Add the captures to the LSI so they can be noted as already 9465 // captured within tryCaptureVar. 9466 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(), 9467 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) { 9468 if (C->capturesVariable()) { 9469 VarDecl *VD = C->getCapturedVar(); 9470 if (VD->isInitCapture()) 9471 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9472 QualType CaptureType = VD->getType(); 9473 const bool ByRef = C->getCaptureKind() == LCK_ByRef; 9474 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9475 /*RefersToEnclosingLocal*/true, C->getLocation(), 9476 /*EllipsisLoc*/C->isPackExpansion() 9477 ? C->getEllipsisLoc() : SourceLocation(), 9478 CaptureType, /*Expr*/ 0); 9479 9480 } else if (C->capturesThis()) { 9481 LSI->addThisCapture(/*Nested*/ false, C->getLocation(), 9482 S.getCurrentThisType(), /*Expr*/ 0); 9483 } 9484 } 9485 } 9486 9487 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9488 // Clear the last template instantiation error context. 9489 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9490 9491 if (!D) 9492 return D; 9493 FunctionDecl *FD = 0; 9494 9495 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9496 FD = FunTmpl->getTemplatedDecl(); 9497 else 9498 FD = cast<FunctionDecl>(D); 9499 // If we are instantiating a generic lambda call operator, push 9500 // a LambdaScopeInfo onto the function stack. But use the information 9501 // that's already been calculated (ActOnLambdaExpr) to prime the current 9502 // LambdaScopeInfo. 9503 // When the template operator is being specialized, the LambdaScopeInfo, 9504 // has to be properly restored so that tryCaptureVariable doesn't try 9505 // and capture any new variables. In addition when calculating potential 9506 // captures during transformation of nested lambdas, it is necessary to 9507 // have the LSI properly restored. 9508 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9509 assert(ActiveTemplateInstantiations.size() && 9510 "There should be an active template instantiation on the stack " 9511 "when instantiating a generic lambda!"); 9512 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9513 } 9514 else 9515 // Enter a new function scope 9516 PushFunctionScope(); 9517 9518 // See if this is a redefinition. 9519 if (!FD->isLateTemplateParsed()) 9520 CheckForFunctionRedefinition(FD); 9521 9522 // Builtin functions cannot be defined. 9523 if (unsigned BuiltinID = FD->getBuiltinID()) { 9524 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9525 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9526 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9527 FD->setInvalidDecl(); 9528 } 9529 } 9530 9531 // The return type of a function definition must be complete 9532 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9533 QualType ResultType = FD->getResultType(); 9534 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9535 !FD->isInvalidDecl() && 9536 RequireCompleteType(FD->getLocation(), ResultType, 9537 diag::err_func_def_incomplete_result)) 9538 FD->setInvalidDecl(); 9539 9540 // GNU warning -Wmissing-prototypes: 9541 // Warn if a global function is defined without a previous 9542 // prototype declaration. This warning is issued even if the 9543 // definition itself provides a prototype. The aim is to detect 9544 // global functions that fail to be declared in header files. 9545 const FunctionDecl *PossibleZeroParamPrototype = 0; 9546 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9547 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9548 9549 if (PossibleZeroParamPrototype) { 9550 // We found a declaration that is not a prototype, 9551 // but that could be a zero-parameter prototype 9552 if (TypeSourceInfo *TI = 9553 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9554 TypeLoc TL = TI->getTypeLoc(); 9555 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9556 Diag(PossibleZeroParamPrototype->getLocation(), 9557 diag::note_declaration_not_a_prototype) 9558 << PossibleZeroParamPrototype 9559 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9560 } 9561 } 9562 } 9563 9564 if (FnBodyScope) 9565 PushDeclContext(FnBodyScope, FD); 9566 9567 // Check the validity of our function parameters 9568 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9569 /*CheckParameterNames=*/true); 9570 9571 // Introduce our parameters into the function scope 9572 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 9573 ParmVarDecl *Param = FD->getParamDecl(p); 9574 Param->setOwningFunction(FD); 9575 9576 // If this has an identifier, add it to the scope stack. 9577 if (Param->getIdentifier() && FnBodyScope) { 9578 CheckShadow(FnBodyScope, Param); 9579 9580 PushOnScopeChains(Param, FnBodyScope); 9581 } 9582 } 9583 9584 // If we had any tags defined in the function prototype, 9585 // introduce them into the function scope. 9586 if (FnBodyScope) { 9587 for (ArrayRef<NamedDecl *>::iterator 9588 I = FD->getDeclsInPrototypeScope().begin(), 9589 E = FD->getDeclsInPrototypeScope().end(); 9590 I != E; ++I) { 9591 NamedDecl *D = *I; 9592 9593 // Some of these decls (like enums) may have been pinned to the translation unit 9594 // for lack of a real context earlier. If so, remove from the translation unit 9595 // and reattach to the current context. 9596 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9597 // Is the decl actually in the context? 9598 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 9599 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 9600 if (*DI == D) { 9601 Context.getTranslationUnitDecl()->removeDecl(D); 9602 break; 9603 } 9604 } 9605 // Either way, reassign the lexical decl context to our FunctionDecl. 9606 D->setLexicalDeclContext(CurContext); 9607 } 9608 9609 // If the decl has a non-null name, make accessible in the current scope. 9610 if (!D->getName().empty()) 9611 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9612 9613 // Similarly, dive into enums and fish their constants out, making them 9614 // accessible in this scope. 9615 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 9616 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 9617 EE = ED->enumerator_end(); EI != EE; ++EI) 9618 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 9619 } 9620 } 9621 } 9622 9623 // Ensure that the function's exception specification is instantiated. 9624 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9625 ResolveExceptionSpec(D->getLocation(), FPT); 9626 9627 // Checking attributes of current function definition 9628 // dllimport attribute. 9629 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9630 if (DA && (!FD->getAttr<DLLExportAttr>())) { 9631 // dllimport attribute cannot be directly applied to definition. 9632 // Microsoft accepts dllimport for functions defined within class scope. 9633 if (!DA->isInherited() && 9634 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9635 Diag(FD->getLocation(), 9636 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9637 << "dllimport"; 9638 FD->setInvalidDecl(); 9639 return D; 9640 } 9641 9642 // Visual C++ appears to not think this is an issue, so only issue 9643 // a warning when Microsoft extensions are disabled. 9644 if (!LangOpts.MicrosoftExt) { 9645 // If a symbol previously declared dllimport is later defined, the 9646 // attribute is ignored in subsequent references, and a warning is 9647 // emitted. 9648 Diag(FD->getLocation(), 9649 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 9650 << FD->getName() << "dllimport"; 9651 } 9652 } 9653 // We want to attach documentation to original Decl (which might be 9654 // a function template). 9655 ActOnDocumentableDecl(D); 9656 return D; 9657 } 9658 9659 /// \brief Given the set of return statements within a function body, 9660 /// compute the variables that are subject to the named return value 9661 /// optimization. 9662 /// 9663 /// Each of the variables that is subject to the named return value 9664 /// optimization will be marked as NRVO variables in the AST, and any 9665 /// return statement that has a marked NRVO variable as its NRVO candidate can 9666 /// use the named return value optimization. 9667 /// 9668 /// This function applies a very simplistic algorithm for NRVO: if every return 9669 /// statement in the function has the same NRVO candidate, that candidate is 9670 /// the NRVO variable. 9671 /// 9672 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9673 /// statements and the lifetimes of the NRVO candidates. We should be able to 9674 /// find a maximal set of NRVO variables. 9675 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9676 ReturnStmt **Returns = Scope->Returns.data(); 9677 9678 const VarDecl *NRVOCandidate = 0; 9679 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9680 if (!Returns[I]->getNRVOCandidate()) 9681 return; 9682 9683 if (!NRVOCandidate) 9684 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9685 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9686 return; 9687 } 9688 9689 if (NRVOCandidate) 9690 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9691 } 9692 9693 bool Sema::canSkipFunctionBody(Decl *D) { 9694 if (!Consumer.shouldSkipFunctionBody(D)) 9695 return false; 9696 9697 if (isa<ObjCMethodDecl>(D)) 9698 return true; 9699 9700 FunctionDecl *FD = 0; 9701 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 9702 FD = FTD->getTemplatedDecl(); 9703 else 9704 FD = cast<FunctionDecl>(D); 9705 9706 // We cannot skip the body of a function (or function template) which is 9707 // constexpr, since we may need to evaluate its body in order to parse the 9708 // rest of the file. 9709 // We cannot skip the body of a function with an undeduced return type, 9710 // because any callers of that function need to know the type. 9711 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType(); 9712 } 9713 9714 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9715 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9716 FD->setHasSkippedBody(); 9717 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9718 MD->setHasSkippedBody(); 9719 return ActOnFinishFunctionBody(Decl, 0); 9720 } 9721 9722 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9723 return ActOnFinishFunctionBody(D, BodyArg, false); 9724 } 9725 9726 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9727 bool IsInstantiation) { 9728 FunctionDecl *FD = 0; 9729 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 9730 if (FunTmpl) 9731 FD = FunTmpl->getTemplatedDecl(); 9732 else 9733 FD = dyn_cast_or_null<FunctionDecl>(dcl); 9734 9735 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9736 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9737 9738 if (FD) { 9739 FD->setBody(Body); 9740 9741 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9742 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) { 9743 // If the function has a deduced result type but contains no 'return' 9744 // statements, the result type as written must be exactly 'auto', and 9745 // the deduced result type is 'void'. 9746 if (!FD->getResultType()->getAs<AutoType>()) { 9747 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9748 << FD->getResultType(); 9749 FD->setInvalidDecl(); 9750 } else { 9751 // Substitute 'void' for the 'auto' in the type. 9752 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9753 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc(); 9754 Context.adjustDeducedFunctionResultType( 9755 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9756 } 9757 } 9758 9759 // The only way to be included in UndefinedButUsed is if there is an 9760 // ODR use before the definition. Avoid the expensive map lookup if this 9761 // is the first declaration. 9762 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9763 if (!FD->isExternallyVisible()) 9764 UndefinedButUsed.erase(FD); 9765 else if (FD->isInlined() && 9766 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9767 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9768 UndefinedButUsed.erase(FD); 9769 } 9770 9771 // If the function implicitly returns zero (like 'main') or is naked, 9772 // don't complain about missing return statements. 9773 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9774 WP.disableCheckFallThrough(); 9775 9776 // MSVC permits the use of pure specifier (=0) on function definition, 9777 // defined at class scope, warn about this non standard construct. 9778 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9779 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9780 9781 if (!FD->isInvalidDecl()) { 9782 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9783 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9784 FD->getResultType(), FD); 9785 9786 // If this is a constructor, we need a vtable. 9787 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9788 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9789 9790 // Try to apply the named return value optimization. We have to check 9791 // if we can do this here because lambdas keep return statements around 9792 // to deduce an implicit return type. 9793 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 9794 !FD->isDependentContext()) 9795 computeNRVO(Body, getCurFunction()); 9796 } 9797 9798 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9799 "Function parsing confused"); 9800 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9801 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9802 MD->setBody(Body); 9803 if (!MD->isInvalidDecl()) { 9804 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9805 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9806 MD->getResultType(), MD); 9807 9808 if (Body) 9809 computeNRVO(Body, getCurFunction()); 9810 } 9811 if (getCurFunction()->ObjCShouldCallSuper) { 9812 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9813 << MD->getSelector().getAsString(); 9814 getCurFunction()->ObjCShouldCallSuper = false; 9815 } 9816 } else { 9817 return 0; 9818 } 9819 9820 assert(!getCurFunction()->ObjCShouldCallSuper && 9821 "This should only be set for ObjC methods, which should have been " 9822 "handled in the block above."); 9823 9824 // Verify and clean out per-function state. 9825 if (Body) { 9826 // C++ constructors that have function-try-blocks can't have return 9827 // statements in the handlers of that block. (C++ [except.handle]p14) 9828 // Verify this. 9829 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 9830 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 9831 9832 // Verify that gotos and switch cases don't jump into scopes illegally. 9833 if (getCurFunction()->NeedsScopeChecking() && 9834 !dcl->isInvalidDecl() && 9835 !hasAnyUnrecoverableErrorsInThisFunction() && 9836 !PP.isCodeCompletionEnabled()) 9837 DiagnoseInvalidJumps(Body); 9838 9839 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 9840 if (!Destructor->getParent()->isDependentType()) 9841 CheckDestructor(Destructor); 9842 9843 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9844 Destructor->getParent()); 9845 } 9846 9847 // If any errors have occurred, clear out any temporaries that may have 9848 // been leftover. This ensures that these temporaries won't be picked up for 9849 // deletion in some later function. 9850 if (PP.getDiagnostics().hasErrorOccurred() || 9851 PP.getDiagnostics().getSuppressAllDiagnostics()) { 9852 DiscardCleanupsInEvaluationContext(); 9853 } 9854 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 9855 !isa<FunctionTemplateDecl>(dcl)) { 9856 // Since the body is valid, issue any analysis-based warnings that are 9857 // enabled. 9858 ActivePolicy = &WP; 9859 } 9860 9861 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 9862 (!CheckConstexprFunctionDecl(FD) || 9863 !CheckConstexprFunctionBody(FD, Body))) 9864 FD->setInvalidDecl(); 9865 9866 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 9867 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 9868 assert(MaybeODRUseExprs.empty() && 9869 "Leftover expressions for odr-use checking"); 9870 } 9871 9872 if (!IsInstantiation) 9873 PopDeclContext(); 9874 9875 PopFunctionScopeInfo(ActivePolicy, dcl); 9876 // If any errors have occurred, clear out any temporaries that may have 9877 // been leftover. This ensures that these temporaries won't be picked up for 9878 // deletion in some later function. 9879 if (getDiagnostics().hasErrorOccurred()) { 9880 DiscardCleanupsInEvaluationContext(); 9881 } 9882 9883 return dcl; 9884 } 9885 9886 9887 /// When we finish delayed parsing of an attribute, we must attach it to the 9888 /// relevant Decl. 9889 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 9890 ParsedAttributes &Attrs) { 9891 // Always attach attributes to the underlying decl. 9892 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9893 D = TD->getTemplatedDecl(); 9894 ProcessDeclAttributeList(S, D, Attrs.getList()); 9895 9896 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 9897 if (Method->isStatic()) 9898 checkThisInStaticMemberFunctionAttributes(Method); 9899 } 9900 9901 9902 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 9903 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 9904 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 9905 IdentifierInfo &II, Scope *S) { 9906 // Before we produce a declaration for an implicitly defined 9907 // function, see whether there was a locally-scoped declaration of 9908 // this name as a function or variable. If so, use that 9909 // (non-visible) declaration, and complain about it. 9910 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 9911 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 9912 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 9913 return ExternCPrev; 9914 } 9915 9916 // Extension in C99. Legal in C90, but warn about it. 9917 unsigned diag_id; 9918 if (II.getName().startswith("__builtin_")) 9919 diag_id = diag::warn_builtin_unknown; 9920 else if (getLangOpts().C99) 9921 diag_id = diag::ext_implicit_function_decl; 9922 else 9923 diag_id = diag::warn_implicit_function_decl; 9924 Diag(Loc, diag_id) << &II; 9925 9926 // Because typo correction is expensive, only do it if the implicit 9927 // function declaration is going to be treated as an error. 9928 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 9929 TypoCorrection Corrected; 9930 DeclFilterCCC<FunctionDecl> Validator; 9931 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 9932 LookupOrdinaryName, S, 0, Validator))) 9933 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 9934 /*ErrorRecovery*/false); 9935 } 9936 9937 // Set a Declarator for the implicit definition: int foo(); 9938 const char *Dummy; 9939 AttributeFactory attrFactory; 9940 DeclSpec DS(attrFactory); 9941 unsigned DiagID; 9942 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 9943 (void)Error; // Silence warning. 9944 assert(!Error && "Error setting up implicit decl!"); 9945 SourceLocation NoLoc; 9946 Declarator D(DS, Declarator::BlockContext); 9947 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 9948 /*IsAmbiguous=*/false, 9949 /*RParenLoc=*/NoLoc, 9950 /*ArgInfo=*/0, 9951 /*NumArgs=*/0, 9952 /*EllipsisLoc=*/NoLoc, 9953 /*RParenLoc=*/NoLoc, 9954 /*TypeQuals=*/0, 9955 /*RefQualifierIsLvalueRef=*/true, 9956 /*RefQualifierLoc=*/NoLoc, 9957 /*ConstQualifierLoc=*/NoLoc, 9958 /*VolatileQualifierLoc=*/NoLoc, 9959 /*MutableLoc=*/NoLoc, 9960 EST_None, 9961 /*ESpecLoc=*/NoLoc, 9962 /*Exceptions=*/0, 9963 /*ExceptionRanges=*/0, 9964 /*NumExceptions=*/0, 9965 /*NoexceptExpr=*/0, 9966 Loc, Loc, D), 9967 DS.getAttributes(), 9968 SourceLocation()); 9969 D.SetIdentifier(&II, Loc); 9970 9971 // Insert this function into translation-unit scope. 9972 9973 DeclContext *PrevDC = CurContext; 9974 CurContext = Context.getTranslationUnitDecl(); 9975 9976 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 9977 FD->setImplicit(); 9978 9979 CurContext = PrevDC; 9980 9981 AddKnownFunctionAttributes(FD); 9982 9983 return FD; 9984 } 9985 9986 /// \brief Adds any function attributes that we know a priori based on 9987 /// the declaration of this function. 9988 /// 9989 /// These attributes can apply both to implicitly-declared builtins 9990 /// (like __builtin___printf_chk) or to library-declared functions 9991 /// like NSLog or printf. 9992 /// 9993 /// We need to check for duplicate attributes both here and where user-written 9994 /// attributes are applied to declarations. 9995 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 9996 if (FD->isInvalidDecl()) 9997 return; 9998 9999 // If this is a built-in function, map its builtin attributes to 10000 // actual attributes. 10001 if (unsigned BuiltinID = FD->getBuiltinID()) { 10002 // Handle printf-formatting attributes. 10003 unsigned FormatIdx; 10004 bool HasVAListArg; 10005 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10006 if (!FD->getAttr<FormatAttr>()) { 10007 const char *fmt = "printf"; 10008 unsigned int NumParams = FD->getNumParams(); 10009 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10010 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10011 fmt = "NSString"; 10012 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10013 &Context.Idents.get(fmt), 10014 FormatIdx+1, 10015 HasVAListArg ? 0 : FormatIdx+2)); 10016 } 10017 } 10018 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10019 HasVAListArg)) { 10020 if (!FD->getAttr<FormatAttr>()) 10021 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10022 &Context.Idents.get("scanf"), 10023 FormatIdx+1, 10024 HasVAListArg ? 0 : FormatIdx+2)); 10025 } 10026 10027 // Mark const if we don't care about errno and that is the only 10028 // thing preventing the function from being const. This allows 10029 // IRgen to use LLVM intrinsics for such functions. 10030 if (!getLangOpts().MathErrno && 10031 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10032 if (!FD->getAttr<ConstAttr>()) 10033 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 10034 } 10035 10036 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10037 !FD->getAttr<ReturnsTwiceAttr>()) 10038 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 10039 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 10040 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 10041 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 10042 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 10043 } 10044 10045 IdentifierInfo *Name = FD->getIdentifier(); 10046 if (!Name) 10047 return; 10048 if ((!getLangOpts().CPlusPlus && 10049 FD->getDeclContext()->isTranslationUnit()) || 10050 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10051 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10052 LinkageSpecDecl::lang_c)) { 10053 // Okay: this could be a libc/libm/Objective-C function we know 10054 // about. 10055 } else 10056 return; 10057 10058 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10059 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10060 // target-specific builtins, perhaps? 10061 if (!FD->getAttr<FormatAttr>()) 10062 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10063 &Context.Idents.get("printf"), 2, 10064 Name->isStr("vasprintf") ? 0 : 3)); 10065 } 10066 10067 if (Name->isStr("__CFStringMakeConstantString")) { 10068 // We already have a __builtin___CFStringMakeConstantString, 10069 // but builds that use -fno-constant-cfstrings don't go through that. 10070 if (!FD->getAttr<FormatArgAttr>()) 10071 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 10072 } 10073 } 10074 10075 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10076 TypeSourceInfo *TInfo) { 10077 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10078 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10079 10080 if (!TInfo) { 10081 assert(D.isInvalidType() && "no declarator info for valid type"); 10082 TInfo = Context.getTrivialTypeSourceInfo(T); 10083 } 10084 10085 // Scope manipulation handled by caller. 10086 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10087 D.getLocStart(), 10088 D.getIdentifierLoc(), 10089 D.getIdentifier(), 10090 TInfo); 10091 10092 // Bail out immediately if we have an invalid declaration. 10093 if (D.isInvalidType()) { 10094 NewTD->setInvalidDecl(); 10095 return NewTD; 10096 } 10097 10098 if (D.getDeclSpec().isModulePrivateSpecified()) { 10099 if (CurContext->isFunctionOrMethod()) 10100 Diag(NewTD->getLocation(), diag::err_module_private_local) 10101 << 2 << NewTD->getDeclName() 10102 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10103 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10104 else 10105 NewTD->setModulePrivate(); 10106 } 10107 10108 // C++ [dcl.typedef]p8: 10109 // If the typedef declaration defines an unnamed class (or 10110 // enum), the first typedef-name declared by the declaration 10111 // to be that class type (or enum type) is used to denote the 10112 // class type (or enum type) for linkage purposes only. 10113 // We need to check whether the type was declared in the declaration. 10114 switch (D.getDeclSpec().getTypeSpecType()) { 10115 case TST_enum: 10116 case TST_struct: 10117 case TST_interface: 10118 case TST_union: 10119 case TST_class: { 10120 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10121 10122 // Do nothing if the tag is not anonymous or already has an 10123 // associated typedef (from an earlier typedef in this decl group). 10124 if (tagFromDeclSpec->getIdentifier()) break; 10125 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10126 10127 // A well-formed anonymous tag must always be a TUK_Definition. 10128 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10129 10130 // The type must match the tag exactly; no qualifiers allowed. 10131 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10132 break; 10133 10134 // Otherwise, set this is the anon-decl typedef for the tag. 10135 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10136 break; 10137 } 10138 10139 default: 10140 break; 10141 } 10142 10143 return NewTD; 10144 } 10145 10146 10147 /// \brief Check that this is a valid underlying type for an enum declaration. 10148 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10149 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10150 QualType T = TI->getType(); 10151 10152 if (T->isDependentType()) 10153 return false; 10154 10155 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10156 if (BT->isInteger()) 10157 return false; 10158 10159 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10160 return true; 10161 } 10162 10163 /// Check whether this is a valid redeclaration of a previous enumeration. 10164 /// \return true if the redeclaration was invalid. 10165 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10166 QualType EnumUnderlyingTy, 10167 const EnumDecl *Prev) { 10168 bool IsFixed = !EnumUnderlyingTy.isNull(); 10169 10170 if (IsScoped != Prev->isScoped()) { 10171 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10172 << Prev->isScoped(); 10173 Diag(Prev->getLocation(), diag::note_previous_use); 10174 return true; 10175 } 10176 10177 if (IsFixed && Prev->isFixed()) { 10178 if (!EnumUnderlyingTy->isDependentType() && 10179 !Prev->getIntegerType()->isDependentType() && 10180 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10181 Prev->getIntegerType())) { 10182 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10183 << EnumUnderlyingTy << Prev->getIntegerType(); 10184 Diag(Prev->getLocation(), diag::note_previous_use); 10185 return true; 10186 } 10187 } else if (IsFixed != Prev->isFixed()) { 10188 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10189 << Prev->isFixed(); 10190 Diag(Prev->getLocation(), diag::note_previous_use); 10191 return true; 10192 } 10193 10194 return false; 10195 } 10196 10197 /// \brief Get diagnostic %select index for tag kind for 10198 /// redeclaration diagnostic message. 10199 /// WARNING: Indexes apply to particular diagnostics only! 10200 /// 10201 /// \returns diagnostic %select index. 10202 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10203 switch (Tag) { 10204 case TTK_Struct: return 0; 10205 case TTK_Interface: return 1; 10206 case TTK_Class: return 2; 10207 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10208 } 10209 } 10210 10211 /// \brief Determine if tag kind is a class-key compatible with 10212 /// class for redeclaration (class, struct, or __interface). 10213 /// 10214 /// \returns true iff the tag kind is compatible. 10215 static bool isClassCompatTagKind(TagTypeKind Tag) 10216 { 10217 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10218 } 10219 10220 /// \brief Determine whether a tag with a given kind is acceptable 10221 /// as a redeclaration of the given tag declaration. 10222 /// 10223 /// \returns true if the new tag kind is acceptable, false otherwise. 10224 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10225 TagTypeKind NewTag, bool isDefinition, 10226 SourceLocation NewTagLoc, 10227 const IdentifierInfo &Name) { 10228 // C++ [dcl.type.elab]p3: 10229 // The class-key or enum keyword present in the 10230 // elaborated-type-specifier shall agree in kind with the 10231 // declaration to which the name in the elaborated-type-specifier 10232 // refers. This rule also applies to the form of 10233 // elaborated-type-specifier that declares a class-name or 10234 // friend class since it can be construed as referring to the 10235 // definition of the class. Thus, in any 10236 // elaborated-type-specifier, the enum keyword shall be used to 10237 // refer to an enumeration (7.2), the union class-key shall be 10238 // used to refer to a union (clause 9), and either the class or 10239 // struct class-key shall be used to refer to a class (clause 9) 10240 // declared using the class or struct class-key. 10241 TagTypeKind OldTag = Previous->getTagKind(); 10242 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10243 if (OldTag == NewTag) 10244 return true; 10245 10246 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10247 // Warn about the struct/class tag mismatch. 10248 bool isTemplate = false; 10249 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10250 isTemplate = Record->getDescribedClassTemplate(); 10251 10252 if (!ActiveTemplateInstantiations.empty()) { 10253 // In a template instantiation, do not offer fix-its for tag mismatches 10254 // since they usually mess up the template instead of fixing the problem. 10255 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10256 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10257 << getRedeclDiagFromTagKind(OldTag); 10258 return true; 10259 } 10260 10261 if (isDefinition) { 10262 // On definitions, check previous tags and issue a fix-it for each 10263 // one that doesn't match the current tag. 10264 if (Previous->getDefinition()) { 10265 // Don't suggest fix-its for redefinitions. 10266 return true; 10267 } 10268 10269 bool previousMismatch = false; 10270 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 10271 E(Previous->redecls_end()); I != E; ++I) { 10272 if (I->getTagKind() != NewTag) { 10273 if (!previousMismatch) { 10274 previousMismatch = true; 10275 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10276 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10277 << getRedeclDiagFromTagKind(I->getTagKind()); 10278 } 10279 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10280 << getRedeclDiagFromTagKind(NewTag) 10281 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10282 TypeWithKeyword::getTagTypeKindName(NewTag)); 10283 } 10284 } 10285 return true; 10286 } 10287 10288 // Check for a previous definition. If current tag and definition 10289 // are same type, do nothing. If no definition, but disagree with 10290 // with previous tag type, give a warning, but no fix-it. 10291 const TagDecl *Redecl = Previous->getDefinition() ? 10292 Previous->getDefinition() : Previous; 10293 if (Redecl->getTagKind() == NewTag) { 10294 return true; 10295 } 10296 10297 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10298 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10299 << getRedeclDiagFromTagKind(OldTag); 10300 Diag(Redecl->getLocation(), diag::note_previous_use); 10301 10302 // If there is a previous defintion, suggest a fix-it. 10303 if (Previous->getDefinition()) { 10304 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10305 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10306 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10307 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10308 } 10309 10310 return true; 10311 } 10312 return false; 10313 } 10314 10315 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10316 /// former case, Name will be non-null. In the later case, Name will be null. 10317 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10318 /// reference/declaration/definition of a tag. 10319 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10320 SourceLocation KWLoc, CXXScopeSpec &SS, 10321 IdentifierInfo *Name, SourceLocation NameLoc, 10322 AttributeList *Attr, AccessSpecifier AS, 10323 SourceLocation ModulePrivateLoc, 10324 MultiTemplateParamsArg TemplateParameterLists, 10325 bool &OwnedDecl, bool &IsDependent, 10326 SourceLocation ScopedEnumKWLoc, 10327 bool ScopedEnumUsesClassTag, 10328 TypeResult UnderlyingType) { 10329 // If this is not a definition, it must have a name. 10330 IdentifierInfo *OrigName = Name; 10331 assert((Name != 0 || TUK == TUK_Definition) && 10332 "Nameless record must be a definition!"); 10333 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10334 10335 OwnedDecl = false; 10336 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10337 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10338 10339 // FIXME: Check explicit specializations more carefully. 10340 bool isExplicitSpecialization = false; 10341 bool Invalid = false; 10342 10343 // We only need to do this matching if we have template parameters 10344 // or a scope specifier, which also conveniently avoids this work 10345 // for non-C++ cases. 10346 if (TemplateParameterLists.size() > 0 || 10347 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10348 if (TemplateParameterList *TemplateParams = 10349 MatchTemplateParametersToScopeSpecifier( 10350 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10351 isExplicitSpecialization, Invalid)) { 10352 if (Kind == TTK_Enum) { 10353 Diag(KWLoc, diag::err_enum_template); 10354 return 0; 10355 } 10356 10357 if (TemplateParams->size() > 0) { 10358 // This is a declaration or definition of a class template (which may 10359 // be a member of another template). 10360 10361 if (Invalid) 10362 return 0; 10363 10364 OwnedDecl = false; 10365 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10366 SS, Name, NameLoc, Attr, 10367 TemplateParams, AS, 10368 ModulePrivateLoc, 10369 TemplateParameterLists.size()-1, 10370 TemplateParameterLists.data()); 10371 return Result.get(); 10372 } else { 10373 // The "template<>" header is extraneous. 10374 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10375 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10376 isExplicitSpecialization = true; 10377 } 10378 } 10379 } 10380 10381 // Figure out the underlying type if this a enum declaration. We need to do 10382 // this early, because it's needed to detect if this is an incompatible 10383 // redeclaration. 10384 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10385 10386 if (Kind == TTK_Enum) { 10387 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10388 // No underlying type explicitly specified, or we failed to parse the 10389 // type, default to int. 10390 EnumUnderlying = Context.IntTy.getTypePtr(); 10391 else if (UnderlyingType.get()) { 10392 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10393 // integral type; any cv-qualification is ignored. 10394 TypeSourceInfo *TI = 0; 10395 GetTypeFromParser(UnderlyingType.get(), &TI); 10396 EnumUnderlying = TI; 10397 10398 if (CheckEnumUnderlyingType(TI)) 10399 // Recover by falling back to int. 10400 EnumUnderlying = Context.IntTy.getTypePtr(); 10401 10402 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10403 UPPC_FixedUnderlyingType)) 10404 EnumUnderlying = Context.IntTy.getTypePtr(); 10405 10406 } else if (getLangOpts().MicrosoftMode) 10407 // Microsoft enums are always of int type. 10408 EnumUnderlying = Context.IntTy.getTypePtr(); 10409 } 10410 10411 DeclContext *SearchDC = CurContext; 10412 DeclContext *DC = CurContext; 10413 bool isStdBadAlloc = false; 10414 10415 RedeclarationKind Redecl = ForRedeclaration; 10416 if (TUK == TUK_Friend || TUK == TUK_Reference) 10417 Redecl = NotForRedeclaration; 10418 10419 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10420 bool FriendSawTagOutsideEnclosingNamespace = false; 10421 if (Name && SS.isNotEmpty()) { 10422 // We have a nested-name tag ('struct foo::bar'). 10423 10424 // Check for invalid 'foo::'. 10425 if (SS.isInvalid()) { 10426 Name = 0; 10427 goto CreateNewDecl; 10428 } 10429 10430 // If this is a friend or a reference to a class in a dependent 10431 // context, don't try to make a decl for it. 10432 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10433 DC = computeDeclContext(SS, false); 10434 if (!DC) { 10435 IsDependent = true; 10436 return 0; 10437 } 10438 } else { 10439 DC = computeDeclContext(SS, true); 10440 if (!DC) { 10441 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10442 << SS.getRange(); 10443 return 0; 10444 } 10445 } 10446 10447 if (RequireCompleteDeclContext(SS, DC)) 10448 return 0; 10449 10450 SearchDC = DC; 10451 // Look-up name inside 'foo::'. 10452 LookupQualifiedName(Previous, DC); 10453 10454 if (Previous.isAmbiguous()) 10455 return 0; 10456 10457 if (Previous.empty()) { 10458 // Name lookup did not find anything. However, if the 10459 // nested-name-specifier refers to the current instantiation, 10460 // and that current instantiation has any dependent base 10461 // classes, we might find something at instantiation time: treat 10462 // this as a dependent elaborated-type-specifier. 10463 // But this only makes any sense for reference-like lookups. 10464 if (Previous.wasNotFoundInCurrentInstantiation() && 10465 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10466 IsDependent = true; 10467 return 0; 10468 } 10469 10470 // A tag 'foo::bar' must already exist. 10471 Diag(NameLoc, diag::err_not_tag_in_scope) 10472 << Kind << Name << DC << SS.getRange(); 10473 Name = 0; 10474 Invalid = true; 10475 goto CreateNewDecl; 10476 } 10477 } else if (Name) { 10478 // If this is a named struct, check to see if there was a previous forward 10479 // declaration or definition. 10480 // FIXME: We're looking into outer scopes here, even when we 10481 // shouldn't be. Doing so can result in ambiguities that we 10482 // shouldn't be diagnosing. 10483 LookupName(Previous, S); 10484 10485 // When declaring or defining a tag, ignore ambiguities introduced 10486 // by types using'ed into this scope. 10487 if (Previous.isAmbiguous() && 10488 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10489 LookupResult::Filter F = Previous.makeFilter(); 10490 while (F.hasNext()) { 10491 NamedDecl *ND = F.next(); 10492 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10493 F.erase(); 10494 } 10495 F.done(); 10496 } 10497 10498 // C++11 [namespace.memdef]p3: 10499 // If the name in a friend declaration is neither qualified nor 10500 // a template-id and the declaration is a function or an 10501 // elaborated-type-specifier, the lookup to determine whether 10502 // the entity has been previously declared shall not consider 10503 // any scopes outside the innermost enclosing namespace. 10504 // 10505 // Does it matter that this should be by scope instead of by 10506 // semantic context? 10507 if (!Previous.empty() && TUK == TUK_Friend) { 10508 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10509 LookupResult::Filter F = Previous.makeFilter(); 10510 while (F.hasNext()) { 10511 NamedDecl *ND = F.next(); 10512 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10513 if (DC->isFileContext() && 10514 !EnclosingNS->Encloses(ND->getDeclContext())) { 10515 F.erase(); 10516 FriendSawTagOutsideEnclosingNamespace = true; 10517 } 10518 } 10519 F.done(); 10520 } 10521 10522 // Note: there used to be some attempt at recovery here. 10523 if (Previous.isAmbiguous()) 10524 return 0; 10525 10526 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10527 // FIXME: This makes sure that we ignore the contexts associated 10528 // with C structs, unions, and enums when looking for a matching 10529 // tag declaration or definition. See the similar lookup tweak 10530 // in Sema::LookupName; is there a better way to deal with this? 10531 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10532 SearchDC = SearchDC->getParent(); 10533 } 10534 } else if (S->isFunctionPrototypeScope()) { 10535 // If this is an enum declaration in function prototype scope, set its 10536 // initial context to the translation unit. 10537 // FIXME: [citation needed] 10538 SearchDC = Context.getTranslationUnitDecl(); 10539 } 10540 10541 if (Previous.isSingleResult() && 10542 Previous.getFoundDecl()->isTemplateParameter()) { 10543 // Maybe we will complain about the shadowed template parameter. 10544 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10545 // Just pretend that we didn't see the previous declaration. 10546 Previous.clear(); 10547 } 10548 10549 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10550 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10551 // This is a declaration of or a reference to "std::bad_alloc". 10552 isStdBadAlloc = true; 10553 10554 if (Previous.empty() && StdBadAlloc) { 10555 // std::bad_alloc has been implicitly declared (but made invisible to 10556 // name lookup). Fill in this implicit declaration as the previous 10557 // declaration, so that the declarations get chained appropriately. 10558 Previous.addDecl(getStdBadAlloc()); 10559 } 10560 } 10561 10562 // If we didn't find a previous declaration, and this is a reference 10563 // (or friend reference), move to the correct scope. In C++, we 10564 // also need to do a redeclaration lookup there, just in case 10565 // there's a shadow friend decl. 10566 if (Name && Previous.empty() && 10567 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10568 if (Invalid) goto CreateNewDecl; 10569 assert(SS.isEmpty()); 10570 10571 if (TUK == TUK_Reference) { 10572 // C++ [basic.scope.pdecl]p5: 10573 // -- for an elaborated-type-specifier of the form 10574 // 10575 // class-key identifier 10576 // 10577 // if the elaborated-type-specifier is used in the 10578 // decl-specifier-seq or parameter-declaration-clause of a 10579 // function defined in namespace scope, the identifier is 10580 // declared as a class-name in the namespace that contains 10581 // the declaration; otherwise, except as a friend 10582 // declaration, the identifier is declared in the smallest 10583 // non-class, non-function-prototype scope that contains the 10584 // declaration. 10585 // 10586 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10587 // C structs and unions. 10588 // 10589 // It is an error in C++ to declare (rather than define) an enum 10590 // type, including via an elaborated type specifier. We'll 10591 // diagnose that later; for now, declare the enum in the same 10592 // scope as we would have picked for any other tag type. 10593 // 10594 // GNU C also supports this behavior as part of its incomplete 10595 // enum types extension, while GNU C++ does not. 10596 // 10597 // Find the context where we'll be declaring the tag. 10598 // FIXME: We would like to maintain the current DeclContext as the 10599 // lexical context, 10600 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10601 SearchDC = SearchDC->getParent(); 10602 10603 // Find the scope where we'll be declaring the tag. 10604 while (S->isClassScope() || 10605 (getLangOpts().CPlusPlus && 10606 S->isFunctionPrototypeScope()) || 10607 ((S->getFlags() & Scope::DeclScope) == 0) || 10608 (S->getEntity() && S->getEntity()->isTransparentContext())) 10609 S = S->getParent(); 10610 } else { 10611 assert(TUK == TUK_Friend); 10612 // C++ [namespace.memdef]p3: 10613 // If a friend declaration in a non-local class first declares a 10614 // class or function, the friend class or function is a member of 10615 // the innermost enclosing namespace. 10616 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10617 } 10618 10619 // In C++, we need to do a redeclaration lookup to properly 10620 // diagnose some problems. 10621 if (getLangOpts().CPlusPlus) { 10622 Previous.setRedeclarationKind(ForRedeclaration); 10623 LookupQualifiedName(Previous, SearchDC); 10624 } 10625 } 10626 10627 if (!Previous.empty()) { 10628 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 10629 10630 // It's okay to have a tag decl in the same scope as a typedef 10631 // which hides a tag decl in the same scope. Finding this 10632 // insanity with a redeclaration lookup can only actually happen 10633 // in C++. 10634 // 10635 // This is also okay for elaborated-type-specifiers, which is 10636 // technically forbidden by the current standard but which is 10637 // okay according to the likely resolution of an open issue; 10638 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10639 if (getLangOpts().CPlusPlus) { 10640 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10641 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10642 TagDecl *Tag = TT->getDecl(); 10643 if (Tag->getDeclName() == Name && 10644 Tag->getDeclContext()->getRedeclContext() 10645 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10646 PrevDecl = Tag; 10647 Previous.clear(); 10648 Previous.addDecl(Tag); 10649 Previous.resolveKind(); 10650 } 10651 } 10652 } 10653 } 10654 10655 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10656 // If this is a use of a previous tag, or if the tag is already declared 10657 // in the same scope (so that the definition/declaration completes or 10658 // rementions the tag), reuse the decl. 10659 if (TUK == TUK_Reference || TUK == TUK_Friend || 10660 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 10661 // Make sure that this wasn't declared as an enum and now used as a 10662 // struct or something similar. 10663 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10664 TUK == TUK_Definition, KWLoc, 10665 *Name)) { 10666 bool SafeToContinue 10667 = (PrevTagDecl->getTagKind() != TTK_Enum && 10668 Kind != TTK_Enum); 10669 if (SafeToContinue) 10670 Diag(KWLoc, diag::err_use_with_wrong_tag) 10671 << Name 10672 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10673 PrevTagDecl->getKindName()); 10674 else 10675 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10676 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10677 10678 if (SafeToContinue) 10679 Kind = PrevTagDecl->getTagKind(); 10680 else { 10681 // Recover by making this an anonymous redefinition. 10682 Name = 0; 10683 Previous.clear(); 10684 Invalid = true; 10685 } 10686 } 10687 10688 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10689 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10690 10691 // If this is an elaborated-type-specifier for a scoped enumeration, 10692 // the 'class' keyword is not necessary and not permitted. 10693 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10694 if (ScopedEnum) 10695 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10696 << PrevEnum->isScoped() 10697 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10698 return PrevTagDecl; 10699 } 10700 10701 QualType EnumUnderlyingTy; 10702 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10703 EnumUnderlyingTy = TI->getType(); 10704 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10705 EnumUnderlyingTy = QualType(T, 0); 10706 10707 // All conflicts with previous declarations are recovered by 10708 // returning the previous declaration, unless this is a definition, 10709 // in which case we want the caller to bail out. 10710 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10711 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10712 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10713 } 10714 10715 // C++11 [class.mem]p1: 10716 // A member shall not be declared twice in the member-specification, 10717 // except that a nested class or member class template can be declared 10718 // and then later defined. 10719 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10720 S->isDeclScope(PrevDecl)) { 10721 Diag(NameLoc, diag::ext_member_redeclared); 10722 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10723 } 10724 10725 if (!Invalid) { 10726 // If this is a use, just return the declaration we found. 10727 10728 // FIXME: In the future, return a variant or some other clue 10729 // for the consumer of this Decl to know it doesn't own it. 10730 // For our current ASTs this shouldn't be a problem, but will 10731 // need to be changed with DeclGroups. 10732 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10733 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10734 return PrevTagDecl; 10735 10736 // Diagnose attempts to redefine a tag. 10737 if (TUK == TUK_Definition) { 10738 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10739 // If we're defining a specialization and the previous definition 10740 // is from an implicit instantiation, don't emit an error 10741 // here; we'll catch this in the general case below. 10742 bool IsExplicitSpecializationAfterInstantiation = false; 10743 if (isExplicitSpecialization) { 10744 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10745 IsExplicitSpecializationAfterInstantiation = 10746 RD->getTemplateSpecializationKind() != 10747 TSK_ExplicitSpecialization; 10748 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10749 IsExplicitSpecializationAfterInstantiation = 10750 ED->getTemplateSpecializationKind() != 10751 TSK_ExplicitSpecialization; 10752 } 10753 10754 if (!IsExplicitSpecializationAfterInstantiation) { 10755 // A redeclaration in function prototype scope in C isn't 10756 // visible elsewhere, so merely issue a warning. 10757 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10758 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10759 else 10760 Diag(NameLoc, diag::err_redefinition) << Name; 10761 Diag(Def->getLocation(), diag::note_previous_definition); 10762 // If this is a redefinition, recover by making this 10763 // struct be anonymous, which will make any later 10764 // references get the previous definition. 10765 Name = 0; 10766 Previous.clear(); 10767 Invalid = true; 10768 } 10769 } else { 10770 // If the type is currently being defined, complain 10771 // about a nested redefinition. 10772 const TagType *Tag 10773 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10774 if (Tag->isBeingDefined()) { 10775 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10776 Diag(PrevTagDecl->getLocation(), 10777 diag::note_previous_definition); 10778 Name = 0; 10779 Previous.clear(); 10780 Invalid = true; 10781 } 10782 } 10783 10784 // Okay, this is definition of a previously declared or referenced 10785 // tag PrevDecl. We're going to create a new Decl for it. 10786 } 10787 } 10788 // If we get here we have (another) forward declaration or we 10789 // have a definition. Just create a new decl. 10790 10791 } else { 10792 // If we get here, this is a definition of a new tag type in a nested 10793 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 10794 // new decl/type. We set PrevDecl to NULL so that the entities 10795 // have distinct types. 10796 Previous.clear(); 10797 } 10798 // If we get here, we're going to create a new Decl. If PrevDecl 10799 // is non-NULL, it's a definition of the tag declared by 10800 // PrevDecl. If it's NULL, we have a new definition. 10801 10802 10803 // Otherwise, PrevDecl is not a tag, but was found with tag 10804 // lookup. This is only actually possible in C++, where a few 10805 // things like templates still live in the tag namespace. 10806 } else { 10807 // Use a better diagnostic if an elaborated-type-specifier 10808 // found the wrong kind of type on the first 10809 // (non-redeclaration) lookup. 10810 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 10811 !Previous.isForRedeclaration()) { 10812 unsigned Kind = 0; 10813 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10814 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10815 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10816 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 10817 Diag(PrevDecl->getLocation(), diag::note_declared_at); 10818 Invalid = true; 10819 10820 // Otherwise, only diagnose if the declaration is in scope. 10821 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 10822 isExplicitSpecialization)) { 10823 // do nothing 10824 10825 // Diagnose implicit declarations introduced by elaborated types. 10826 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 10827 unsigned Kind = 0; 10828 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10829 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10830 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10831 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 10832 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10833 Invalid = true; 10834 10835 // Otherwise it's a declaration. Call out a particularly common 10836 // case here. 10837 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10838 unsigned Kind = 0; 10839 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 10840 Diag(NameLoc, diag::err_tag_definition_of_typedef) 10841 << Name << Kind << TND->getUnderlyingType(); 10842 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10843 Invalid = true; 10844 10845 // Otherwise, diagnose. 10846 } else { 10847 // The tag name clashes with something else in the target scope, 10848 // issue an error and recover by making this tag be anonymous. 10849 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 10850 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10851 Name = 0; 10852 Invalid = true; 10853 } 10854 10855 // The existing declaration isn't relevant to us; we're in a 10856 // new scope, so clear out the previous declaration. 10857 Previous.clear(); 10858 } 10859 } 10860 10861 CreateNewDecl: 10862 10863 TagDecl *PrevDecl = 0; 10864 if (Previous.isSingleResult()) 10865 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 10866 10867 // If there is an identifier, use the location of the identifier as the 10868 // location of the decl, otherwise use the location of the struct/union 10869 // keyword. 10870 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 10871 10872 // Otherwise, create a new declaration. If there is a previous 10873 // declaration of the same entity, the two will be linked via 10874 // PrevDecl. 10875 TagDecl *New; 10876 10877 bool IsForwardReference = false; 10878 if (Kind == TTK_Enum) { 10879 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10880 // enum X { A, B, C } D; D should chain to X. 10881 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 10882 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 10883 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 10884 // If this is an undefined enum, warn. 10885 if (TUK != TUK_Definition && !Invalid) { 10886 TagDecl *Def; 10887 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 10888 cast<EnumDecl>(New)->isFixed()) { 10889 // C++0x: 7.2p2: opaque-enum-declaration. 10890 // Conflicts are diagnosed above. Do nothing. 10891 } 10892 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 10893 Diag(Loc, diag::ext_forward_ref_enum_def) 10894 << New; 10895 Diag(Def->getLocation(), diag::note_previous_definition); 10896 } else { 10897 unsigned DiagID = diag::ext_forward_ref_enum; 10898 if (getLangOpts().MicrosoftMode) 10899 DiagID = diag::ext_ms_forward_ref_enum; 10900 else if (getLangOpts().CPlusPlus) 10901 DiagID = diag::err_forward_ref_enum; 10902 Diag(Loc, DiagID); 10903 10904 // If this is a forward-declared reference to an enumeration, make a 10905 // note of it; we won't actually be introducing the declaration into 10906 // the declaration context. 10907 if (TUK == TUK_Reference) 10908 IsForwardReference = true; 10909 } 10910 } 10911 10912 if (EnumUnderlying) { 10913 EnumDecl *ED = cast<EnumDecl>(New); 10914 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10915 ED->setIntegerTypeSourceInfo(TI); 10916 else 10917 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 10918 ED->setPromotionType(ED->getIntegerType()); 10919 } 10920 10921 } else { 10922 // struct/union/class 10923 10924 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10925 // struct X { int A; } D; D should chain to X. 10926 if (getLangOpts().CPlusPlus) { 10927 // FIXME: Look for a way to use RecordDecl for simple structs. 10928 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10929 cast_or_null<CXXRecordDecl>(PrevDecl)); 10930 10931 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 10932 StdBadAlloc = cast<CXXRecordDecl>(New); 10933 } else 10934 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10935 cast_or_null<RecordDecl>(PrevDecl)); 10936 } 10937 10938 // Maybe add qualifier info. 10939 if (SS.isNotEmpty()) { 10940 if (SS.isSet()) { 10941 // If this is either a declaration or a definition, check the 10942 // nested-name-specifier against the current context. We don't do this 10943 // for explicit specializations, because they have similar checking 10944 // (with more specific diagnostics) in the call to 10945 // CheckMemberSpecialization, below. 10946 if (!isExplicitSpecialization && 10947 (TUK == TUK_Definition || TUK == TUK_Declaration) && 10948 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 10949 Invalid = true; 10950 10951 New->setQualifierInfo(SS.getWithLocInContext(Context)); 10952 if (TemplateParameterLists.size() > 0) { 10953 New->setTemplateParameterListsInfo(Context, 10954 TemplateParameterLists.size(), 10955 TemplateParameterLists.data()); 10956 } 10957 } 10958 else 10959 Invalid = true; 10960 } 10961 10962 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 10963 // Add alignment attributes if necessary; these attributes are checked when 10964 // the ASTContext lays out the structure. 10965 // 10966 // It is important for implementing the correct semantics that this 10967 // happen here (in act on tag decl). The #pragma pack stack is 10968 // maintained as a result of parser callbacks which can occur at 10969 // many points during the parsing of a struct declaration (because 10970 // the #pragma tokens are effectively skipped over during the 10971 // parsing of the struct). 10972 if (TUK == TUK_Definition) { 10973 AddAlignmentAttributesForRecord(RD); 10974 AddMsStructLayoutForRecord(RD); 10975 } 10976 } 10977 10978 if (ModulePrivateLoc.isValid()) { 10979 if (isExplicitSpecialization) 10980 Diag(New->getLocation(), diag::err_module_private_specialization) 10981 << 2 10982 << FixItHint::CreateRemoval(ModulePrivateLoc); 10983 // __module_private__ does not apply to local classes. However, we only 10984 // diagnose this as an error when the declaration specifiers are 10985 // freestanding. Here, we just ignore the __module_private__. 10986 else if (!SearchDC->isFunctionOrMethod()) 10987 New->setModulePrivate(); 10988 } 10989 10990 // If this is a specialization of a member class (of a class template), 10991 // check the specialization. 10992 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 10993 Invalid = true; 10994 10995 if (Invalid) 10996 New->setInvalidDecl(); 10997 10998 if (Attr) 10999 ProcessDeclAttributeList(S, New, Attr); 11000 11001 // If we're declaring or defining a tag in function prototype scope 11002 // in C, note that this type can only be used within the function. 11003 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 11004 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11005 11006 // Set the lexical context. If the tag has a C++ scope specifier, the 11007 // lexical context will be different from the semantic context. 11008 New->setLexicalDeclContext(CurContext); 11009 11010 // Mark this as a friend decl if applicable. 11011 // In Microsoft mode, a friend declaration also acts as a forward 11012 // declaration so we always pass true to setObjectOfFriendDecl to make 11013 // the tag name visible. 11014 if (TUK == TUK_Friend) 11015 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11016 getLangOpts().MicrosoftExt); 11017 11018 // Set the access specifier. 11019 if (!Invalid && SearchDC->isRecord()) 11020 SetMemberAccessSpecifier(New, PrevDecl, AS); 11021 11022 if (TUK == TUK_Definition) 11023 New->startDefinition(); 11024 11025 // If this has an identifier, add it to the scope stack. 11026 if (TUK == TUK_Friend) { 11027 // We might be replacing an existing declaration in the lookup tables; 11028 // if so, borrow its access specifier. 11029 if (PrevDecl) 11030 New->setAccess(PrevDecl->getAccess()); 11031 11032 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11033 DC->makeDeclVisibleInContext(New); 11034 if (Name) // can be null along some error paths 11035 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11036 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11037 } else if (Name) { 11038 S = getNonFieldDeclScope(S); 11039 PushOnScopeChains(New, S, !IsForwardReference); 11040 if (IsForwardReference) 11041 SearchDC->makeDeclVisibleInContext(New); 11042 11043 } else { 11044 CurContext->addDecl(New); 11045 } 11046 11047 // If this is the C FILE type, notify the AST context. 11048 if (IdentifierInfo *II = New->getIdentifier()) 11049 if (!New->isInvalidDecl() && 11050 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11051 II->isStr("FILE")) 11052 Context.setFILEDecl(New); 11053 11054 // If we were in function prototype scope (and not in C++ mode), add this 11055 // tag to the list of decls to inject into the function definition scope. 11056 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 11057 InFunctionDeclarator && Name) 11058 DeclsInPrototypeScope.push_back(New); 11059 11060 if (PrevDecl) 11061 mergeDeclAttributes(New, PrevDecl); 11062 11063 // If there's a #pragma GCC visibility in scope, set the visibility of this 11064 // record. 11065 AddPushedVisibilityAttribute(New); 11066 11067 OwnedDecl = true; 11068 // In C++, don't return an invalid declaration. We can't recover well from 11069 // the cases where we make the type anonymous. 11070 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11071 } 11072 11073 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11074 AdjustDeclIfTemplate(TagD); 11075 TagDecl *Tag = cast<TagDecl>(TagD); 11076 11077 // Enter the tag context. 11078 PushDeclContext(S, Tag); 11079 11080 ActOnDocumentableDecl(TagD); 11081 11082 // If there's a #pragma GCC visibility in scope, set the visibility of this 11083 // record. 11084 AddPushedVisibilityAttribute(Tag); 11085 } 11086 11087 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11088 assert(isa<ObjCContainerDecl>(IDecl) && 11089 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11090 DeclContext *OCD = cast<DeclContext>(IDecl); 11091 assert(getContainingDC(OCD) == CurContext && 11092 "The next DeclContext should be lexically contained in the current one."); 11093 CurContext = OCD; 11094 return IDecl; 11095 } 11096 11097 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11098 SourceLocation FinalLoc, 11099 bool IsFinalSpelledSealed, 11100 SourceLocation LBraceLoc) { 11101 AdjustDeclIfTemplate(TagD); 11102 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11103 11104 FieldCollector->StartClass(); 11105 11106 if (!Record->getIdentifier()) 11107 return; 11108 11109 if (FinalLoc.isValid()) 11110 Record->addAttr(new (Context) 11111 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11112 11113 // C++ [class]p2: 11114 // [...] The class-name is also inserted into the scope of the 11115 // class itself; this is known as the injected-class-name. For 11116 // purposes of access checking, the injected-class-name is treated 11117 // as if it were a public member name. 11118 CXXRecordDecl *InjectedClassName 11119 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11120 Record->getLocStart(), Record->getLocation(), 11121 Record->getIdentifier(), 11122 /*PrevDecl=*/0, 11123 /*DelayTypeCreation=*/true); 11124 Context.getTypeDeclType(InjectedClassName, Record); 11125 InjectedClassName->setImplicit(); 11126 InjectedClassName->setAccess(AS_public); 11127 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11128 InjectedClassName->setDescribedClassTemplate(Template); 11129 PushOnScopeChains(InjectedClassName, S); 11130 assert(InjectedClassName->isInjectedClassName() && 11131 "Broken injected-class-name"); 11132 } 11133 11134 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11135 SourceLocation RBraceLoc) { 11136 AdjustDeclIfTemplate(TagD); 11137 TagDecl *Tag = cast<TagDecl>(TagD); 11138 Tag->setRBraceLoc(RBraceLoc); 11139 11140 // Make sure we "complete" the definition even it is invalid. 11141 if (Tag->isBeingDefined()) { 11142 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11143 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11144 RD->completeDefinition(); 11145 } 11146 11147 if (isa<CXXRecordDecl>(Tag)) 11148 FieldCollector->FinishClass(); 11149 11150 // Exit this scope of this tag's definition. 11151 PopDeclContext(); 11152 11153 if (getCurLexicalContext()->isObjCContainer() && 11154 Tag->getDeclContext()->isFileContext()) 11155 Tag->setTopLevelDeclInObjCContainer(); 11156 11157 // Notify the consumer that we've defined a tag. 11158 if (!Tag->isInvalidDecl()) 11159 Consumer.HandleTagDeclDefinition(Tag); 11160 } 11161 11162 void Sema::ActOnObjCContainerFinishDefinition() { 11163 // Exit this scope of this interface definition. 11164 PopDeclContext(); 11165 } 11166 11167 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11168 assert(DC == CurContext && "Mismatch of container contexts"); 11169 OriginalLexicalContext = DC; 11170 ActOnObjCContainerFinishDefinition(); 11171 } 11172 11173 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11174 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11175 OriginalLexicalContext = 0; 11176 } 11177 11178 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11179 AdjustDeclIfTemplate(TagD); 11180 TagDecl *Tag = cast<TagDecl>(TagD); 11181 Tag->setInvalidDecl(); 11182 11183 // Make sure we "complete" the definition even it is invalid. 11184 if (Tag->isBeingDefined()) { 11185 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11186 RD->completeDefinition(); 11187 } 11188 11189 // We're undoing ActOnTagStartDefinition here, not 11190 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11191 // the FieldCollector. 11192 11193 PopDeclContext(); 11194 } 11195 11196 // Note that FieldName may be null for anonymous bitfields. 11197 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11198 IdentifierInfo *FieldName, 11199 QualType FieldTy, bool IsMsStruct, 11200 Expr *BitWidth, bool *ZeroWidth) { 11201 // Default to true; that shouldn't confuse checks for emptiness 11202 if (ZeroWidth) 11203 *ZeroWidth = true; 11204 11205 // C99 6.7.2.1p4 - verify the field type. 11206 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11207 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11208 // Handle incomplete types with specific error. 11209 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11210 return ExprError(); 11211 if (FieldName) 11212 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11213 << FieldName << FieldTy << BitWidth->getSourceRange(); 11214 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11215 << FieldTy << BitWidth->getSourceRange(); 11216 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11217 UPPC_BitFieldWidth)) 11218 return ExprError(); 11219 11220 // If the bit-width is type- or value-dependent, don't try to check 11221 // it now. 11222 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11223 return Owned(BitWidth); 11224 11225 llvm::APSInt Value; 11226 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11227 if (ICE.isInvalid()) 11228 return ICE; 11229 BitWidth = ICE.take(); 11230 11231 if (Value != 0 && ZeroWidth) 11232 *ZeroWidth = false; 11233 11234 // Zero-width bitfield is ok for anonymous field. 11235 if (Value == 0 && FieldName) 11236 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11237 11238 if (Value.isSigned() && Value.isNegative()) { 11239 if (FieldName) 11240 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11241 << FieldName << Value.toString(10); 11242 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11243 << Value.toString(10); 11244 } 11245 11246 if (!FieldTy->isDependentType()) { 11247 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11248 if (Value.getZExtValue() > TypeSize) { 11249 if (!getLangOpts().CPlusPlus || IsMsStruct) { 11250 if (FieldName) 11251 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11252 << FieldName << (unsigned)Value.getZExtValue() 11253 << (unsigned)TypeSize; 11254 11255 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11256 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11257 } 11258 11259 if (FieldName) 11260 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11261 << FieldName << (unsigned)Value.getZExtValue() 11262 << (unsigned)TypeSize; 11263 else 11264 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11265 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11266 } 11267 } 11268 11269 return Owned(BitWidth); 11270 } 11271 11272 /// ActOnField - Each field of a C struct/union is passed into this in order 11273 /// to create a FieldDecl object for it. 11274 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11275 Declarator &D, Expr *BitfieldWidth) { 11276 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11277 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11278 /*InitStyle=*/ICIS_NoInit, AS_public); 11279 return Res; 11280 } 11281 11282 /// HandleField - Analyze a field of a C struct or a C++ data member. 11283 /// 11284 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11285 SourceLocation DeclStart, 11286 Declarator &D, Expr *BitWidth, 11287 InClassInitStyle InitStyle, 11288 AccessSpecifier AS) { 11289 IdentifierInfo *II = D.getIdentifier(); 11290 SourceLocation Loc = DeclStart; 11291 if (II) Loc = D.getIdentifierLoc(); 11292 11293 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11294 QualType T = TInfo->getType(); 11295 if (getLangOpts().CPlusPlus) { 11296 CheckExtraCXXDefaultArguments(D); 11297 11298 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11299 UPPC_DataMemberType)) { 11300 D.setInvalidType(); 11301 T = Context.IntTy; 11302 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11303 } 11304 } 11305 11306 // TR 18037 does not allow fields to be declared with address spaces. 11307 if (T.getQualifiers().hasAddressSpace()) { 11308 Diag(Loc, diag::err_field_with_address_space); 11309 D.setInvalidType(); 11310 } 11311 11312 // OpenCL 1.2 spec, s6.9 r: 11313 // The event type cannot be used to declare a structure or union field. 11314 if (LangOpts.OpenCL && T->isEventT()) { 11315 Diag(Loc, diag::err_event_t_struct_field); 11316 D.setInvalidType(); 11317 } 11318 11319 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11320 11321 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11322 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11323 diag::err_invalid_thread) 11324 << DeclSpec::getSpecifierName(TSCS); 11325 11326 // Check to see if this name was declared as a member previously 11327 NamedDecl *PrevDecl = 0; 11328 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11329 LookupName(Previous, S); 11330 switch (Previous.getResultKind()) { 11331 case LookupResult::Found: 11332 case LookupResult::FoundUnresolvedValue: 11333 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11334 break; 11335 11336 case LookupResult::FoundOverloaded: 11337 PrevDecl = Previous.getRepresentativeDecl(); 11338 break; 11339 11340 case LookupResult::NotFound: 11341 case LookupResult::NotFoundInCurrentInstantiation: 11342 case LookupResult::Ambiguous: 11343 break; 11344 } 11345 Previous.suppressDiagnostics(); 11346 11347 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11348 // Maybe we will complain about the shadowed template parameter. 11349 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11350 // Just pretend that we didn't see the previous declaration. 11351 PrevDecl = 0; 11352 } 11353 11354 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11355 PrevDecl = 0; 11356 11357 bool Mutable 11358 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11359 SourceLocation TSSL = D.getLocStart(); 11360 FieldDecl *NewFD 11361 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11362 TSSL, AS, PrevDecl, &D); 11363 11364 if (NewFD->isInvalidDecl()) 11365 Record->setInvalidDecl(); 11366 11367 if (D.getDeclSpec().isModulePrivateSpecified()) 11368 NewFD->setModulePrivate(); 11369 11370 if (NewFD->isInvalidDecl() && PrevDecl) { 11371 // Don't introduce NewFD into scope; there's already something 11372 // with the same name in the same scope. 11373 } else if (II) { 11374 PushOnScopeChains(NewFD, S); 11375 } else 11376 Record->addDecl(NewFD); 11377 11378 return NewFD; 11379 } 11380 11381 /// \brief Build a new FieldDecl and check its well-formedness. 11382 /// 11383 /// This routine builds a new FieldDecl given the fields name, type, 11384 /// record, etc. \p PrevDecl should refer to any previous declaration 11385 /// with the same name and in the same scope as the field to be 11386 /// created. 11387 /// 11388 /// \returns a new FieldDecl. 11389 /// 11390 /// \todo The Declarator argument is a hack. It will be removed once 11391 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11392 TypeSourceInfo *TInfo, 11393 RecordDecl *Record, SourceLocation Loc, 11394 bool Mutable, Expr *BitWidth, 11395 InClassInitStyle InitStyle, 11396 SourceLocation TSSL, 11397 AccessSpecifier AS, NamedDecl *PrevDecl, 11398 Declarator *D) { 11399 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11400 bool InvalidDecl = false; 11401 if (D) InvalidDecl = D->isInvalidType(); 11402 11403 // If we receive a broken type, recover by assuming 'int' and 11404 // marking this declaration as invalid. 11405 if (T.isNull()) { 11406 InvalidDecl = true; 11407 T = Context.IntTy; 11408 } 11409 11410 QualType EltTy = Context.getBaseElementType(T); 11411 if (!EltTy->isDependentType()) { 11412 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11413 // Fields of incomplete type force their record to be invalid. 11414 Record->setInvalidDecl(); 11415 InvalidDecl = true; 11416 } else { 11417 NamedDecl *Def; 11418 EltTy->isIncompleteType(&Def); 11419 if (Def && Def->isInvalidDecl()) { 11420 Record->setInvalidDecl(); 11421 InvalidDecl = true; 11422 } 11423 } 11424 } 11425 11426 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11427 if (BitWidth && getLangOpts().OpenCL) { 11428 Diag(Loc, diag::err_opencl_bitfields); 11429 InvalidDecl = true; 11430 } 11431 11432 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11433 // than a variably modified type. 11434 if (!InvalidDecl && T->isVariablyModifiedType()) { 11435 bool SizeIsNegative; 11436 llvm::APSInt Oversized; 11437 11438 TypeSourceInfo *FixedTInfo = 11439 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11440 SizeIsNegative, 11441 Oversized); 11442 if (FixedTInfo) { 11443 Diag(Loc, diag::warn_illegal_constant_array_size); 11444 TInfo = FixedTInfo; 11445 T = FixedTInfo->getType(); 11446 } else { 11447 if (SizeIsNegative) 11448 Diag(Loc, diag::err_typecheck_negative_array_size); 11449 else if (Oversized.getBoolValue()) 11450 Diag(Loc, diag::err_array_too_large) 11451 << Oversized.toString(10); 11452 else 11453 Diag(Loc, diag::err_typecheck_field_variable_size); 11454 InvalidDecl = true; 11455 } 11456 } 11457 11458 // Fields can not have abstract class types 11459 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11460 diag::err_abstract_type_in_decl, 11461 AbstractFieldType)) 11462 InvalidDecl = true; 11463 11464 bool ZeroWidth = false; 11465 // If this is declared as a bit-field, check the bit-field. 11466 if (!InvalidDecl && BitWidth) { 11467 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11468 &ZeroWidth).take(); 11469 if (!BitWidth) { 11470 InvalidDecl = true; 11471 BitWidth = 0; 11472 ZeroWidth = false; 11473 } 11474 } 11475 11476 // Check that 'mutable' is consistent with the type of the declaration. 11477 if (!InvalidDecl && Mutable) { 11478 unsigned DiagID = 0; 11479 if (T->isReferenceType()) 11480 DiagID = diag::err_mutable_reference; 11481 else if (T.isConstQualified()) 11482 DiagID = diag::err_mutable_const; 11483 11484 if (DiagID) { 11485 SourceLocation ErrLoc = Loc; 11486 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11487 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11488 Diag(ErrLoc, DiagID); 11489 Mutable = false; 11490 InvalidDecl = true; 11491 } 11492 } 11493 11494 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11495 BitWidth, Mutable, InitStyle); 11496 if (InvalidDecl) 11497 NewFD->setInvalidDecl(); 11498 11499 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11500 Diag(Loc, diag::err_duplicate_member) << II; 11501 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11502 NewFD->setInvalidDecl(); 11503 } 11504 11505 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11506 if (Record->isUnion()) { 11507 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11508 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11509 if (RDecl->getDefinition()) { 11510 // C++ [class.union]p1: An object of a class with a non-trivial 11511 // constructor, a non-trivial copy constructor, a non-trivial 11512 // destructor, or a non-trivial copy assignment operator 11513 // cannot be a member of a union, nor can an array of such 11514 // objects. 11515 if (CheckNontrivialField(NewFD)) 11516 NewFD->setInvalidDecl(); 11517 } 11518 } 11519 11520 // C++ [class.union]p1: If a union contains a member of reference type, 11521 // the program is ill-formed, except when compiling with MSVC extensions 11522 // enabled. 11523 if (EltTy->isReferenceType()) { 11524 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11525 diag::ext_union_member_of_reference_type : 11526 diag::err_union_member_of_reference_type) 11527 << NewFD->getDeclName() << EltTy; 11528 if (!getLangOpts().MicrosoftExt) 11529 NewFD->setInvalidDecl(); 11530 } 11531 } 11532 } 11533 11534 // FIXME: We need to pass in the attributes given an AST 11535 // representation, not a parser representation. 11536 if (D) { 11537 // FIXME: The current scope is almost... but not entirely... correct here. 11538 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11539 11540 if (NewFD->hasAttrs()) 11541 CheckAlignasUnderalignment(NewFD); 11542 } 11543 11544 // In auto-retain/release, infer strong retension for fields of 11545 // retainable type. 11546 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11547 NewFD->setInvalidDecl(); 11548 11549 if (T.isObjCGCWeak()) 11550 Diag(Loc, diag::warn_attribute_weak_on_field); 11551 11552 NewFD->setAccess(AS); 11553 return NewFD; 11554 } 11555 11556 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11557 assert(FD); 11558 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11559 11560 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11561 return false; 11562 11563 QualType EltTy = Context.getBaseElementType(FD->getType()); 11564 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11565 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11566 if (RDecl->getDefinition()) { 11567 // We check for copy constructors before constructors 11568 // because otherwise we'll never get complaints about 11569 // copy constructors. 11570 11571 CXXSpecialMember member = CXXInvalid; 11572 // We're required to check for any non-trivial constructors. Since the 11573 // implicit default constructor is suppressed if there are any 11574 // user-declared constructors, we just need to check that there is a 11575 // trivial default constructor and a trivial copy constructor. (We don't 11576 // worry about move constructors here, since this is a C++98 check.) 11577 if (RDecl->hasNonTrivialCopyConstructor()) 11578 member = CXXCopyConstructor; 11579 else if (!RDecl->hasTrivialDefaultConstructor()) 11580 member = CXXDefaultConstructor; 11581 else if (RDecl->hasNonTrivialCopyAssignment()) 11582 member = CXXCopyAssignment; 11583 else if (RDecl->hasNonTrivialDestructor()) 11584 member = CXXDestructor; 11585 11586 if (member != CXXInvalid) { 11587 if (!getLangOpts().CPlusPlus11 && 11588 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11589 // Objective-C++ ARC: it is an error to have a non-trivial field of 11590 // a union. However, system headers in Objective-C programs 11591 // occasionally have Objective-C lifetime objects within unions, 11592 // and rather than cause the program to fail, we make those 11593 // members unavailable. 11594 SourceLocation Loc = FD->getLocation(); 11595 if (getSourceManager().isInSystemHeader(Loc)) { 11596 if (!FD->hasAttr<UnavailableAttr>()) 11597 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 11598 "this system field has retaining ownership")); 11599 return false; 11600 } 11601 } 11602 11603 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11604 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11605 diag::err_illegal_union_or_anon_struct_member) 11606 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11607 DiagnoseNontrivial(RDecl, member); 11608 return !getLangOpts().CPlusPlus11; 11609 } 11610 } 11611 } 11612 11613 return false; 11614 } 11615 11616 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11617 /// AST enum value. 11618 static ObjCIvarDecl::AccessControl 11619 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11620 switch (ivarVisibility) { 11621 default: llvm_unreachable("Unknown visitibility kind"); 11622 case tok::objc_private: return ObjCIvarDecl::Private; 11623 case tok::objc_public: return ObjCIvarDecl::Public; 11624 case tok::objc_protected: return ObjCIvarDecl::Protected; 11625 case tok::objc_package: return ObjCIvarDecl::Package; 11626 } 11627 } 11628 11629 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11630 /// in order to create an IvarDecl object for it. 11631 Decl *Sema::ActOnIvar(Scope *S, 11632 SourceLocation DeclStart, 11633 Declarator &D, Expr *BitfieldWidth, 11634 tok::ObjCKeywordKind Visibility) { 11635 11636 IdentifierInfo *II = D.getIdentifier(); 11637 Expr *BitWidth = (Expr*)BitfieldWidth; 11638 SourceLocation Loc = DeclStart; 11639 if (II) Loc = D.getIdentifierLoc(); 11640 11641 // FIXME: Unnamed fields can be handled in various different ways, for 11642 // example, unnamed unions inject all members into the struct namespace! 11643 11644 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11645 QualType T = TInfo->getType(); 11646 11647 if (BitWidth) { 11648 // 6.7.2.1p3, 6.7.2.1p4 11649 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11650 if (!BitWidth) 11651 D.setInvalidType(); 11652 } else { 11653 // Not a bitfield. 11654 11655 // validate II. 11656 11657 } 11658 if (T->isReferenceType()) { 11659 Diag(Loc, diag::err_ivar_reference_type); 11660 D.setInvalidType(); 11661 } 11662 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11663 // than a variably modified type. 11664 else if (T->isVariablyModifiedType()) { 11665 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11666 D.setInvalidType(); 11667 } 11668 11669 // Get the visibility (access control) for this ivar. 11670 ObjCIvarDecl::AccessControl ac = 11671 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11672 : ObjCIvarDecl::None; 11673 // Must set ivar's DeclContext to its enclosing interface. 11674 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11675 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11676 return 0; 11677 ObjCContainerDecl *EnclosingContext; 11678 if (ObjCImplementationDecl *IMPDecl = 11679 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11680 if (LangOpts.ObjCRuntime.isFragile()) { 11681 // Case of ivar declared in an implementation. Context is that of its class. 11682 EnclosingContext = IMPDecl->getClassInterface(); 11683 assert(EnclosingContext && "Implementation has no class interface!"); 11684 } 11685 else 11686 EnclosingContext = EnclosingDecl; 11687 } else { 11688 if (ObjCCategoryDecl *CDecl = 11689 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11690 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11691 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11692 return 0; 11693 } 11694 } 11695 EnclosingContext = EnclosingDecl; 11696 } 11697 11698 // Construct the decl. 11699 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11700 DeclStart, Loc, II, T, 11701 TInfo, ac, (Expr *)BitfieldWidth); 11702 11703 if (II) { 11704 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11705 ForRedeclaration); 11706 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11707 && !isa<TagDecl>(PrevDecl)) { 11708 Diag(Loc, diag::err_duplicate_member) << II; 11709 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11710 NewID->setInvalidDecl(); 11711 } 11712 } 11713 11714 // Process attributes attached to the ivar. 11715 ProcessDeclAttributes(S, NewID, D); 11716 11717 if (D.isInvalidType()) 11718 NewID->setInvalidDecl(); 11719 11720 // In ARC, infer 'retaining' for ivars of retainable type. 11721 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11722 NewID->setInvalidDecl(); 11723 11724 if (D.getDeclSpec().isModulePrivateSpecified()) 11725 NewID->setModulePrivate(); 11726 11727 if (II) { 11728 // FIXME: When interfaces are DeclContexts, we'll need to add 11729 // these to the interface. 11730 S->AddDecl(NewID); 11731 IdResolver.AddDecl(NewID); 11732 } 11733 11734 if (LangOpts.ObjCRuntime.isNonFragile() && 11735 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11736 Diag(Loc, diag::warn_ivars_in_interface); 11737 11738 return NewID; 11739 } 11740 11741 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11742 /// class and class extensions. For every class \@interface and class 11743 /// extension \@interface, if the last ivar is a bitfield of any type, 11744 /// then add an implicit `char :0` ivar to the end of that interface. 11745 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11746 SmallVectorImpl<Decl *> &AllIvarDecls) { 11747 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11748 return; 11749 11750 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11751 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11752 11753 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11754 return; 11755 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11756 if (!ID) { 11757 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11758 if (!CD->IsClassExtension()) 11759 return; 11760 } 11761 // No need to add this to end of @implementation. 11762 else 11763 return; 11764 } 11765 // All conditions are met. Add a new bitfield to the tail end of ivars. 11766 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11767 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11768 11769 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11770 DeclLoc, DeclLoc, 0, 11771 Context.CharTy, 11772 Context.getTrivialTypeSourceInfo(Context.CharTy, 11773 DeclLoc), 11774 ObjCIvarDecl::Private, BW, 11775 true); 11776 AllIvarDecls.push_back(Ivar); 11777 } 11778 11779 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 11780 ArrayRef<Decl *> Fields, SourceLocation LBrac, 11781 SourceLocation RBrac, AttributeList *Attr) { 11782 assert(EnclosingDecl && "missing record or interface decl"); 11783 11784 // If this is an Objective-C @implementation or category and we have 11785 // new fields here we should reset the layout of the interface since 11786 // it will now change. 11787 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 11788 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 11789 switch (DC->getKind()) { 11790 default: break; 11791 case Decl::ObjCCategory: 11792 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 11793 break; 11794 case Decl::ObjCImplementation: 11795 Context. 11796 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 11797 break; 11798 } 11799 } 11800 11801 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 11802 11803 // Start counting up the number of named members; make sure to include 11804 // members of anonymous structs and unions in the total. 11805 unsigned NumNamedMembers = 0; 11806 if (Record) { 11807 for (RecordDecl::decl_iterator i = Record->decls_begin(), 11808 e = Record->decls_end(); i != e; i++) { 11809 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 11810 if (IFD->getDeclName()) 11811 ++NumNamedMembers; 11812 } 11813 } 11814 11815 // Verify that all the fields are okay. 11816 SmallVector<FieldDecl*, 32> RecFields; 11817 11818 bool ARCErrReported = false; 11819 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 11820 i != end; ++i) { 11821 FieldDecl *FD = cast<FieldDecl>(*i); 11822 11823 // Get the type for the field. 11824 const Type *FDTy = FD->getType().getTypePtr(); 11825 11826 if (!FD->isAnonymousStructOrUnion()) { 11827 // Remember all fields written by the user. 11828 RecFields.push_back(FD); 11829 } 11830 11831 // If the field is already invalid for some reason, don't emit more 11832 // diagnostics about it. 11833 if (FD->isInvalidDecl()) { 11834 EnclosingDecl->setInvalidDecl(); 11835 continue; 11836 } 11837 11838 // C99 6.7.2.1p2: 11839 // A structure or union shall not contain a member with 11840 // incomplete or function type (hence, a structure shall not 11841 // contain an instance of itself, but may contain a pointer to 11842 // an instance of itself), except that the last member of a 11843 // structure with more than one named member may have incomplete 11844 // array type; such a structure (and any union containing, 11845 // possibly recursively, a member that is such a structure) 11846 // shall not be a member of a structure or an element of an 11847 // array. 11848 if (FDTy->isFunctionType()) { 11849 // Field declared as a function. 11850 Diag(FD->getLocation(), diag::err_field_declared_as_function) 11851 << FD->getDeclName(); 11852 FD->setInvalidDecl(); 11853 EnclosingDecl->setInvalidDecl(); 11854 continue; 11855 } else if (FDTy->isIncompleteArrayType() && Record && 11856 ((i + 1 == Fields.end() && !Record->isUnion()) || 11857 ((getLangOpts().MicrosoftExt || 11858 getLangOpts().CPlusPlus) && 11859 (i + 1 == Fields.end() || Record->isUnion())))) { 11860 // Flexible array member. 11861 // Microsoft and g++ is more permissive regarding flexible array. 11862 // It will accept flexible array in union and also 11863 // as the sole element of a struct/class. 11864 unsigned DiagID = 0; 11865 if (Record->isUnion()) 11866 DiagID = getLangOpts().MicrosoftExt 11867 ? diag::ext_flexible_array_union_ms 11868 : getLangOpts().CPlusPlus 11869 ? diag::ext_flexible_array_union_gnu 11870 : diag::err_flexible_array_union; 11871 else if (Fields.size() == 1) 11872 DiagID = getLangOpts().MicrosoftExt 11873 ? diag::ext_flexible_array_empty_aggregate_ms 11874 : getLangOpts().CPlusPlus 11875 ? diag::ext_flexible_array_empty_aggregate_gnu 11876 : NumNamedMembers < 1 11877 ? diag::err_flexible_array_empty_aggregate 11878 : 0; 11879 11880 if (DiagID) 11881 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 11882 << Record->getTagKind(); 11883 // While the layout of types that contain virtual bases is not specified 11884 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 11885 // virtual bases after the derived members. This would make a flexible 11886 // array member declared at the end of an object not adjacent to the end 11887 // of the type. 11888 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 11889 if (RD->getNumVBases() != 0) 11890 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 11891 << FD->getDeclName() << Record->getTagKind(); 11892 if (!getLangOpts().C99) 11893 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11894 << FD->getDeclName() << Record->getTagKind(); 11895 11896 if (!FD->getType()->isDependentType() && 11897 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 11898 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 11899 << FD->getDeclName() << FD->getType(); 11900 FD->setInvalidDecl(); 11901 EnclosingDecl->setInvalidDecl(); 11902 continue; 11903 } 11904 // Okay, we have a legal flexible array member at the end of the struct. 11905 if (Record) 11906 Record->setHasFlexibleArrayMember(true); 11907 } else if (!FDTy->isDependentType() && 11908 RequireCompleteType(FD->getLocation(), FD->getType(), 11909 diag::err_field_incomplete)) { 11910 // Incomplete type 11911 FD->setInvalidDecl(); 11912 EnclosingDecl->setInvalidDecl(); 11913 continue; 11914 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 11915 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 11916 // If this is a member of a union, then entire union becomes "flexible". 11917 if (Record && Record->isUnion()) { 11918 Record->setHasFlexibleArrayMember(true); 11919 } else { 11920 // If this is a struct/class and this is not the last element, reject 11921 // it. Note that GCC supports variable sized arrays in the middle of 11922 // structures. 11923 if (i + 1 != Fields.end()) 11924 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 11925 << FD->getDeclName() << FD->getType(); 11926 else { 11927 // We support flexible arrays at the end of structs in 11928 // other structs as an extension. 11929 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 11930 << FD->getDeclName(); 11931 if (Record) 11932 Record->setHasFlexibleArrayMember(true); 11933 } 11934 } 11935 } 11936 if (isa<ObjCContainerDecl>(EnclosingDecl) && 11937 RequireNonAbstractType(FD->getLocation(), FD->getType(), 11938 diag::err_abstract_type_in_decl, 11939 AbstractIvarType)) { 11940 // Ivars can not have abstract class types 11941 FD->setInvalidDecl(); 11942 } 11943 if (Record && FDTTy->getDecl()->hasObjectMember()) 11944 Record->setHasObjectMember(true); 11945 if (Record && FDTTy->getDecl()->hasVolatileMember()) 11946 Record->setHasVolatileMember(true); 11947 } else if (FDTy->isObjCObjectType()) { 11948 /// A field cannot be an Objective-c object 11949 Diag(FD->getLocation(), diag::err_statically_allocated_object) 11950 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 11951 QualType T = Context.getObjCObjectPointerType(FD->getType()); 11952 FD->setType(T); 11953 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 11954 (!getLangOpts().CPlusPlus || Record->isUnion())) { 11955 // It's an error in ARC if a field has lifetime. 11956 // We don't want to report this in a system header, though, 11957 // so we just make the field unavailable. 11958 // FIXME: that's really not sufficient; we need to make the type 11959 // itself invalid to, say, initialize or copy. 11960 QualType T = FD->getType(); 11961 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 11962 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 11963 SourceLocation loc = FD->getLocation(); 11964 if (getSourceManager().isInSystemHeader(loc)) { 11965 if (!FD->hasAttr<UnavailableAttr>()) { 11966 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 11967 "this system field has retaining ownership")); 11968 } 11969 } else { 11970 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 11971 << T->isBlockPointerType() << Record->getTagKind(); 11972 } 11973 ARCErrReported = true; 11974 } 11975 } else if (getLangOpts().ObjC1 && 11976 getLangOpts().getGC() != LangOptions::NonGC && 11977 Record && !Record->hasObjectMember()) { 11978 if (FD->getType()->isObjCObjectPointerType() || 11979 FD->getType().isObjCGCStrong()) 11980 Record->setHasObjectMember(true); 11981 else if (Context.getAsArrayType(FD->getType())) { 11982 QualType BaseType = Context.getBaseElementType(FD->getType()); 11983 if (BaseType->isRecordType() && 11984 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 11985 Record->setHasObjectMember(true); 11986 else if (BaseType->isObjCObjectPointerType() || 11987 BaseType.isObjCGCStrong()) 11988 Record->setHasObjectMember(true); 11989 } 11990 } 11991 if (Record && FD->getType().isVolatileQualified()) 11992 Record->setHasVolatileMember(true); 11993 // Keep track of the number of named members. 11994 if (FD->getIdentifier()) 11995 ++NumNamedMembers; 11996 } 11997 11998 // Okay, we successfully defined 'Record'. 11999 if (Record) { 12000 bool Completed = false; 12001 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12002 if (!CXXRecord->isInvalidDecl()) { 12003 // Set access bits correctly on the directly-declared conversions. 12004 for (CXXRecordDecl::conversion_iterator 12005 I = CXXRecord->conversion_begin(), 12006 E = CXXRecord->conversion_end(); I != E; ++I) 12007 I.setAccess((*I)->getAccess()); 12008 12009 if (!CXXRecord->isDependentType()) { 12010 if (CXXRecord->hasUserDeclaredDestructor()) { 12011 // Adjust user-defined destructor exception spec. 12012 if (getLangOpts().CPlusPlus11) 12013 AdjustDestructorExceptionSpec(CXXRecord, 12014 CXXRecord->getDestructor()); 12015 12016 // The Microsoft ABI requires that we perform the destructor body 12017 // checks (i.e. operator delete() lookup) at every declaration, as 12018 // any translation unit may need to emit a deleting destructor. 12019 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12020 CheckDestructor(CXXRecord->getDestructor()); 12021 } 12022 12023 // Add any implicitly-declared members to this class. 12024 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12025 12026 // If we have virtual base classes, we may end up finding multiple 12027 // final overriders for a given virtual function. Check for this 12028 // problem now. 12029 if (CXXRecord->getNumVBases()) { 12030 CXXFinalOverriderMap FinalOverriders; 12031 CXXRecord->getFinalOverriders(FinalOverriders); 12032 12033 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12034 MEnd = FinalOverriders.end(); 12035 M != MEnd; ++M) { 12036 for (OverridingMethods::iterator SO = M->second.begin(), 12037 SOEnd = M->second.end(); 12038 SO != SOEnd; ++SO) { 12039 assert(SO->second.size() > 0 && 12040 "Virtual function without overridding functions?"); 12041 if (SO->second.size() == 1) 12042 continue; 12043 12044 // C++ [class.virtual]p2: 12045 // In a derived class, if a virtual member function of a base 12046 // class subobject has more than one final overrider the 12047 // program is ill-formed. 12048 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12049 << (const NamedDecl *)M->first << Record; 12050 Diag(M->first->getLocation(), 12051 diag::note_overridden_virtual_function); 12052 for (OverridingMethods::overriding_iterator 12053 OM = SO->second.begin(), 12054 OMEnd = SO->second.end(); 12055 OM != OMEnd; ++OM) 12056 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12057 << (const NamedDecl *)M->first << OM->Method->getParent(); 12058 12059 Record->setInvalidDecl(); 12060 } 12061 } 12062 CXXRecord->completeDefinition(&FinalOverriders); 12063 Completed = true; 12064 } 12065 } 12066 } 12067 } 12068 12069 if (!Completed) 12070 Record->completeDefinition(); 12071 12072 if (Record->hasAttrs()) 12073 CheckAlignasUnderalignment(Record); 12074 12075 // Check if the structure/union declaration is a type that can have zero 12076 // size in C. For C this is a language extension, for C++ it may cause 12077 // compatibility problems. 12078 bool CheckForZeroSize; 12079 if (!getLangOpts().CPlusPlus) { 12080 CheckForZeroSize = true; 12081 } else { 12082 // For C++ filter out types that cannot be referenced in C code. 12083 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12084 CheckForZeroSize = 12085 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12086 !CXXRecord->isDependentType() && 12087 CXXRecord->isCLike(); 12088 } 12089 if (CheckForZeroSize) { 12090 bool ZeroSize = true; 12091 bool IsEmpty = true; 12092 unsigned NonBitFields = 0; 12093 for (RecordDecl::field_iterator I = Record->field_begin(), 12094 E = Record->field_end(); 12095 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12096 IsEmpty = false; 12097 if (I->isUnnamedBitfield()) { 12098 if (I->getBitWidthValue(Context) > 0) 12099 ZeroSize = false; 12100 } else { 12101 ++NonBitFields; 12102 QualType FieldType = I->getType(); 12103 if (FieldType->isIncompleteType() || 12104 !Context.getTypeSizeInChars(FieldType).isZero()) 12105 ZeroSize = false; 12106 } 12107 } 12108 12109 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12110 // allowed in C++, but warn if its declaration is inside 12111 // extern "C" block. 12112 if (ZeroSize) { 12113 Diag(RecLoc, getLangOpts().CPlusPlus ? 12114 diag::warn_zero_size_struct_union_in_extern_c : 12115 diag::warn_zero_size_struct_union_compat) 12116 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12117 } 12118 12119 // Structs without named members are extension in C (C99 6.7.2.1p7), 12120 // but are accepted by GCC. 12121 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12122 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12123 diag::ext_no_named_members_in_struct_union) 12124 << Record->isUnion(); 12125 } 12126 } 12127 } else { 12128 ObjCIvarDecl **ClsFields = 12129 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12130 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12131 ID->setEndOfDefinitionLoc(RBrac); 12132 // Add ivar's to class's DeclContext. 12133 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12134 ClsFields[i]->setLexicalDeclContext(ID); 12135 ID->addDecl(ClsFields[i]); 12136 } 12137 // Must enforce the rule that ivars in the base classes may not be 12138 // duplicates. 12139 if (ID->getSuperClass()) 12140 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12141 } else if (ObjCImplementationDecl *IMPDecl = 12142 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12143 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12144 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12145 // Ivar declared in @implementation never belongs to the implementation. 12146 // Only it is in implementation's lexical context. 12147 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12148 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12149 IMPDecl->setIvarLBraceLoc(LBrac); 12150 IMPDecl->setIvarRBraceLoc(RBrac); 12151 } else if (ObjCCategoryDecl *CDecl = 12152 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12153 // case of ivars in class extension; all other cases have been 12154 // reported as errors elsewhere. 12155 // FIXME. Class extension does not have a LocEnd field. 12156 // CDecl->setLocEnd(RBrac); 12157 // Add ivar's to class extension's DeclContext. 12158 // Diagnose redeclaration of private ivars. 12159 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12160 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12161 if (IDecl) { 12162 if (const ObjCIvarDecl *ClsIvar = 12163 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12164 Diag(ClsFields[i]->getLocation(), 12165 diag::err_duplicate_ivar_declaration); 12166 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12167 continue; 12168 } 12169 for (ObjCInterfaceDecl::known_extensions_iterator 12170 Ext = IDecl->known_extensions_begin(), 12171 ExtEnd = IDecl->known_extensions_end(); 12172 Ext != ExtEnd; ++Ext) { 12173 if (const ObjCIvarDecl *ClsExtIvar 12174 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12175 Diag(ClsFields[i]->getLocation(), 12176 diag::err_duplicate_ivar_declaration); 12177 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12178 continue; 12179 } 12180 } 12181 } 12182 ClsFields[i]->setLexicalDeclContext(CDecl); 12183 CDecl->addDecl(ClsFields[i]); 12184 } 12185 CDecl->setIvarLBraceLoc(LBrac); 12186 CDecl->setIvarRBraceLoc(RBrac); 12187 } 12188 } 12189 12190 if (Attr) 12191 ProcessDeclAttributeList(S, Record, Attr); 12192 } 12193 12194 /// \brief Determine whether the given integral value is representable within 12195 /// the given type T. 12196 static bool isRepresentableIntegerValue(ASTContext &Context, 12197 llvm::APSInt &Value, 12198 QualType T) { 12199 assert(T->isIntegralType(Context) && "Integral type required!"); 12200 unsigned BitWidth = Context.getIntWidth(T); 12201 12202 if (Value.isUnsigned() || Value.isNonNegative()) { 12203 if (T->isSignedIntegerOrEnumerationType()) 12204 --BitWidth; 12205 return Value.getActiveBits() <= BitWidth; 12206 } 12207 return Value.getMinSignedBits() <= BitWidth; 12208 } 12209 12210 // \brief Given an integral type, return the next larger integral type 12211 // (or a NULL type of no such type exists). 12212 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12213 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12214 // enum checking below. 12215 assert(T->isIntegralType(Context) && "Integral type required!"); 12216 const unsigned NumTypes = 4; 12217 QualType SignedIntegralTypes[NumTypes] = { 12218 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12219 }; 12220 QualType UnsignedIntegralTypes[NumTypes] = { 12221 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12222 Context.UnsignedLongLongTy 12223 }; 12224 12225 unsigned BitWidth = Context.getTypeSize(T); 12226 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12227 : UnsignedIntegralTypes; 12228 for (unsigned I = 0; I != NumTypes; ++I) 12229 if (Context.getTypeSize(Types[I]) > BitWidth) 12230 return Types[I]; 12231 12232 return QualType(); 12233 } 12234 12235 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12236 EnumConstantDecl *LastEnumConst, 12237 SourceLocation IdLoc, 12238 IdentifierInfo *Id, 12239 Expr *Val) { 12240 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12241 llvm::APSInt EnumVal(IntWidth); 12242 QualType EltTy; 12243 12244 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12245 Val = 0; 12246 12247 if (Val) 12248 Val = DefaultLvalueConversion(Val).take(); 12249 12250 if (Val) { 12251 if (Enum->isDependentType() || Val->isTypeDependent()) 12252 EltTy = Context.DependentTy; 12253 else { 12254 SourceLocation ExpLoc; 12255 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12256 !getLangOpts().MicrosoftMode) { 12257 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12258 // constant-expression in the enumerator-definition shall be a converted 12259 // constant expression of the underlying type. 12260 EltTy = Enum->getIntegerType(); 12261 ExprResult Converted = 12262 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12263 CCEK_Enumerator); 12264 if (Converted.isInvalid()) 12265 Val = 0; 12266 else 12267 Val = Converted.take(); 12268 } else if (!Val->isValueDependent() && 12269 !(Val = VerifyIntegerConstantExpression(Val, 12270 &EnumVal).take())) { 12271 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12272 } else { 12273 if (Enum->isFixed()) { 12274 EltTy = Enum->getIntegerType(); 12275 12276 // In Obj-C and Microsoft mode, require the enumeration value to be 12277 // representable in the underlying type of the enumeration. In C++11, 12278 // we perform a non-narrowing conversion as part of converted constant 12279 // expression checking. 12280 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12281 if (getLangOpts().MicrosoftMode) { 12282 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12283 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12284 } else 12285 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12286 } else 12287 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12288 } else if (getLangOpts().CPlusPlus) { 12289 // C++11 [dcl.enum]p5: 12290 // If the underlying type is not fixed, the type of each enumerator 12291 // is the type of its initializing value: 12292 // - If an initializer is specified for an enumerator, the 12293 // initializing value has the same type as the expression. 12294 EltTy = Val->getType(); 12295 } else { 12296 // C99 6.7.2.2p2: 12297 // The expression that defines the value of an enumeration constant 12298 // shall be an integer constant expression that has a value 12299 // representable as an int. 12300 12301 // Complain if the value is not representable in an int. 12302 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12303 Diag(IdLoc, diag::ext_enum_value_not_int) 12304 << EnumVal.toString(10) << Val->getSourceRange() 12305 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12306 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12307 // Force the type of the expression to 'int'. 12308 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12309 } 12310 EltTy = Val->getType(); 12311 } 12312 } 12313 } 12314 } 12315 12316 if (!Val) { 12317 if (Enum->isDependentType()) 12318 EltTy = Context.DependentTy; 12319 else if (!LastEnumConst) { 12320 // C++0x [dcl.enum]p5: 12321 // If the underlying type is not fixed, the type of each enumerator 12322 // is the type of its initializing value: 12323 // - If no initializer is specified for the first enumerator, the 12324 // initializing value has an unspecified integral type. 12325 // 12326 // GCC uses 'int' for its unspecified integral type, as does 12327 // C99 6.7.2.2p3. 12328 if (Enum->isFixed()) { 12329 EltTy = Enum->getIntegerType(); 12330 } 12331 else { 12332 EltTy = Context.IntTy; 12333 } 12334 } else { 12335 // Assign the last value + 1. 12336 EnumVal = LastEnumConst->getInitVal(); 12337 ++EnumVal; 12338 EltTy = LastEnumConst->getType(); 12339 12340 // Check for overflow on increment. 12341 if (EnumVal < LastEnumConst->getInitVal()) { 12342 // C++0x [dcl.enum]p5: 12343 // If the underlying type is not fixed, the type of each enumerator 12344 // is the type of its initializing value: 12345 // 12346 // - Otherwise the type of the initializing value is the same as 12347 // the type of the initializing value of the preceding enumerator 12348 // unless the incremented value is not representable in that type, 12349 // in which case the type is an unspecified integral type 12350 // sufficient to contain the incremented value. If no such type 12351 // exists, the program is ill-formed. 12352 QualType T = getNextLargerIntegralType(Context, EltTy); 12353 if (T.isNull() || Enum->isFixed()) { 12354 // There is no integral type larger enough to represent this 12355 // value. Complain, then allow the value to wrap around. 12356 EnumVal = LastEnumConst->getInitVal(); 12357 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12358 ++EnumVal; 12359 if (Enum->isFixed()) 12360 // When the underlying type is fixed, this is ill-formed. 12361 Diag(IdLoc, diag::err_enumerator_wrapped) 12362 << EnumVal.toString(10) 12363 << EltTy; 12364 else 12365 Diag(IdLoc, diag::warn_enumerator_too_large) 12366 << EnumVal.toString(10); 12367 } else { 12368 EltTy = T; 12369 } 12370 12371 // Retrieve the last enumerator's value, extent that type to the 12372 // type that is supposed to be large enough to represent the incremented 12373 // value, then increment. 12374 EnumVal = LastEnumConst->getInitVal(); 12375 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12376 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12377 ++EnumVal; 12378 12379 // If we're not in C++, diagnose the overflow of enumerator values, 12380 // which in C99 means that the enumerator value is not representable in 12381 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12382 // permits enumerator values that are representable in some larger 12383 // integral type. 12384 if (!getLangOpts().CPlusPlus && !T.isNull()) 12385 Diag(IdLoc, diag::warn_enum_value_overflow); 12386 } else if (!getLangOpts().CPlusPlus && 12387 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12388 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12389 Diag(IdLoc, diag::ext_enum_value_not_int) 12390 << EnumVal.toString(10) << 1; 12391 } 12392 } 12393 } 12394 12395 if (!EltTy->isDependentType()) { 12396 // Make the enumerator value match the signedness and size of the 12397 // enumerator's type. 12398 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12399 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12400 } 12401 12402 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12403 Val, EnumVal); 12404 } 12405 12406 12407 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12408 SourceLocation IdLoc, IdentifierInfo *Id, 12409 AttributeList *Attr, 12410 SourceLocation EqualLoc, Expr *Val) { 12411 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12412 EnumConstantDecl *LastEnumConst = 12413 cast_or_null<EnumConstantDecl>(lastEnumConst); 12414 12415 // The scope passed in may not be a decl scope. Zip up the scope tree until 12416 // we find one that is. 12417 S = getNonFieldDeclScope(S); 12418 12419 // Verify that there isn't already something declared with this name in this 12420 // scope. 12421 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12422 ForRedeclaration); 12423 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12424 // Maybe we will complain about the shadowed template parameter. 12425 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12426 // Just pretend that we didn't see the previous declaration. 12427 PrevDecl = 0; 12428 } 12429 12430 if (PrevDecl) { 12431 // When in C++, we may get a TagDecl with the same name; in this case the 12432 // enum constant will 'hide' the tag. 12433 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12434 "Received TagDecl when not in C++!"); 12435 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12436 if (isa<EnumConstantDecl>(PrevDecl)) 12437 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12438 else 12439 Diag(IdLoc, diag::err_redefinition) << Id; 12440 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12441 return 0; 12442 } 12443 } 12444 12445 // C++ [class.mem]p15: 12446 // If T is the name of a class, then each of the following shall have a name 12447 // different from T: 12448 // - every enumerator of every member of class T that is an unscoped 12449 // enumerated type 12450 if (CXXRecordDecl *Record 12451 = dyn_cast<CXXRecordDecl>( 12452 TheEnumDecl->getDeclContext()->getRedeclContext())) 12453 if (!TheEnumDecl->isScoped() && 12454 Record->getIdentifier() && Record->getIdentifier() == Id) 12455 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12456 12457 EnumConstantDecl *New = 12458 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12459 12460 if (New) { 12461 // Process attributes. 12462 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12463 12464 // Register this decl in the current scope stack. 12465 New->setAccess(TheEnumDecl->getAccess()); 12466 PushOnScopeChains(New, S); 12467 } 12468 12469 ActOnDocumentableDecl(New); 12470 12471 return New; 12472 } 12473 12474 // Returns true when the enum initial expression does not trigger the 12475 // duplicate enum warning. A few common cases are exempted as follows: 12476 // Element2 = Element1 12477 // Element2 = Element1 + 1 12478 // Element2 = Element1 - 1 12479 // Where Element2 and Element1 are from the same enum. 12480 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12481 Expr *InitExpr = ECD->getInitExpr(); 12482 if (!InitExpr) 12483 return true; 12484 InitExpr = InitExpr->IgnoreImpCasts(); 12485 12486 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12487 if (!BO->isAdditiveOp()) 12488 return true; 12489 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12490 if (!IL) 12491 return true; 12492 if (IL->getValue() != 1) 12493 return true; 12494 12495 InitExpr = BO->getLHS(); 12496 } 12497 12498 // This checks if the elements are from the same enum. 12499 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12500 if (!DRE) 12501 return true; 12502 12503 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12504 if (!EnumConstant) 12505 return true; 12506 12507 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12508 Enum) 12509 return true; 12510 12511 return false; 12512 } 12513 12514 struct DupKey { 12515 int64_t val; 12516 bool isTombstoneOrEmptyKey; 12517 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12518 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12519 }; 12520 12521 static DupKey GetDupKey(const llvm::APSInt& Val) { 12522 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12523 false); 12524 } 12525 12526 struct DenseMapInfoDupKey { 12527 static DupKey getEmptyKey() { return DupKey(0, true); } 12528 static DupKey getTombstoneKey() { return DupKey(1, true); } 12529 static unsigned getHashValue(const DupKey Key) { 12530 return (unsigned)(Key.val * 37); 12531 } 12532 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12533 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12534 LHS.val == RHS.val; 12535 } 12536 }; 12537 12538 // Emits a warning when an element is implicitly set a value that 12539 // a previous element has already been set to. 12540 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12541 EnumDecl *Enum, 12542 QualType EnumType) { 12543 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12544 Enum->getLocation()) == 12545 DiagnosticsEngine::Ignored) 12546 return; 12547 // Avoid anonymous enums 12548 if (!Enum->getIdentifier()) 12549 return; 12550 12551 // Only check for small enums. 12552 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12553 return; 12554 12555 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12556 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12557 12558 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12559 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12560 ValueToVectorMap; 12561 12562 DuplicatesVector DupVector; 12563 ValueToVectorMap EnumMap; 12564 12565 // Populate the EnumMap with all values represented by enum constants without 12566 // an initialier. 12567 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12568 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12569 12570 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12571 // this constant. Skip this enum since it may be ill-formed. 12572 if (!ECD) { 12573 return; 12574 } 12575 12576 if (ECD->getInitExpr()) 12577 continue; 12578 12579 DupKey Key = GetDupKey(ECD->getInitVal()); 12580 DeclOrVector &Entry = EnumMap[Key]; 12581 12582 // First time encountering this value. 12583 if (Entry.isNull()) 12584 Entry = ECD; 12585 } 12586 12587 // Create vectors for any values that has duplicates. 12588 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12589 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12590 if (!ValidDuplicateEnum(ECD, Enum)) 12591 continue; 12592 12593 DupKey Key = GetDupKey(ECD->getInitVal()); 12594 12595 DeclOrVector& Entry = EnumMap[Key]; 12596 if (Entry.isNull()) 12597 continue; 12598 12599 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12600 // Ensure constants are different. 12601 if (D == ECD) 12602 continue; 12603 12604 // Create new vector and push values onto it. 12605 ECDVector *Vec = new ECDVector(); 12606 Vec->push_back(D); 12607 Vec->push_back(ECD); 12608 12609 // Update entry to point to the duplicates vector. 12610 Entry = Vec; 12611 12612 // Store the vector somewhere we can consult later for quick emission of 12613 // diagnostics. 12614 DupVector.push_back(Vec); 12615 continue; 12616 } 12617 12618 ECDVector *Vec = Entry.get<ECDVector*>(); 12619 // Make sure constants are not added more than once. 12620 if (*Vec->begin() == ECD) 12621 continue; 12622 12623 Vec->push_back(ECD); 12624 } 12625 12626 // Emit diagnostics. 12627 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12628 DupVectorEnd = DupVector.end(); 12629 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12630 ECDVector *Vec = *DupVectorIter; 12631 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12632 12633 // Emit warning for one enum constant. 12634 ECDVector::iterator I = Vec->begin(); 12635 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12636 << (*I)->getName() << (*I)->getInitVal().toString(10) 12637 << (*I)->getSourceRange(); 12638 ++I; 12639 12640 // Emit one note for each of the remaining enum constants with 12641 // the same value. 12642 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12643 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12644 << (*I)->getName() << (*I)->getInitVal().toString(10) 12645 << (*I)->getSourceRange(); 12646 delete Vec; 12647 } 12648 } 12649 12650 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12651 SourceLocation RBraceLoc, Decl *EnumDeclX, 12652 ArrayRef<Decl *> Elements, 12653 Scope *S, AttributeList *Attr) { 12654 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12655 QualType EnumType = Context.getTypeDeclType(Enum); 12656 12657 if (Attr) 12658 ProcessDeclAttributeList(S, Enum, Attr); 12659 12660 if (Enum->isDependentType()) { 12661 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12662 EnumConstantDecl *ECD = 12663 cast_or_null<EnumConstantDecl>(Elements[i]); 12664 if (!ECD) continue; 12665 12666 ECD->setType(EnumType); 12667 } 12668 12669 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12670 return; 12671 } 12672 12673 // TODO: If the result value doesn't fit in an int, it must be a long or long 12674 // long value. ISO C does not support this, but GCC does as an extension, 12675 // emit a warning. 12676 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12677 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12678 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12679 12680 // Verify that all the values are okay, compute the size of the values, and 12681 // reverse the list. 12682 unsigned NumNegativeBits = 0; 12683 unsigned NumPositiveBits = 0; 12684 12685 // Keep track of whether all elements have type int. 12686 bool AllElementsInt = true; 12687 12688 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12689 EnumConstantDecl *ECD = 12690 cast_or_null<EnumConstantDecl>(Elements[i]); 12691 if (!ECD) continue; // Already issued a diagnostic. 12692 12693 const llvm::APSInt &InitVal = ECD->getInitVal(); 12694 12695 // Keep track of the size of positive and negative values. 12696 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12697 NumPositiveBits = std::max(NumPositiveBits, 12698 (unsigned)InitVal.getActiveBits()); 12699 else 12700 NumNegativeBits = std::max(NumNegativeBits, 12701 (unsigned)InitVal.getMinSignedBits()); 12702 12703 // Keep track of whether every enum element has type int (very commmon). 12704 if (AllElementsInt) 12705 AllElementsInt = ECD->getType() == Context.IntTy; 12706 } 12707 12708 // Figure out the type that should be used for this enum. 12709 QualType BestType; 12710 unsigned BestWidth; 12711 12712 // C++0x N3000 [conv.prom]p3: 12713 // An rvalue of an unscoped enumeration type whose underlying 12714 // type is not fixed can be converted to an rvalue of the first 12715 // of the following types that can represent all the values of 12716 // the enumeration: int, unsigned int, long int, unsigned long 12717 // int, long long int, or unsigned long long int. 12718 // C99 6.4.4.3p2: 12719 // An identifier declared as an enumeration constant has type int. 12720 // The C99 rule is modified by a gcc extension 12721 QualType BestPromotionType; 12722 12723 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 12724 // -fshort-enums is the equivalent to specifying the packed attribute on all 12725 // enum definitions. 12726 if (LangOpts.ShortEnums) 12727 Packed = true; 12728 12729 if (Enum->isFixed()) { 12730 BestType = Enum->getIntegerType(); 12731 if (BestType->isPromotableIntegerType()) 12732 BestPromotionType = Context.getPromotedIntegerType(BestType); 12733 else 12734 BestPromotionType = BestType; 12735 // We don't need to set BestWidth, because BestType is going to be the type 12736 // of the enumerators, but we do anyway because otherwise some compilers 12737 // warn that it might be used uninitialized. 12738 BestWidth = CharWidth; 12739 } 12740 else if (NumNegativeBits) { 12741 // If there is a negative value, figure out the smallest integer type (of 12742 // int/long/longlong) that fits. 12743 // If it's packed, check also if it fits a char or a short. 12744 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12745 BestType = Context.SignedCharTy; 12746 BestWidth = CharWidth; 12747 } else if (Packed && NumNegativeBits <= ShortWidth && 12748 NumPositiveBits < ShortWidth) { 12749 BestType = Context.ShortTy; 12750 BestWidth = ShortWidth; 12751 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12752 BestType = Context.IntTy; 12753 BestWidth = IntWidth; 12754 } else { 12755 BestWidth = Context.getTargetInfo().getLongWidth(); 12756 12757 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12758 BestType = Context.LongTy; 12759 } else { 12760 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12761 12762 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12763 Diag(Enum->getLocation(), diag::warn_enum_too_large); 12764 BestType = Context.LongLongTy; 12765 } 12766 } 12767 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12768 } else { 12769 // If there is no negative value, figure out the smallest type that fits 12770 // all of the enumerator values. 12771 // If it's packed, check also if it fits a char or a short. 12772 if (Packed && NumPositiveBits <= CharWidth) { 12773 BestType = Context.UnsignedCharTy; 12774 BestPromotionType = Context.IntTy; 12775 BestWidth = CharWidth; 12776 } else if (Packed && NumPositiveBits <= ShortWidth) { 12777 BestType = Context.UnsignedShortTy; 12778 BestPromotionType = Context.IntTy; 12779 BestWidth = ShortWidth; 12780 } else if (NumPositiveBits <= IntWidth) { 12781 BestType = Context.UnsignedIntTy; 12782 BestWidth = IntWidth; 12783 BestPromotionType 12784 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12785 ? Context.UnsignedIntTy : Context.IntTy; 12786 } else if (NumPositiveBits <= 12787 (BestWidth = Context.getTargetInfo().getLongWidth())) { 12788 BestType = Context.UnsignedLongTy; 12789 BestPromotionType 12790 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12791 ? Context.UnsignedLongTy : Context.LongTy; 12792 } else { 12793 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12794 assert(NumPositiveBits <= BestWidth && 12795 "How could an initializer get larger than ULL?"); 12796 BestType = Context.UnsignedLongLongTy; 12797 BestPromotionType 12798 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12799 ? Context.UnsignedLongLongTy : Context.LongLongTy; 12800 } 12801 } 12802 12803 // Loop over all of the enumerator constants, changing their types to match 12804 // the type of the enum if needed. 12805 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12806 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12807 if (!ECD) continue; // Already issued a diagnostic. 12808 12809 // Standard C says the enumerators have int type, but we allow, as an 12810 // extension, the enumerators to be larger than int size. If each 12811 // enumerator value fits in an int, type it as an int, otherwise type it the 12812 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 12813 // that X has type 'int', not 'unsigned'. 12814 12815 // Determine whether the value fits into an int. 12816 llvm::APSInt InitVal = ECD->getInitVal(); 12817 12818 // If it fits into an integer type, force it. Otherwise force it to match 12819 // the enum decl type. 12820 QualType NewTy; 12821 unsigned NewWidth; 12822 bool NewSign; 12823 if (!getLangOpts().CPlusPlus && 12824 !Enum->isFixed() && 12825 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 12826 NewTy = Context.IntTy; 12827 NewWidth = IntWidth; 12828 NewSign = true; 12829 } else if (ECD->getType() == BestType) { 12830 // Already the right type! 12831 if (getLangOpts().CPlusPlus) 12832 // C++ [dcl.enum]p4: Following the closing brace of an 12833 // enum-specifier, each enumerator has the type of its 12834 // enumeration. 12835 ECD->setType(EnumType); 12836 continue; 12837 } else { 12838 NewTy = BestType; 12839 NewWidth = BestWidth; 12840 NewSign = BestType->isSignedIntegerOrEnumerationType(); 12841 } 12842 12843 // Adjust the APSInt value. 12844 InitVal = InitVal.extOrTrunc(NewWidth); 12845 InitVal.setIsSigned(NewSign); 12846 ECD->setInitVal(InitVal); 12847 12848 // Adjust the Expr initializer and type. 12849 if (ECD->getInitExpr() && 12850 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 12851 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 12852 CK_IntegralCast, 12853 ECD->getInitExpr(), 12854 /*base paths*/ 0, 12855 VK_RValue)); 12856 if (getLangOpts().CPlusPlus) 12857 // C++ [dcl.enum]p4: Following the closing brace of an 12858 // enum-specifier, each enumerator has the type of its 12859 // enumeration. 12860 ECD->setType(EnumType); 12861 else 12862 ECD->setType(NewTy); 12863 } 12864 12865 Enum->completeDefinition(BestType, BestPromotionType, 12866 NumPositiveBits, NumNegativeBits); 12867 12868 // If we're declaring a function, ensure this decl isn't forgotten about - 12869 // it needs to go into the function scope. 12870 if (InFunctionDeclarator) 12871 DeclsInPrototypeScope.push_back(Enum); 12872 12873 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 12874 12875 // Now that the enum type is defined, ensure it's not been underaligned. 12876 if (Enum->hasAttrs()) 12877 CheckAlignasUnderalignment(Enum); 12878 } 12879 12880 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 12881 SourceLocation StartLoc, 12882 SourceLocation EndLoc) { 12883 StringLiteral *AsmString = cast<StringLiteral>(expr); 12884 12885 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 12886 AsmString, StartLoc, 12887 EndLoc); 12888 CurContext->addDecl(New); 12889 return New; 12890 } 12891 12892 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 12893 SourceLocation ImportLoc, 12894 ModuleIdPath Path) { 12895 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 12896 Module::AllVisible, 12897 /*IsIncludeDirective=*/false); 12898 if (!Mod) 12899 return true; 12900 12901 SmallVector<SourceLocation, 2> IdentifierLocs; 12902 Module *ModCheck = Mod; 12903 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 12904 // If we've run out of module parents, just drop the remaining identifiers. 12905 // We need the length to be consistent. 12906 if (!ModCheck) 12907 break; 12908 ModCheck = ModCheck->Parent; 12909 12910 IdentifierLocs.push_back(Path[I].second); 12911 } 12912 12913 ImportDecl *Import = ImportDecl::Create(Context, 12914 Context.getTranslationUnitDecl(), 12915 AtLoc.isValid()? AtLoc : ImportLoc, 12916 Mod, IdentifierLocs); 12917 Context.getTranslationUnitDecl()->addDecl(Import); 12918 return Import; 12919 } 12920 12921 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 12922 // FIXME: Should we synthesize an ImportDecl here? 12923 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 12924 /*Complain=*/true); 12925 } 12926 12927 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 12928 // Create the implicit import declaration. 12929 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 12930 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 12931 Loc, Mod, Loc); 12932 TU->addDecl(ImportD); 12933 Consumer.HandleImplicitImportDecl(ImportD); 12934 12935 // Make the module visible. 12936 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 12937 /*Complain=*/false); 12938 } 12939 12940 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 12941 IdentifierInfo* AliasName, 12942 SourceLocation PragmaLoc, 12943 SourceLocation NameLoc, 12944 SourceLocation AliasNameLoc) { 12945 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 12946 LookupOrdinaryName); 12947 AsmLabelAttr *Attr = 12948 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 12949 12950 if (PrevDecl) 12951 PrevDecl->addAttr(Attr); 12952 else 12953 (void)ExtnameUndeclaredIdentifiers.insert( 12954 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 12955 } 12956 12957 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 12958 SourceLocation PragmaLoc, 12959 SourceLocation NameLoc) { 12960 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 12961 12962 if (PrevDecl) { 12963 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 12964 } else { 12965 (void)WeakUndeclaredIdentifiers.insert( 12966 std::pair<IdentifierInfo*,WeakInfo> 12967 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 12968 } 12969 } 12970 12971 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 12972 IdentifierInfo* AliasName, 12973 SourceLocation PragmaLoc, 12974 SourceLocation NameLoc, 12975 SourceLocation AliasNameLoc) { 12976 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 12977 LookupOrdinaryName); 12978 WeakInfo W = WeakInfo(Name, NameLoc); 12979 12980 if (PrevDecl) { 12981 if (!PrevDecl->hasAttr<AliasAttr>()) 12982 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 12983 DeclApplyPragmaWeak(TUScope, ND, W); 12984 } else { 12985 (void)WeakUndeclaredIdentifiers.insert( 12986 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 12987 } 12988 } 12989 12990 Decl *Sema::getObjCDeclContext() const { 12991 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 12992 } 12993 12994 AvailabilityResult Sema::getCurContextAvailability() const { 12995 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 12996 return D->getAvailability(); 12997 } 12998