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().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 471 DiagID = diag::warn_typename_missing; 472 473 Diag(SS->getRange().getBegin(), DiagID) 474 << 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 && 849 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 850 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 851 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 852 DiagnoseUseOfDecl(Type, NameLoc); 853 QualType T = Context.getTypeDeclType(Type); 854 if (SS.isNotEmpty()) 855 return buildNestedType(*this, SS, T, NameLoc); 856 return ParsedType::make(T); 857 } 858 859 if (FirstDecl->isCXXClassMember()) 860 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 861 862 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 863 return BuildDeclarationNameExpr(SS, Result, ADL); 864 } 865 866 // Determines the context to return to after temporarily entering a 867 // context. This depends in an unnecessarily complicated way on the 868 // exact ordering of callbacks from the parser. 869 DeclContext *Sema::getContainingDC(DeclContext *DC) { 870 871 // Functions defined inline within classes aren't parsed until we've 872 // finished parsing the top-level class, so the top-level class is 873 // the context we'll need to return to. 874 // A Lambda call operator whose parent is a class must not be treated 875 // as an inline member function. A Lambda can be used legally 876 // either as an in-class member initializer or a default argument. These 877 // are parsed once the class has been marked complete and so the containing 878 // context would be the nested class (when the lambda is defined in one); 879 // If the class is not complete, then the lambda is being used in an 880 // ill-formed fashion (such as to specify the width of a bit-field, or 881 // in an array-bound) - in which case we still want to return the 882 // lexically containing DC (which could be a nested class). 883 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 884 DC = DC->getLexicalParent(); 885 886 // A function not defined within a class will always return to its 887 // lexical context. 888 if (!isa<CXXRecordDecl>(DC)) 889 return DC; 890 891 // A C++ inline method/friend is parsed *after* the topmost class 892 // it was declared in is fully parsed ("complete"); the topmost 893 // class is the context we need to return to. 894 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 895 DC = RD; 896 897 // Return the declaration context of the topmost class the inline method is 898 // declared in. 899 return DC; 900 } 901 902 return DC->getLexicalParent(); 903 } 904 905 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 906 assert(getContainingDC(DC) == CurContext && 907 "The next DeclContext should be lexically contained in the current one."); 908 CurContext = DC; 909 S->setEntity(DC); 910 } 911 912 void Sema::PopDeclContext() { 913 assert(CurContext && "DeclContext imbalance!"); 914 915 CurContext = getContainingDC(CurContext); 916 assert(CurContext && "Popped translation unit!"); 917 } 918 919 /// EnterDeclaratorContext - Used when we must lookup names in the context 920 /// of a declarator's nested name specifier. 921 /// 922 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 923 // C++0x [basic.lookup.unqual]p13: 924 // A name used in the definition of a static data member of class 925 // X (after the qualified-id of the static member) is looked up as 926 // if the name was used in a member function of X. 927 // C++0x [basic.lookup.unqual]p14: 928 // If a variable member of a namespace is defined outside of the 929 // scope of its namespace then any name used in the definition of 930 // the variable member (after the declarator-id) is looked up as 931 // if the definition of the variable member occurred in its 932 // namespace. 933 // Both of these imply that we should push a scope whose context 934 // is the semantic context of the declaration. We can't use 935 // PushDeclContext here because that context is not necessarily 936 // lexically contained in the current context. Fortunately, 937 // the containing scope should have the appropriate information. 938 939 assert(!S->getEntity() && "scope already has entity"); 940 941 #ifndef NDEBUG 942 Scope *Ancestor = S->getParent(); 943 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 944 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 945 #endif 946 947 CurContext = DC; 948 S->setEntity(DC); 949 } 950 951 void Sema::ExitDeclaratorContext(Scope *S) { 952 assert(S->getEntity() == CurContext && "Context imbalance!"); 953 954 // Switch back to the lexical context. The safety of this is 955 // enforced by an assert in EnterDeclaratorContext. 956 Scope *Ancestor = S->getParent(); 957 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 958 CurContext = Ancestor->getEntity(); 959 960 // We don't need to do anything with the scope, which is going to 961 // disappear. 962 } 963 964 965 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 966 // We assume that the caller has already called 967 // ActOnReenterTemplateScope so getTemplatedDecl() works. 968 FunctionDecl *FD = D->getAsFunction(); 969 if (!FD) 970 return; 971 972 // Same implementation as PushDeclContext, but enters the context 973 // from the lexical parent, rather than the top-level class. 974 assert(CurContext == FD->getLexicalParent() && 975 "The next DeclContext should be lexically contained in the current one."); 976 CurContext = FD; 977 S->setEntity(CurContext); 978 979 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 980 ParmVarDecl *Param = FD->getParamDecl(P); 981 // If the parameter has an identifier, then add it to the scope 982 if (Param->getIdentifier()) { 983 S->AddDecl(Param); 984 IdResolver.AddDecl(Param); 985 } 986 } 987 } 988 989 990 void Sema::ActOnExitFunctionContext() { 991 // Same implementation as PopDeclContext, but returns to the lexical parent, 992 // rather than the top-level class. 993 assert(CurContext && "DeclContext imbalance!"); 994 CurContext = CurContext->getLexicalParent(); 995 assert(CurContext && "Popped translation unit!"); 996 } 997 998 999 /// \brief Determine whether we allow overloading of the function 1000 /// PrevDecl with another declaration. 1001 /// 1002 /// This routine determines whether overloading is possible, not 1003 /// whether some new function is actually an overload. It will return 1004 /// true in C++ (where we can always provide overloads) or, as an 1005 /// extension, in C when the previous function is already an 1006 /// overloaded function declaration or has the "overloadable" 1007 /// attribute. 1008 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1009 ASTContext &Context) { 1010 if (Context.getLangOpts().CPlusPlus) 1011 return true; 1012 1013 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1014 return true; 1015 1016 return (Previous.getResultKind() == LookupResult::Found 1017 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1018 } 1019 1020 /// Add this decl to the scope shadowed decl chains. 1021 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1022 // Move up the scope chain until we find the nearest enclosing 1023 // non-transparent context. The declaration will be introduced into this 1024 // scope. 1025 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1026 S = S->getParent(); 1027 1028 // Add scoped declarations into their context, so that they can be 1029 // found later. Declarations without a context won't be inserted 1030 // into any context. 1031 if (AddToContext) 1032 CurContext->addDecl(D); 1033 1034 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1035 // are function-local declarations. 1036 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1037 !D->getDeclContext()->getRedeclContext()->Equals( 1038 D->getLexicalDeclContext()->getRedeclContext()) && 1039 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1040 return; 1041 1042 // Template instantiations should also not be pushed into scope. 1043 if (isa<FunctionDecl>(D) && 1044 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1045 return; 1046 1047 // If this replaces anything in the current scope, 1048 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1049 IEnd = IdResolver.end(); 1050 for (; I != IEnd; ++I) { 1051 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1052 S->RemoveDecl(*I); 1053 IdResolver.RemoveDecl(*I); 1054 1055 // Should only need to replace one decl. 1056 break; 1057 } 1058 } 1059 1060 S->AddDecl(D); 1061 1062 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1063 // Implicitly-generated labels may end up getting generated in an order that 1064 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1065 // the label at the appropriate place in the identifier chain. 1066 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1067 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1068 if (IDC == CurContext) { 1069 if (!S->isDeclScope(*I)) 1070 continue; 1071 } else if (IDC->Encloses(CurContext)) 1072 break; 1073 } 1074 1075 IdResolver.InsertDeclAfter(I, D); 1076 } else { 1077 IdResolver.AddDecl(D); 1078 } 1079 } 1080 1081 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1082 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1083 TUScope->AddDecl(D); 1084 } 1085 1086 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1087 bool AllowInlineNamespace) { 1088 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1089 } 1090 1091 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1092 DeclContext *TargetDC = DC->getPrimaryContext(); 1093 do { 1094 if (DeclContext *ScopeDC = S->getEntity()) 1095 if (ScopeDC->getPrimaryContext() == TargetDC) 1096 return S; 1097 } while ((S = S->getParent())); 1098 1099 return 0; 1100 } 1101 1102 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1103 DeclContext*, 1104 ASTContext&); 1105 1106 /// Filters out lookup results that don't fall within the given scope 1107 /// as determined by isDeclInScope. 1108 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1109 bool ConsiderLinkage, 1110 bool AllowInlineNamespace) { 1111 LookupResult::Filter F = R.makeFilter(); 1112 while (F.hasNext()) { 1113 NamedDecl *D = F.next(); 1114 1115 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1116 continue; 1117 1118 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1119 continue; 1120 1121 F.erase(); 1122 } 1123 1124 F.done(); 1125 } 1126 1127 static bool isUsingDecl(NamedDecl *D) { 1128 return isa<UsingShadowDecl>(D) || 1129 isa<UnresolvedUsingTypenameDecl>(D) || 1130 isa<UnresolvedUsingValueDecl>(D); 1131 } 1132 1133 /// Removes using shadow declarations from the lookup results. 1134 static void RemoveUsingDecls(LookupResult &R) { 1135 LookupResult::Filter F = R.makeFilter(); 1136 while (F.hasNext()) 1137 if (isUsingDecl(F.next())) 1138 F.erase(); 1139 1140 F.done(); 1141 } 1142 1143 /// \brief Check for this common pattern: 1144 /// @code 1145 /// class S { 1146 /// S(const S&); // DO NOT IMPLEMENT 1147 /// void operator=(const S&); // DO NOT IMPLEMENT 1148 /// }; 1149 /// @endcode 1150 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1151 // FIXME: Should check for private access too but access is set after we get 1152 // the decl here. 1153 if (D->doesThisDeclarationHaveABody()) 1154 return false; 1155 1156 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1157 return CD->isCopyConstructor(); 1158 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1159 return Method->isCopyAssignmentOperator(); 1160 return false; 1161 } 1162 1163 // We need this to handle 1164 // 1165 // typedef struct { 1166 // void *foo() { return 0; } 1167 // } A; 1168 // 1169 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1170 // for example. If 'A', foo will have external linkage. If we have '*A', 1171 // foo will have no linkage. Since we can't know until we get to the end 1172 // of the typedef, this function finds out if D might have non-external linkage. 1173 // Callers should verify at the end of the TU if it D has external linkage or 1174 // not. 1175 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1176 const DeclContext *DC = D->getDeclContext(); 1177 while (!DC->isTranslationUnit()) { 1178 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1179 if (!RD->hasNameForLinkage()) 1180 return true; 1181 } 1182 DC = DC->getParent(); 1183 } 1184 1185 return !D->isExternallyVisible(); 1186 } 1187 1188 // FIXME: This needs to be refactored; some other isInMainFile users want 1189 // these semantics. 1190 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1191 if (S.TUKind != TU_Complete) 1192 return false; 1193 return S.SourceMgr.isInMainFile(Loc); 1194 } 1195 1196 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1197 assert(D); 1198 1199 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1200 return false; 1201 1202 // Ignore class templates. 1203 if (D->getDeclContext()->isDependentContext() || 1204 D->getLexicalDeclContext()->isDependentContext()) 1205 return false; 1206 1207 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1208 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1209 return false; 1210 1211 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1212 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1213 return false; 1214 } else { 1215 // 'static inline' functions are defined in headers; don't warn. 1216 if (FD->isInlineSpecified() && 1217 !isMainFileLoc(*this, FD->getLocation())) 1218 return false; 1219 } 1220 1221 if (FD->doesThisDeclarationHaveABody() && 1222 Context.DeclMustBeEmitted(FD)) 1223 return false; 1224 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1225 // Constants and utility variables are defined in headers with internal 1226 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1227 // like "inline".) 1228 if (!isMainFileLoc(*this, VD->getLocation())) 1229 return false; 1230 1231 if (Context.DeclMustBeEmitted(VD)) 1232 return false; 1233 1234 if (VD->isStaticDataMember() && 1235 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1236 return false; 1237 } else { 1238 return false; 1239 } 1240 1241 // Only warn for unused decls internal to the translation unit. 1242 return mightHaveNonExternalLinkage(D); 1243 } 1244 1245 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1246 if (!D) 1247 return; 1248 1249 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1250 const FunctionDecl *First = FD->getFirstDecl(); 1251 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1252 return; // First should already be in the vector. 1253 } 1254 1255 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1256 const VarDecl *First = VD->getFirstDecl(); 1257 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1258 return; // First should already be in the vector. 1259 } 1260 1261 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1262 UnusedFileScopedDecls.push_back(D); 1263 } 1264 1265 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1266 if (D->isInvalidDecl()) 1267 return false; 1268 1269 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1270 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1271 return false; 1272 1273 if (isa<LabelDecl>(D)) 1274 return true; 1275 1276 // White-list anything that isn't a local variable. 1277 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1278 !D->getDeclContext()->isFunctionOrMethod()) 1279 return false; 1280 1281 // Types of valid local variables should be complete, so this should succeed. 1282 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1283 1284 // White-list anything with an __attribute__((unused)) type. 1285 QualType Ty = VD->getType(); 1286 1287 // Only look at the outermost level of typedef. 1288 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1289 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1290 return false; 1291 } 1292 1293 // If we failed to complete the type for some reason, or if the type is 1294 // dependent, don't diagnose the variable. 1295 if (Ty->isIncompleteType() || Ty->isDependentType()) 1296 return false; 1297 1298 if (const TagType *TT = Ty->getAs<TagType>()) { 1299 const TagDecl *Tag = TT->getDecl(); 1300 if (Tag->hasAttr<UnusedAttr>()) 1301 return false; 1302 1303 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1304 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1305 return false; 1306 1307 if (const Expr *Init = VD->getInit()) { 1308 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1309 Init = Cleanups->getSubExpr(); 1310 const CXXConstructExpr *Construct = 1311 dyn_cast<CXXConstructExpr>(Init); 1312 if (Construct && !Construct->isElidable()) { 1313 CXXConstructorDecl *CD = Construct->getConstructor(); 1314 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1315 return false; 1316 } 1317 } 1318 } 1319 } 1320 1321 // TODO: __attribute__((unused)) templates? 1322 } 1323 1324 return true; 1325 } 1326 1327 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1328 FixItHint &Hint) { 1329 if (isa<LabelDecl>(D)) { 1330 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1331 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1332 if (AfterColon.isInvalid()) 1333 return; 1334 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1335 getCharRange(D->getLocStart(), AfterColon)); 1336 } 1337 return; 1338 } 1339 1340 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1341 /// unless they are marked attr(unused). 1342 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1343 FixItHint Hint; 1344 if (!ShouldDiagnoseUnusedDecl(D)) 1345 return; 1346 1347 GenerateFixForUnusedDecl(D, Context, Hint); 1348 1349 unsigned DiagID; 1350 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1351 DiagID = diag::warn_unused_exception_param; 1352 else if (isa<LabelDecl>(D)) 1353 DiagID = diag::warn_unused_label; 1354 else 1355 DiagID = diag::warn_unused_variable; 1356 1357 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1358 } 1359 1360 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1361 // Verify that we have no forward references left. If so, there was a goto 1362 // or address of a label taken, but no definition of it. Label fwd 1363 // definitions are indicated with a null substmt. 1364 if (L->getStmt() == 0) 1365 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1366 } 1367 1368 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1369 if (S->decl_empty()) return; 1370 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1371 "Scope shouldn't contain decls!"); 1372 1373 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1374 I != E; ++I) { 1375 Decl *TmpD = (*I); 1376 assert(TmpD && "This decl didn't get pushed??"); 1377 1378 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1379 NamedDecl *D = cast<NamedDecl>(TmpD); 1380 1381 if (!D->getDeclName()) continue; 1382 1383 // Diagnose unused variables in this scope. 1384 if (!S->hasUnrecoverableErrorOccurred()) 1385 DiagnoseUnusedDecl(D); 1386 1387 // If this was a forward reference to a label, verify it was defined. 1388 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1389 CheckPoppedLabel(LD, *this); 1390 1391 // Remove this name from our lexical scope. 1392 IdResolver.RemoveDecl(D); 1393 } 1394 } 1395 1396 void Sema::ActOnStartFunctionDeclarator() { 1397 ++InFunctionDeclarator; 1398 } 1399 1400 void Sema::ActOnEndFunctionDeclarator() { 1401 assert(InFunctionDeclarator); 1402 --InFunctionDeclarator; 1403 } 1404 1405 /// \brief Look for an Objective-C class in the translation unit. 1406 /// 1407 /// \param Id The name of the Objective-C class we're looking for. If 1408 /// typo-correction fixes this name, the Id will be updated 1409 /// to the fixed name. 1410 /// 1411 /// \param IdLoc The location of the name in the translation unit. 1412 /// 1413 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1414 /// if there is no class with the given name. 1415 /// 1416 /// \returns The declaration of the named Objective-C class, or NULL if the 1417 /// class could not be found. 1418 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1419 SourceLocation IdLoc, 1420 bool DoTypoCorrection) { 1421 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1422 // creation from this context. 1423 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1424 1425 if (!IDecl && DoTypoCorrection) { 1426 // Perform typo correction at the given location, but only if we 1427 // find an Objective-C class name. 1428 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1429 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1430 LookupOrdinaryName, TUScope, NULL, 1431 Validator)) { 1432 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1433 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1434 Id = IDecl->getIdentifier(); 1435 } 1436 } 1437 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1438 // This routine must always return a class definition, if any. 1439 if (Def && Def->getDefinition()) 1440 Def = Def->getDefinition(); 1441 return Def; 1442 } 1443 1444 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1445 /// from S, where a non-field would be declared. This routine copes 1446 /// with the difference between C and C++ scoping rules in structs and 1447 /// unions. For example, the following code is well-formed in C but 1448 /// ill-formed in C++: 1449 /// @code 1450 /// struct S6 { 1451 /// enum { BAR } e; 1452 /// }; 1453 /// 1454 /// void test_S6() { 1455 /// struct S6 a; 1456 /// a.e = BAR; 1457 /// } 1458 /// @endcode 1459 /// For the declaration of BAR, this routine will return a different 1460 /// scope. The scope S will be the scope of the unnamed enumeration 1461 /// within S6. In C++, this routine will return the scope associated 1462 /// with S6, because the enumeration's scope is a transparent 1463 /// context but structures can contain non-field names. In C, this 1464 /// routine will return the translation unit scope, since the 1465 /// enumeration's scope is a transparent context and structures cannot 1466 /// contain non-field names. 1467 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1468 while (((S->getFlags() & Scope::DeclScope) == 0) || 1469 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1470 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1471 S = S->getParent(); 1472 return S; 1473 } 1474 1475 /// \brief Looks up the declaration of "struct objc_super" and 1476 /// saves it for later use in building builtin declaration of 1477 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1478 /// pre-existing declaration exists no action takes place. 1479 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1480 IdentifierInfo *II) { 1481 if (!II->isStr("objc_msgSendSuper")) 1482 return; 1483 ASTContext &Context = ThisSema.Context; 1484 1485 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1486 SourceLocation(), Sema::LookupTagName); 1487 ThisSema.LookupName(Result, S); 1488 if (Result.getResultKind() == LookupResult::Found) 1489 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1490 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1491 } 1492 1493 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1494 /// file scope. lazily create a decl for it. ForRedeclaration is true 1495 /// if we're creating this built-in in anticipation of redeclaring the 1496 /// built-in. 1497 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1498 Scope *S, bool ForRedeclaration, 1499 SourceLocation Loc) { 1500 LookupPredefedObjCSuperType(*this, S, II); 1501 1502 Builtin::ID BID = (Builtin::ID)bid; 1503 1504 ASTContext::GetBuiltinTypeError Error; 1505 QualType R = Context.GetBuiltinType(BID, Error); 1506 switch (Error) { 1507 case ASTContext::GE_None: 1508 // Okay 1509 break; 1510 1511 case ASTContext::GE_Missing_stdio: 1512 if (ForRedeclaration) 1513 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1514 << Context.BuiltinInfo.GetName(BID); 1515 return 0; 1516 1517 case ASTContext::GE_Missing_setjmp: 1518 if (ForRedeclaration) 1519 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1520 << Context.BuiltinInfo.GetName(BID); 1521 return 0; 1522 1523 case ASTContext::GE_Missing_ucontext: 1524 if (ForRedeclaration) 1525 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1526 << Context.BuiltinInfo.GetName(BID); 1527 return 0; 1528 } 1529 1530 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1531 Diag(Loc, diag::ext_implicit_lib_function_decl) 1532 << Context.BuiltinInfo.GetName(BID) 1533 << R; 1534 if (Context.BuiltinInfo.getHeaderName(BID) && 1535 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1536 != DiagnosticsEngine::Ignored) 1537 Diag(Loc, diag::note_please_include_header) 1538 << Context.BuiltinInfo.getHeaderName(BID) 1539 << Context.BuiltinInfo.GetName(BID); 1540 } 1541 1542 DeclContext *Parent = Context.getTranslationUnitDecl(); 1543 if (getLangOpts().CPlusPlus) { 1544 LinkageSpecDecl *CLinkageDecl = 1545 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1546 LinkageSpecDecl::lang_c, false); 1547 CLinkageDecl->setImplicit(); 1548 Parent->addDecl(CLinkageDecl); 1549 Parent = CLinkageDecl; 1550 } 1551 1552 FunctionDecl *New = FunctionDecl::Create(Context, 1553 Parent, 1554 Loc, Loc, II, R, /*TInfo=*/0, 1555 SC_Extern, 1556 false, 1557 /*hasPrototype=*/true); 1558 New->setImplicit(); 1559 1560 // Create Decl objects for each parameter, adding them to the 1561 // FunctionDecl. 1562 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1563 SmallVector<ParmVarDecl*, 16> Params; 1564 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1565 ParmVarDecl *parm = 1566 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1567 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0); 1568 parm->setScopeInfo(0, i); 1569 Params.push_back(parm); 1570 } 1571 New->setParams(Params); 1572 } 1573 1574 AddKnownFunctionAttributes(New); 1575 RegisterLocallyScopedExternCDecl(New, S); 1576 1577 // TUScope is the translation-unit scope to insert this function into. 1578 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1579 // relate Scopes to DeclContexts, and probably eliminate CurContext 1580 // entirely, but we're not there yet. 1581 DeclContext *SavedContext = CurContext; 1582 CurContext = Parent; 1583 PushOnScopeChains(New, TUScope); 1584 CurContext = SavedContext; 1585 return New; 1586 } 1587 1588 /// \brief Filter out any previous declarations that the given declaration 1589 /// should not consider because they are not permitted to conflict, e.g., 1590 /// because they come from hidden sub-modules and do not refer to the same 1591 /// entity. 1592 static void filterNonConflictingPreviousDecls(ASTContext &context, 1593 NamedDecl *decl, 1594 LookupResult &previous){ 1595 // This is only interesting when modules are enabled. 1596 if (!context.getLangOpts().Modules) 1597 return; 1598 1599 // Empty sets are uninteresting. 1600 if (previous.empty()) 1601 return; 1602 1603 LookupResult::Filter filter = previous.makeFilter(); 1604 while (filter.hasNext()) { 1605 NamedDecl *old = filter.next(); 1606 1607 // Non-hidden declarations are never ignored. 1608 if (!old->isHidden()) 1609 continue; 1610 1611 if (!old->isExternallyVisible()) 1612 filter.erase(); 1613 } 1614 1615 filter.done(); 1616 } 1617 1618 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1619 QualType OldType; 1620 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1621 OldType = OldTypedef->getUnderlyingType(); 1622 else 1623 OldType = Context.getTypeDeclType(Old); 1624 QualType NewType = New->getUnderlyingType(); 1625 1626 if (NewType->isVariablyModifiedType()) { 1627 // Must not redefine a typedef with a variably-modified type. 1628 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1629 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1630 << Kind << NewType; 1631 if (Old->getLocation().isValid()) 1632 Diag(Old->getLocation(), diag::note_previous_definition); 1633 New->setInvalidDecl(); 1634 return true; 1635 } 1636 1637 if (OldType != NewType && 1638 !OldType->isDependentType() && 1639 !NewType->isDependentType() && 1640 !Context.hasSameType(OldType, NewType)) { 1641 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1642 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1643 << Kind << NewType << OldType; 1644 if (Old->getLocation().isValid()) 1645 Diag(Old->getLocation(), diag::note_previous_definition); 1646 New->setInvalidDecl(); 1647 return true; 1648 } 1649 return false; 1650 } 1651 1652 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1653 /// same name and scope as a previous declaration 'Old'. Figure out 1654 /// how to resolve this situation, merging decls or emitting 1655 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1656 /// 1657 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1658 // If the new decl is known invalid already, don't bother doing any 1659 // merging checks. 1660 if (New->isInvalidDecl()) return; 1661 1662 // Allow multiple definitions for ObjC built-in typedefs. 1663 // FIXME: Verify the underlying types are equivalent! 1664 if (getLangOpts().ObjC1) { 1665 const IdentifierInfo *TypeID = New->getIdentifier(); 1666 switch (TypeID->getLength()) { 1667 default: break; 1668 case 2: 1669 { 1670 if (!TypeID->isStr("id")) 1671 break; 1672 QualType T = New->getUnderlyingType(); 1673 if (!T->isPointerType()) 1674 break; 1675 if (!T->isVoidPointerType()) { 1676 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1677 if (!PT->isStructureType()) 1678 break; 1679 } 1680 Context.setObjCIdRedefinitionType(T); 1681 // Install the built-in type for 'id', ignoring the current definition. 1682 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1683 return; 1684 } 1685 case 5: 1686 if (!TypeID->isStr("Class")) 1687 break; 1688 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1689 // Install the built-in type for 'Class', ignoring the current definition. 1690 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1691 return; 1692 case 3: 1693 if (!TypeID->isStr("SEL")) 1694 break; 1695 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1696 // Install the built-in type for 'SEL', ignoring the current definition. 1697 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1698 return; 1699 } 1700 // Fall through - the typedef name was not a builtin type. 1701 } 1702 1703 // Verify the old decl was also a type. 1704 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1705 if (!Old) { 1706 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1707 << New->getDeclName(); 1708 1709 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1710 if (OldD->getLocation().isValid()) 1711 Diag(OldD->getLocation(), diag::note_previous_definition); 1712 1713 return New->setInvalidDecl(); 1714 } 1715 1716 // If the old declaration is invalid, just give up here. 1717 if (Old->isInvalidDecl()) 1718 return New->setInvalidDecl(); 1719 1720 // If the typedef types are not identical, reject them in all languages and 1721 // with any extensions enabled. 1722 if (isIncompatibleTypedef(Old, New)) 1723 return; 1724 1725 // The types match. Link up the redeclaration chain and merge attributes if 1726 // the old declaration was a typedef. 1727 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1728 New->setPreviousDecl(Typedef); 1729 mergeDeclAttributes(New, Old); 1730 } 1731 1732 if (getLangOpts().MicrosoftExt) 1733 return; 1734 1735 if (getLangOpts().CPlusPlus) { 1736 // C++ [dcl.typedef]p2: 1737 // In a given non-class scope, a typedef specifier can be used to 1738 // redefine the name of any type declared in that scope to refer 1739 // to the type to which it already refers. 1740 if (!isa<CXXRecordDecl>(CurContext)) 1741 return; 1742 1743 // C++0x [dcl.typedef]p4: 1744 // In a given class scope, a typedef specifier can be used to redefine 1745 // any class-name declared in that scope that is not also a typedef-name 1746 // to refer to the type to which it already refers. 1747 // 1748 // This wording came in via DR424, which was a correction to the 1749 // wording in DR56, which accidentally banned code like: 1750 // 1751 // struct S { 1752 // typedef struct A { } A; 1753 // }; 1754 // 1755 // in the C++03 standard. We implement the C++0x semantics, which 1756 // allow the above but disallow 1757 // 1758 // struct S { 1759 // typedef int I; 1760 // typedef int I; 1761 // }; 1762 // 1763 // since that was the intent of DR56. 1764 if (!isa<TypedefNameDecl>(Old)) 1765 return; 1766 1767 Diag(New->getLocation(), diag::err_redefinition) 1768 << New->getDeclName(); 1769 Diag(Old->getLocation(), diag::note_previous_definition); 1770 return New->setInvalidDecl(); 1771 } 1772 1773 // Modules always permit redefinition of typedefs, as does C11. 1774 if (getLangOpts().Modules || getLangOpts().C11) 1775 return; 1776 1777 // If we have a redefinition of a typedef in C, emit a warning. This warning 1778 // is normally mapped to an error, but can be controlled with 1779 // -Wtypedef-redefinition. If either the original or the redefinition is 1780 // in a system header, don't emit this for compatibility with GCC. 1781 if (getDiagnostics().getSuppressSystemWarnings() && 1782 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1783 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1784 return; 1785 1786 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1787 << New->getDeclName(); 1788 Diag(Old->getLocation(), diag::note_previous_definition); 1789 return; 1790 } 1791 1792 /// DeclhasAttr - returns true if decl Declaration already has the target 1793 /// attribute. 1794 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1795 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1796 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1797 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1798 if ((*i)->getKind() == A->getKind()) { 1799 if (Ann) { 1800 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1801 return true; 1802 continue; 1803 } 1804 // FIXME: Don't hardcode this check 1805 if (OA && isa<OwnershipAttr>(*i)) 1806 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1807 return true; 1808 } 1809 1810 return false; 1811 } 1812 1813 static bool isAttributeTargetADefinition(Decl *D) { 1814 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1815 return VD->isThisDeclarationADefinition(); 1816 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1817 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1818 return true; 1819 } 1820 1821 /// Merge alignment attributes from \p Old to \p New, taking into account the 1822 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1823 /// 1824 /// \return \c true if any attributes were added to \p New. 1825 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1826 // Look for alignas attributes on Old, and pick out whichever attribute 1827 // specifies the strictest alignment requirement. 1828 AlignedAttr *OldAlignasAttr = 0; 1829 AlignedAttr *OldStrictestAlignAttr = 0; 1830 unsigned OldAlign = 0; 1831 for (specific_attr_iterator<AlignedAttr> 1832 I = Old->specific_attr_begin<AlignedAttr>(), 1833 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1834 // FIXME: We have no way of representing inherited dependent alignments 1835 // in a case like: 1836 // template<int A, int B> struct alignas(A) X; 1837 // template<int A, int B> struct alignas(B) X {}; 1838 // For now, we just ignore any alignas attributes which are not on the 1839 // definition in such a case. 1840 if (I->isAlignmentDependent()) 1841 return false; 1842 1843 if (I->isAlignas()) 1844 OldAlignasAttr = *I; 1845 1846 unsigned Align = I->getAlignment(S.Context); 1847 if (Align > OldAlign) { 1848 OldAlign = Align; 1849 OldStrictestAlignAttr = *I; 1850 } 1851 } 1852 1853 // Look for alignas attributes on New. 1854 AlignedAttr *NewAlignasAttr = 0; 1855 unsigned NewAlign = 0; 1856 for (specific_attr_iterator<AlignedAttr> 1857 I = New->specific_attr_begin<AlignedAttr>(), 1858 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1859 if (I->isAlignmentDependent()) 1860 return false; 1861 1862 if (I->isAlignas()) 1863 NewAlignasAttr = *I; 1864 1865 unsigned Align = I->getAlignment(S.Context); 1866 if (Align > NewAlign) 1867 NewAlign = Align; 1868 } 1869 1870 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1871 // Both declarations have 'alignas' attributes. We require them to match. 1872 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1873 // fall short. (If two declarations both have alignas, they must both match 1874 // every definition, and so must match each other if there is a definition.) 1875 1876 // If either declaration only contains 'alignas(0)' specifiers, then it 1877 // specifies the natural alignment for the type. 1878 if (OldAlign == 0 || NewAlign == 0) { 1879 QualType Ty; 1880 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1881 Ty = VD->getType(); 1882 else 1883 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1884 1885 if (OldAlign == 0) 1886 OldAlign = S.Context.getTypeAlign(Ty); 1887 if (NewAlign == 0) 1888 NewAlign = S.Context.getTypeAlign(Ty); 1889 } 1890 1891 if (OldAlign != NewAlign) { 1892 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1893 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1894 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1895 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1896 } 1897 } 1898 1899 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1900 // C++11 [dcl.align]p6: 1901 // if any declaration of an entity has an alignment-specifier, 1902 // every defining declaration of that entity shall specify an 1903 // equivalent alignment. 1904 // C11 6.7.5/7: 1905 // If the definition of an object does not have an alignment 1906 // specifier, any other declaration of that object shall also 1907 // have no alignment specifier. 1908 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1909 << OldAlignasAttr; 1910 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1911 << OldAlignasAttr; 1912 } 1913 1914 bool AnyAdded = false; 1915 1916 // Ensure we have an attribute representing the strictest alignment. 1917 if (OldAlign > NewAlign) { 1918 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1919 Clone->setInherited(true); 1920 New->addAttr(Clone); 1921 AnyAdded = true; 1922 } 1923 1924 // Ensure we have an alignas attribute if the old declaration had one. 1925 if (OldAlignasAttr && !NewAlignasAttr && 1926 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1927 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1928 Clone->setInherited(true); 1929 New->addAttr(Clone); 1930 AnyAdded = true; 1931 } 1932 1933 return AnyAdded; 1934 } 1935 1936 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1937 bool Override) { 1938 InheritableAttr *NewAttr = NULL; 1939 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1940 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1941 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1942 AA->getIntroduced(), AA->getDeprecated(), 1943 AA->getObsoleted(), AA->getUnavailable(), 1944 AA->getMessage(), Override, 1945 AttrSpellingListIndex); 1946 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1947 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1948 AttrSpellingListIndex); 1949 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1950 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1951 AttrSpellingListIndex); 1952 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1953 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1954 AttrSpellingListIndex); 1955 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1956 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1957 AttrSpellingListIndex); 1958 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1959 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1960 FA->getFormatIdx(), FA->getFirstArg(), 1961 AttrSpellingListIndex); 1962 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1963 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1964 AttrSpellingListIndex); 1965 else if (isa<AlignedAttr>(Attr)) 1966 // AlignedAttrs are handled separately, because we need to handle all 1967 // such attributes on a declaration at the same time. 1968 NewAttr = 0; 1969 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 1970 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1971 1972 if (NewAttr) { 1973 NewAttr->setInherited(true); 1974 D->addAttr(NewAttr); 1975 return true; 1976 } 1977 1978 return false; 1979 } 1980 1981 static const Decl *getDefinition(const Decl *D) { 1982 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1983 return TD->getDefinition(); 1984 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1985 const VarDecl *Def = VD->getDefinition(); 1986 if (Def) 1987 return Def; 1988 return VD->getActingDefinition(); 1989 } 1990 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1991 const FunctionDecl* Def; 1992 if (FD->isDefined(Def)) 1993 return Def; 1994 } 1995 return NULL; 1996 } 1997 1998 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 1999 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2000 I != E; ++I) { 2001 Attr *Attribute = *I; 2002 if (Attribute->getKind() == Kind) 2003 return true; 2004 } 2005 return false; 2006 } 2007 2008 /// checkNewAttributesAfterDef - If we already have a definition, check that 2009 /// there are no new attributes in this declaration. 2010 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2011 if (!New->hasAttrs()) 2012 return; 2013 2014 const Decl *Def = getDefinition(Old); 2015 if (!Def || Def == New) 2016 return; 2017 2018 AttrVec &NewAttributes = New->getAttrs(); 2019 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2020 const Attr *NewAttribute = NewAttributes[I]; 2021 2022 if (isa<AliasAttr>(NewAttribute)) { 2023 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2024 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2025 else { 2026 VarDecl *VD = cast<VarDecl>(New); 2027 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2028 VarDecl::TentativeDefinition 2029 ? diag::err_alias_after_tentative 2030 : diag::err_redefinition; 2031 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2032 S.Diag(Def->getLocation(), diag::note_previous_definition); 2033 VD->setInvalidDecl(); 2034 } 2035 ++I; 2036 continue; 2037 } 2038 2039 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2040 // Tentative definitions are only interesting for the alias check above. 2041 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2042 ++I; 2043 continue; 2044 } 2045 } 2046 2047 if (hasAttribute(Def, NewAttribute->getKind())) { 2048 ++I; 2049 continue; // regular attr merging will take care of validating this. 2050 } 2051 2052 if (isa<C11NoReturnAttr>(NewAttribute)) { 2053 // C's _Noreturn is allowed to be added to a function after it is defined. 2054 ++I; 2055 continue; 2056 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2057 if (AA->isAlignas()) { 2058 // C++11 [dcl.align]p6: 2059 // if any declaration of an entity has an alignment-specifier, 2060 // every defining declaration of that entity shall specify an 2061 // equivalent alignment. 2062 // C11 6.7.5/7: 2063 // If the definition of an object does not have an alignment 2064 // specifier, any other declaration of that object shall also 2065 // have no alignment specifier. 2066 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2067 << AA; 2068 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2069 << AA; 2070 NewAttributes.erase(NewAttributes.begin() + I); 2071 --E; 2072 continue; 2073 } 2074 } 2075 2076 S.Diag(NewAttribute->getLocation(), 2077 diag::warn_attribute_precede_definition); 2078 S.Diag(Def->getLocation(), diag::note_previous_definition); 2079 NewAttributes.erase(NewAttributes.begin() + I); 2080 --E; 2081 } 2082 } 2083 2084 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2085 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2086 AvailabilityMergeKind AMK) { 2087 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2088 UsedAttr *NewAttr = OldAttr->clone(Context); 2089 NewAttr->setInherited(true); 2090 New->addAttr(NewAttr); 2091 } 2092 2093 if (!Old->hasAttrs() && !New->hasAttrs()) 2094 return; 2095 2096 // attributes declared post-definition are currently ignored 2097 checkNewAttributesAfterDef(*this, New, Old); 2098 2099 if (!Old->hasAttrs()) 2100 return; 2101 2102 bool foundAny = New->hasAttrs(); 2103 2104 // Ensure that any moving of objects within the allocated map is done before 2105 // we process them. 2106 if (!foundAny) New->setAttrs(AttrVec()); 2107 2108 for (specific_attr_iterator<InheritableAttr> 2109 i = Old->specific_attr_begin<InheritableAttr>(), 2110 e = Old->specific_attr_end<InheritableAttr>(); 2111 i != e; ++i) { 2112 bool Override = false; 2113 // Ignore deprecated/unavailable/availability attributes if requested. 2114 if (isa<DeprecatedAttr>(*i) || 2115 isa<UnavailableAttr>(*i) || 2116 isa<AvailabilityAttr>(*i)) { 2117 switch (AMK) { 2118 case AMK_None: 2119 continue; 2120 2121 case AMK_Redeclaration: 2122 break; 2123 2124 case AMK_Override: 2125 Override = true; 2126 break; 2127 } 2128 } 2129 2130 // Already handled. 2131 if (isa<UsedAttr>(*i)) 2132 continue; 2133 2134 if (mergeDeclAttribute(*this, New, *i, Override)) 2135 foundAny = true; 2136 } 2137 2138 if (mergeAlignedAttrs(*this, New, Old)) 2139 foundAny = true; 2140 2141 if (!foundAny) New->dropAttrs(); 2142 } 2143 2144 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2145 /// to the new one. 2146 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2147 const ParmVarDecl *oldDecl, 2148 Sema &S) { 2149 // C++11 [dcl.attr.depend]p2: 2150 // The first declaration of a function shall specify the 2151 // carries_dependency attribute for its declarator-id if any declaration 2152 // of the function specifies the carries_dependency attribute. 2153 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2154 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2155 S.Diag(CDA->getLocation(), 2156 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2157 // Find the first declaration of the parameter. 2158 // FIXME: Should we build redeclaration chains for function parameters? 2159 const FunctionDecl *FirstFD = 2160 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2161 const ParmVarDecl *FirstVD = 2162 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2163 S.Diag(FirstVD->getLocation(), 2164 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2165 } 2166 2167 if (!oldDecl->hasAttrs()) 2168 return; 2169 2170 bool foundAny = newDecl->hasAttrs(); 2171 2172 // Ensure that any moving of objects within the allocated map is 2173 // done before we process them. 2174 if (!foundAny) newDecl->setAttrs(AttrVec()); 2175 2176 for (specific_attr_iterator<InheritableParamAttr> 2177 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2178 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2179 if (!DeclHasAttr(newDecl, *i)) { 2180 InheritableAttr *newAttr = 2181 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2182 newAttr->setInherited(true); 2183 newDecl->addAttr(newAttr); 2184 foundAny = true; 2185 } 2186 } 2187 2188 if (!foundAny) newDecl->dropAttrs(); 2189 } 2190 2191 namespace { 2192 2193 /// Used in MergeFunctionDecl to keep track of function parameters in 2194 /// C. 2195 struct GNUCompatibleParamWarning { 2196 ParmVarDecl *OldParm; 2197 ParmVarDecl *NewParm; 2198 QualType PromotedType; 2199 }; 2200 2201 } 2202 2203 /// getSpecialMember - get the special member enum for a method. 2204 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2205 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2206 if (Ctor->isDefaultConstructor()) 2207 return Sema::CXXDefaultConstructor; 2208 2209 if (Ctor->isCopyConstructor()) 2210 return Sema::CXXCopyConstructor; 2211 2212 if (Ctor->isMoveConstructor()) 2213 return Sema::CXXMoveConstructor; 2214 } else if (isa<CXXDestructorDecl>(MD)) { 2215 return Sema::CXXDestructor; 2216 } else if (MD->isCopyAssignmentOperator()) { 2217 return Sema::CXXCopyAssignment; 2218 } else if (MD->isMoveAssignmentOperator()) { 2219 return Sema::CXXMoveAssignment; 2220 } 2221 2222 return Sema::CXXInvalid; 2223 } 2224 2225 /// canRedefineFunction - checks if a function can be redefined. Currently, 2226 /// only extern inline functions can be redefined, and even then only in 2227 /// GNU89 mode. 2228 static bool canRedefineFunction(const FunctionDecl *FD, 2229 const LangOptions& LangOpts) { 2230 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2231 !LangOpts.CPlusPlus && 2232 FD->isInlineSpecified() && 2233 FD->getStorageClass() == SC_Extern); 2234 } 2235 2236 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2237 const AttributedType *AT = T->getAs<AttributedType>(); 2238 while (AT && !AT->isCallingConv()) 2239 AT = AT->getModifiedType()->getAs<AttributedType>(); 2240 return AT; 2241 } 2242 2243 template <typename T> 2244 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2245 const DeclContext *DC = Old->getDeclContext(); 2246 if (DC->isRecord()) 2247 return false; 2248 2249 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2250 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2251 return true; 2252 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2253 return true; 2254 return false; 2255 } 2256 2257 /// MergeFunctionDecl - We just parsed a function 'New' from 2258 /// declarator D which has the same name and scope as a previous 2259 /// declaration 'Old'. Figure out how to resolve this situation, 2260 /// merging decls or emitting diagnostics as appropriate. 2261 /// 2262 /// In C++, New and Old must be declarations that are not 2263 /// overloaded. Use IsOverload to determine whether New and Old are 2264 /// overloaded, and to select the Old declaration that New should be 2265 /// merged with. 2266 /// 2267 /// Returns true if there was an error, false otherwise. 2268 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S, 2269 bool MergeTypeWithOld) { 2270 // Verify the old decl was also a function. 2271 FunctionDecl *Old = OldD->getAsFunction(); 2272 if (!Old) { 2273 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2274 if (New->getFriendObjectKind()) { 2275 Diag(New->getLocation(), diag::err_using_decl_friend); 2276 Diag(Shadow->getTargetDecl()->getLocation(), 2277 diag::note_using_decl_target); 2278 Diag(Shadow->getUsingDecl()->getLocation(), 2279 diag::note_using_decl) << 0; 2280 return true; 2281 } 2282 2283 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2284 Diag(Shadow->getTargetDecl()->getLocation(), 2285 diag::note_using_decl_target); 2286 Diag(Shadow->getUsingDecl()->getLocation(), 2287 diag::note_using_decl) << 0; 2288 return true; 2289 } 2290 2291 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2292 << New->getDeclName(); 2293 Diag(OldD->getLocation(), diag::note_previous_definition); 2294 return true; 2295 } 2296 2297 // If the old declaration is invalid, just give up here. 2298 if (Old->isInvalidDecl()) 2299 return true; 2300 2301 // Determine whether the previous declaration was a definition, 2302 // implicit declaration, or a declaration. 2303 diag::kind PrevDiag; 2304 if (Old->isThisDeclarationADefinition()) 2305 PrevDiag = diag::note_previous_definition; 2306 else if (Old->isImplicit()) 2307 PrevDiag = diag::note_previous_implicit_declaration; 2308 else 2309 PrevDiag = diag::note_previous_declaration; 2310 2311 // Don't complain about this if we're in GNU89 mode and the old function 2312 // is an extern inline function. 2313 // Don't complain about specializations. They are not supposed to have 2314 // storage classes. 2315 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2316 New->getStorageClass() == SC_Static && 2317 Old->hasExternalFormalLinkage() && 2318 !New->getTemplateSpecializationInfo() && 2319 !canRedefineFunction(Old, getLangOpts())) { 2320 if (getLangOpts().MicrosoftExt) { 2321 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2322 Diag(Old->getLocation(), PrevDiag); 2323 } else { 2324 Diag(New->getLocation(), diag::err_static_non_static) << New; 2325 Diag(Old->getLocation(), PrevDiag); 2326 return true; 2327 } 2328 } 2329 2330 2331 // If a function is first declared with a calling convention, but is later 2332 // declared or defined without one, all following decls assume the calling 2333 // convention of the first. 2334 // 2335 // It's OK if a function is first declared without a calling convention, 2336 // but is later declared or defined with the default calling convention. 2337 // 2338 // To test if either decl has an explicit calling convention, we look for 2339 // AttributedType sugar nodes on the type as written. If they are missing or 2340 // were canonicalized away, we assume the calling convention was implicit. 2341 // 2342 // Note also that we DO NOT return at this point, because we still have 2343 // other tests to run. 2344 QualType OldQType = Context.getCanonicalType(Old->getType()); 2345 QualType NewQType = Context.getCanonicalType(New->getType()); 2346 const FunctionType *OldType = cast<FunctionType>(OldQType); 2347 const FunctionType *NewType = cast<FunctionType>(NewQType); 2348 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2349 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2350 bool RequiresAdjustment = false; 2351 2352 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2353 FunctionDecl *First = Old->getFirstDecl(); 2354 const FunctionType *FT = 2355 First->getType().getCanonicalType()->castAs<FunctionType>(); 2356 FunctionType::ExtInfo FI = FT->getExtInfo(); 2357 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2358 if (!NewCCExplicit) { 2359 // Inherit the CC from the previous declaration if it was specified 2360 // there but not here. 2361 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2362 RequiresAdjustment = true; 2363 } else { 2364 // Calling conventions aren't compatible, so complain. 2365 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2366 Diag(New->getLocation(), diag::err_cconv_change) 2367 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2368 << !FirstCCExplicit 2369 << (!FirstCCExplicit ? "" : 2370 FunctionType::getNameForCallConv(FI.getCC())); 2371 2372 // Put the note on the first decl, since it is the one that matters. 2373 Diag(First->getLocation(), diag::note_previous_declaration); 2374 return true; 2375 } 2376 } 2377 2378 // FIXME: diagnose the other way around? 2379 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2380 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2381 RequiresAdjustment = true; 2382 } 2383 2384 // Merge regparm attribute. 2385 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2386 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2387 if (NewTypeInfo.getHasRegParm()) { 2388 Diag(New->getLocation(), diag::err_regparm_mismatch) 2389 << NewType->getRegParmType() 2390 << OldType->getRegParmType(); 2391 Diag(Old->getLocation(), diag::note_previous_declaration); 2392 return true; 2393 } 2394 2395 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2396 RequiresAdjustment = true; 2397 } 2398 2399 // Merge ns_returns_retained attribute. 2400 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2401 if (NewTypeInfo.getProducesResult()) { 2402 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2403 Diag(Old->getLocation(), diag::note_previous_declaration); 2404 return true; 2405 } 2406 2407 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2408 RequiresAdjustment = true; 2409 } 2410 2411 if (RequiresAdjustment) { 2412 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2413 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2414 New->setType(QualType(AdjustedType, 0)); 2415 NewQType = Context.getCanonicalType(New->getType()); 2416 NewType = cast<FunctionType>(NewQType); 2417 } 2418 2419 // If this redeclaration makes the function inline, we may need to add it to 2420 // UndefinedButUsed. 2421 if (!Old->isInlined() && New->isInlined() && 2422 !New->hasAttr<GNUInlineAttr>() && 2423 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2424 Old->isUsed(false) && 2425 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2426 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2427 SourceLocation())); 2428 2429 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2430 // about it. 2431 if (New->hasAttr<GNUInlineAttr>() && 2432 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2433 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2434 } 2435 2436 if (getLangOpts().CPlusPlus) { 2437 // (C++98 13.1p2): 2438 // Certain function declarations cannot be overloaded: 2439 // -- Function declarations that differ only in the return type 2440 // cannot be overloaded. 2441 2442 // Go back to the type source info to compare the declared return types, 2443 // per C++1y [dcl.type.auto]p13: 2444 // Redeclarations or specializations of a function or function template 2445 // with a declared return type that uses a placeholder type shall also 2446 // use that placeholder, not a deduced type. 2447 QualType OldDeclaredReturnType = 2448 (Old->getTypeSourceInfo() 2449 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2450 : OldType)->getReturnType(); 2451 QualType NewDeclaredReturnType = 2452 (New->getTypeSourceInfo() 2453 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2454 : NewType)->getReturnType(); 2455 QualType ResQT; 2456 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2457 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2458 New->isLocalExternDecl())) { 2459 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2460 OldDeclaredReturnType->isObjCObjectPointerType()) 2461 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2462 if (ResQT.isNull()) { 2463 if (New->isCXXClassMember() && New->isOutOfLine()) 2464 Diag(New->getLocation(), 2465 diag::err_member_def_does_not_match_ret_type) << New; 2466 else 2467 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2468 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2469 return true; 2470 } 2471 else 2472 NewQType = ResQT; 2473 } 2474 2475 QualType OldReturnType = OldType->getReturnType(); 2476 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2477 if (OldReturnType != NewReturnType) { 2478 // If this function has a deduced return type and has already been 2479 // defined, copy the deduced value from the old declaration. 2480 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2481 if (OldAT && OldAT->isDeduced()) { 2482 New->setType( 2483 SubstAutoType(New->getType(), 2484 OldAT->isDependentType() ? Context.DependentTy 2485 : OldAT->getDeducedType())); 2486 NewQType = Context.getCanonicalType( 2487 SubstAutoType(NewQType, 2488 OldAT->isDependentType() ? Context.DependentTy 2489 : OldAT->getDeducedType())); 2490 } 2491 } 2492 2493 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2494 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2495 if (OldMethod && NewMethod) { 2496 // Preserve triviality. 2497 NewMethod->setTrivial(OldMethod->isTrivial()); 2498 2499 // MSVC allows explicit template specialization at class scope: 2500 // 2 CXXMethodDecls referring to the same function will be injected. 2501 // We don't want a redeclaration error. 2502 bool IsClassScopeExplicitSpecialization = 2503 OldMethod->isFunctionTemplateSpecialization() && 2504 NewMethod->isFunctionTemplateSpecialization(); 2505 bool isFriend = NewMethod->getFriendObjectKind(); 2506 2507 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2508 !IsClassScopeExplicitSpecialization) { 2509 // -- Member function declarations with the same name and the 2510 // same parameter types cannot be overloaded if any of them 2511 // is a static member function declaration. 2512 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2513 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2514 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2515 return true; 2516 } 2517 2518 // C++ [class.mem]p1: 2519 // [...] A member shall not be declared twice in the 2520 // member-specification, except that a nested class or member 2521 // class template can be declared and then later defined. 2522 if (ActiveTemplateInstantiations.empty()) { 2523 unsigned NewDiag; 2524 if (isa<CXXConstructorDecl>(OldMethod)) 2525 NewDiag = diag::err_constructor_redeclared; 2526 else if (isa<CXXDestructorDecl>(NewMethod)) 2527 NewDiag = diag::err_destructor_redeclared; 2528 else if (isa<CXXConversionDecl>(NewMethod)) 2529 NewDiag = diag::err_conv_function_redeclared; 2530 else 2531 NewDiag = diag::err_member_redeclared; 2532 2533 Diag(New->getLocation(), NewDiag); 2534 } else { 2535 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2536 << New << New->getType(); 2537 } 2538 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2539 2540 // Complain if this is an explicit declaration of a special 2541 // member that was initially declared implicitly. 2542 // 2543 // As an exception, it's okay to befriend such methods in order 2544 // to permit the implicit constructor/destructor/operator calls. 2545 } else if (OldMethod->isImplicit()) { 2546 if (isFriend) { 2547 NewMethod->setImplicit(); 2548 } else { 2549 Diag(NewMethod->getLocation(), 2550 diag::err_definition_of_implicitly_declared_member) 2551 << New << getSpecialMember(OldMethod); 2552 return true; 2553 } 2554 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2555 Diag(NewMethod->getLocation(), 2556 diag::err_definition_of_explicitly_defaulted_member) 2557 << getSpecialMember(OldMethod); 2558 return true; 2559 } 2560 } 2561 2562 // C++11 [dcl.attr.noreturn]p1: 2563 // The first declaration of a function shall specify the noreturn 2564 // attribute if any declaration of that function specifies the noreturn 2565 // attribute. 2566 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2567 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2568 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2569 Diag(Old->getFirstDecl()->getLocation(), 2570 diag::note_noreturn_missing_first_decl); 2571 } 2572 2573 // C++11 [dcl.attr.depend]p2: 2574 // The first declaration of a function shall specify the 2575 // carries_dependency attribute for its declarator-id if any declaration 2576 // of the function specifies the carries_dependency attribute. 2577 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2578 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2579 Diag(CDA->getLocation(), 2580 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2581 Diag(Old->getFirstDecl()->getLocation(), 2582 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2583 } 2584 2585 // (C++98 8.3.5p3): 2586 // All declarations for a function shall agree exactly in both the 2587 // return type and the parameter-type-list. 2588 // We also want to respect all the extended bits except noreturn. 2589 2590 // noreturn should now match unless the old type info didn't have it. 2591 QualType OldQTypeForComparison = OldQType; 2592 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2593 assert(OldQType == QualType(OldType, 0)); 2594 const FunctionType *OldTypeForComparison 2595 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2596 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2597 assert(OldQTypeForComparison.isCanonical()); 2598 } 2599 2600 if (haveIncompatibleLanguageLinkages(Old, New)) { 2601 // As a special case, retain the language linkage from previous 2602 // declarations of a friend function as an extension. 2603 // 2604 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2605 // and is useful because there's otherwise no way to specify language 2606 // linkage within class scope. 2607 // 2608 // Check cautiously as the friend object kind isn't yet complete. 2609 if (New->getFriendObjectKind() != Decl::FOK_None) { 2610 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2611 Diag(Old->getLocation(), PrevDiag); 2612 } else { 2613 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2614 Diag(Old->getLocation(), PrevDiag); 2615 return true; 2616 } 2617 } 2618 2619 if (OldQTypeForComparison == NewQType) 2620 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2621 2622 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2623 New->isLocalExternDecl()) { 2624 // It's OK if we couldn't merge types for a local function declaraton 2625 // if either the old or new type is dependent. We'll merge the types 2626 // when we instantiate the function. 2627 return false; 2628 } 2629 2630 // Fall through for conflicting redeclarations and redefinitions. 2631 } 2632 2633 // C: Function types need to be compatible, not identical. This handles 2634 // duplicate function decls like "void f(int); void f(enum X);" properly. 2635 if (!getLangOpts().CPlusPlus && 2636 Context.typesAreCompatible(OldQType, NewQType)) { 2637 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2638 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2639 const FunctionProtoType *OldProto = 0; 2640 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2641 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2642 // The old declaration provided a function prototype, but the 2643 // new declaration does not. Merge in the prototype. 2644 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2645 SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(), 2646 OldProto->param_type_end()); 2647 NewQType = 2648 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2649 OldProto->getExtProtoInfo()); 2650 New->setType(NewQType); 2651 New->setHasInheritedPrototype(); 2652 2653 // Synthesize a parameter for each argument type. 2654 SmallVector<ParmVarDecl*, 16> Params; 2655 for (FunctionProtoType::param_type_iterator 2656 ParamType = OldProto->param_type_begin(), 2657 ParamEnd = OldProto->param_type_end(); 2658 ParamType != ParamEnd; ++ParamType) { 2659 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2660 SourceLocation(), 2661 SourceLocation(), 0, 2662 *ParamType, /*TInfo=*/0, 2663 SC_None, 2664 0); 2665 Param->setScopeInfo(0, Params.size()); 2666 Param->setImplicit(); 2667 Params.push_back(Param); 2668 } 2669 2670 New->setParams(Params); 2671 } 2672 2673 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2674 } 2675 2676 // GNU C permits a K&R definition to follow a prototype declaration 2677 // if the declared types of the parameters in the K&R definition 2678 // match the types in the prototype declaration, even when the 2679 // promoted types of the parameters from the K&R definition differ 2680 // from the types in the prototype. GCC then keeps the types from 2681 // the prototype. 2682 // 2683 // If a variadic prototype is followed by a non-variadic K&R definition, 2684 // the K&R definition becomes variadic. This is sort of an edge case, but 2685 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2686 // C99 6.9.1p8. 2687 if (!getLangOpts().CPlusPlus && 2688 Old->hasPrototype() && !New->hasPrototype() && 2689 New->getType()->getAs<FunctionProtoType>() && 2690 Old->getNumParams() == New->getNumParams()) { 2691 SmallVector<QualType, 16> ArgTypes; 2692 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2693 const FunctionProtoType *OldProto 2694 = Old->getType()->getAs<FunctionProtoType>(); 2695 const FunctionProtoType *NewProto 2696 = New->getType()->getAs<FunctionProtoType>(); 2697 2698 // Determine whether this is the GNU C extension. 2699 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2700 NewProto->getReturnType()); 2701 bool LooseCompatible = !MergedReturn.isNull(); 2702 for (unsigned Idx = 0, End = Old->getNumParams(); 2703 LooseCompatible && Idx != End; ++Idx) { 2704 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2705 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2706 if (Context.typesAreCompatible(OldParm->getType(), 2707 NewProto->getParamType(Idx))) { 2708 ArgTypes.push_back(NewParm->getType()); 2709 } else if (Context.typesAreCompatible(OldParm->getType(), 2710 NewParm->getType(), 2711 /*CompareUnqualified=*/true)) { 2712 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2713 NewProto->getParamType(Idx) }; 2714 Warnings.push_back(Warn); 2715 ArgTypes.push_back(NewParm->getType()); 2716 } else 2717 LooseCompatible = false; 2718 } 2719 2720 if (LooseCompatible) { 2721 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2722 Diag(Warnings[Warn].NewParm->getLocation(), 2723 diag::ext_param_promoted_not_compatible_with_prototype) 2724 << Warnings[Warn].PromotedType 2725 << Warnings[Warn].OldParm->getType(); 2726 if (Warnings[Warn].OldParm->getLocation().isValid()) 2727 Diag(Warnings[Warn].OldParm->getLocation(), 2728 diag::note_previous_declaration); 2729 } 2730 2731 if (MergeTypeWithOld) 2732 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2733 OldProto->getExtProtoInfo())); 2734 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2735 } 2736 2737 // Fall through to diagnose conflicting types. 2738 } 2739 2740 // A function that has already been declared has been redeclared or 2741 // defined with a different type; show an appropriate diagnostic. 2742 2743 // If the previous declaration was an implicitly-generated builtin 2744 // declaration, then at the very least we should use a specialized note. 2745 unsigned BuiltinID; 2746 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2747 // If it's actually a library-defined builtin function like 'malloc' 2748 // or 'printf', just warn about the incompatible redeclaration. 2749 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2750 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2751 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2752 << Old << Old->getType(); 2753 2754 // If this is a global redeclaration, just forget hereafter 2755 // about the "builtin-ness" of the function. 2756 // 2757 // Doing this for local extern declarations is problematic. If 2758 // the builtin declaration remains visible, a second invalid 2759 // local declaration will produce a hard error; if it doesn't 2760 // remain visible, a single bogus local redeclaration (which is 2761 // actually only a warning) could break all the downstream code. 2762 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2763 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2764 2765 return false; 2766 } 2767 2768 PrevDiag = diag::note_previous_builtin_declaration; 2769 } 2770 2771 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2772 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2773 return true; 2774 } 2775 2776 /// \brief Completes the merge of two function declarations that are 2777 /// known to be compatible. 2778 /// 2779 /// This routine handles the merging of attributes and other 2780 /// properties of function declarations from the old declaration to 2781 /// the new declaration, once we know that New is in fact a 2782 /// redeclaration of Old. 2783 /// 2784 /// \returns false 2785 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2786 Scope *S, bool MergeTypeWithOld) { 2787 // Merge the attributes 2788 mergeDeclAttributes(New, Old); 2789 2790 // Merge "pure" flag. 2791 if (Old->isPure()) 2792 New->setPure(); 2793 2794 // Merge "used" flag. 2795 if (Old->getMostRecentDecl()->isUsed(false)) 2796 New->setIsUsed(); 2797 2798 // Merge attributes from the parameters. These can mismatch with K&R 2799 // declarations. 2800 if (New->getNumParams() == Old->getNumParams()) 2801 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2802 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2803 *this); 2804 2805 if (getLangOpts().CPlusPlus) 2806 return MergeCXXFunctionDecl(New, Old, S); 2807 2808 // Merge the function types so the we get the composite types for the return 2809 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2810 // was visible. 2811 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2812 if (!Merged.isNull() && MergeTypeWithOld) 2813 New->setType(Merged); 2814 2815 return false; 2816 } 2817 2818 2819 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2820 ObjCMethodDecl *oldMethod) { 2821 2822 // Merge the attributes, including deprecated/unavailable 2823 AvailabilityMergeKind MergeKind = 2824 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2825 : AMK_Override; 2826 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2827 2828 // Merge attributes from the parameters. 2829 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2830 oe = oldMethod->param_end(); 2831 for (ObjCMethodDecl::param_iterator 2832 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2833 ni != ne && oi != oe; ++ni, ++oi) 2834 mergeParamDeclAttributes(*ni, *oi, *this); 2835 2836 CheckObjCMethodOverride(newMethod, oldMethod); 2837 } 2838 2839 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2840 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2841 /// emitting diagnostics as appropriate. 2842 /// 2843 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2844 /// to here in AddInitializerToDecl. We can't check them before the initializer 2845 /// is attached. 2846 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2847 bool MergeTypeWithOld) { 2848 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2849 return; 2850 2851 QualType MergedT; 2852 if (getLangOpts().CPlusPlus) { 2853 if (New->getType()->isUndeducedType()) { 2854 // We don't know what the new type is until the initializer is attached. 2855 return; 2856 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2857 // These could still be something that needs exception specs checked. 2858 return MergeVarDeclExceptionSpecs(New, Old); 2859 } 2860 // C++ [basic.link]p10: 2861 // [...] the types specified by all declarations referring to a given 2862 // object or function shall be identical, except that declarations for an 2863 // array object can specify array types that differ by the presence or 2864 // absence of a major array bound (8.3.4). 2865 else if (Old->getType()->isIncompleteArrayType() && 2866 New->getType()->isArrayType()) { 2867 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2868 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2869 if (Context.hasSameType(OldArray->getElementType(), 2870 NewArray->getElementType())) 2871 MergedT = New->getType(); 2872 } else if (Old->getType()->isArrayType() && 2873 New->getType()->isIncompleteArrayType()) { 2874 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2875 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2876 if (Context.hasSameType(OldArray->getElementType(), 2877 NewArray->getElementType())) 2878 MergedT = Old->getType(); 2879 } else if (New->getType()->isObjCObjectPointerType() && 2880 Old->getType()->isObjCObjectPointerType()) { 2881 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2882 Old->getType()); 2883 } 2884 } else { 2885 // C 6.2.7p2: 2886 // All declarations that refer to the same object or function shall have 2887 // compatible type. 2888 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2889 } 2890 if (MergedT.isNull()) { 2891 // It's OK if we couldn't merge types if either type is dependent, for a 2892 // block-scope variable. In other cases (static data members of class 2893 // templates, variable templates, ...), we require the types to be 2894 // equivalent. 2895 // FIXME: The C++ standard doesn't say anything about this. 2896 if ((New->getType()->isDependentType() || 2897 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2898 // If the old type was dependent, we can't merge with it, so the new type 2899 // becomes dependent for now. We'll reproduce the original type when we 2900 // instantiate the TypeSourceInfo for the variable. 2901 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2902 New->setType(Context.DependentTy); 2903 return; 2904 } 2905 2906 // FIXME: Even if this merging succeeds, some other non-visible declaration 2907 // of this variable might have an incompatible type. For instance: 2908 // 2909 // extern int arr[]; 2910 // void f() { extern int arr[2]; } 2911 // void g() { extern int arr[3]; } 2912 // 2913 // Neither C nor C++ requires a diagnostic for this, but we should still try 2914 // to diagnose it. 2915 Diag(New->getLocation(), diag::err_redefinition_different_type) 2916 << New->getDeclName() << New->getType() << Old->getType(); 2917 Diag(Old->getLocation(), diag::note_previous_definition); 2918 return New->setInvalidDecl(); 2919 } 2920 2921 // Don't actually update the type on the new declaration if the old 2922 // declaration was an extern declaration in a different scope. 2923 if (MergeTypeWithOld) 2924 New->setType(MergedT); 2925 } 2926 2927 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2928 LookupResult &Previous) { 2929 // C11 6.2.7p4: 2930 // For an identifier with internal or external linkage declared 2931 // in a scope in which a prior declaration of that identifier is 2932 // visible, if the prior declaration specifies internal or 2933 // external linkage, the type of the identifier at the later 2934 // declaration becomes the composite type. 2935 // 2936 // If the variable isn't visible, we do not merge with its type. 2937 if (Previous.isShadowed()) 2938 return false; 2939 2940 if (S.getLangOpts().CPlusPlus) { 2941 // C++11 [dcl.array]p3: 2942 // If there is a preceding declaration of the entity in the same 2943 // scope in which the bound was specified, an omitted array bound 2944 // is taken to be the same as in that earlier declaration. 2945 return NewVD->isPreviousDeclInSameBlockScope() || 2946 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2947 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2948 } else { 2949 // If the old declaration was function-local, don't merge with its 2950 // type unless we're in the same function. 2951 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2952 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2953 } 2954 } 2955 2956 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2957 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2958 /// situation, merging decls or emitting diagnostics as appropriate. 2959 /// 2960 /// Tentative definition rules (C99 6.9.2p2) are checked by 2961 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2962 /// definitions here, since the initializer hasn't been attached. 2963 /// 2964 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2965 // If the new decl is already invalid, don't do any other checking. 2966 if (New->isInvalidDecl()) 2967 return; 2968 2969 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 2970 2971 // Verify the old decl was also a variable or variable template. 2972 VarDecl *Old = 0; 2973 VarTemplateDecl *OldTemplate = 0; 2974 if (Previous.isSingleResult()) { 2975 if (NewTemplate) { 2976 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 2977 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0; 2978 } else 2979 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2980 } 2981 if (!Old) { 2982 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2983 << New->getDeclName(); 2984 Diag(Previous.getRepresentativeDecl()->getLocation(), 2985 diag::note_previous_definition); 2986 return New->setInvalidDecl(); 2987 } 2988 2989 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 2990 return; 2991 2992 // Ensure the template parameters are compatible. 2993 if (NewTemplate && 2994 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 2995 OldTemplate->getTemplateParameters(), 2996 /*Complain=*/true, TPL_TemplateMatch)) 2997 return; 2998 2999 // C++ [class.mem]p1: 3000 // A member shall not be declared twice in the member-specification [...] 3001 // 3002 // Here, we need only consider static data members. 3003 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3004 Diag(New->getLocation(), diag::err_duplicate_member) 3005 << New->getIdentifier(); 3006 Diag(Old->getLocation(), diag::note_previous_declaration); 3007 New->setInvalidDecl(); 3008 } 3009 3010 mergeDeclAttributes(New, Old); 3011 // Warn if an already-declared variable is made a weak_import in a subsequent 3012 // declaration 3013 if (New->hasAttr<WeakImportAttr>() && 3014 Old->getStorageClass() == SC_None && 3015 !Old->hasAttr<WeakImportAttr>()) { 3016 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3017 Diag(Old->getLocation(), diag::note_previous_definition); 3018 // Remove weak_import attribute on new declaration. 3019 New->dropAttr<WeakImportAttr>(); 3020 } 3021 3022 // Merge the types. 3023 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3024 3025 if (New->isInvalidDecl()) 3026 return; 3027 3028 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3029 if (New->getStorageClass() == SC_Static && 3030 !New->isStaticDataMember() && 3031 Old->hasExternalFormalLinkage()) { 3032 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3033 Diag(Old->getLocation(), diag::note_previous_definition); 3034 return New->setInvalidDecl(); 3035 } 3036 // C99 6.2.2p4: 3037 // For an identifier declared with the storage-class specifier 3038 // extern in a scope in which a prior declaration of that 3039 // identifier is visible,23) if the prior declaration specifies 3040 // internal or external linkage, the linkage of the identifier at 3041 // the later declaration is the same as the linkage specified at 3042 // the prior declaration. If no prior declaration is visible, or 3043 // if the prior declaration specifies no linkage, then the 3044 // identifier has external linkage. 3045 if (New->hasExternalStorage() && Old->hasLinkage()) 3046 /* Okay */; 3047 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3048 !New->isStaticDataMember() && 3049 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3050 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3051 Diag(Old->getLocation(), diag::note_previous_definition); 3052 return New->setInvalidDecl(); 3053 } 3054 3055 // Check if extern is followed by non-extern and vice-versa. 3056 if (New->hasExternalStorage() && 3057 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3058 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3059 Diag(Old->getLocation(), diag::note_previous_definition); 3060 return New->setInvalidDecl(); 3061 } 3062 if (Old->hasLinkage() && New->isLocalVarDecl() && 3063 !New->hasExternalStorage()) { 3064 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3065 Diag(Old->getLocation(), diag::note_previous_definition); 3066 return New->setInvalidDecl(); 3067 } 3068 3069 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3070 3071 // FIXME: The test for external storage here seems wrong? We still 3072 // need to check for mismatches. 3073 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3074 // Don't complain about out-of-line definitions of static members. 3075 !(Old->getLexicalDeclContext()->isRecord() && 3076 !New->getLexicalDeclContext()->isRecord())) { 3077 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3078 Diag(Old->getLocation(), diag::note_previous_definition); 3079 return New->setInvalidDecl(); 3080 } 3081 3082 if (New->getTLSKind() != Old->getTLSKind()) { 3083 if (!Old->getTLSKind()) { 3084 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3085 Diag(Old->getLocation(), diag::note_previous_declaration); 3086 } else if (!New->getTLSKind()) { 3087 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3088 Diag(Old->getLocation(), diag::note_previous_declaration); 3089 } else { 3090 // Do not allow redeclaration to change the variable between requiring 3091 // static and dynamic initialization. 3092 // FIXME: GCC allows this, but uses the TLS keyword on the first 3093 // declaration to determine the kind. Do we need to be compatible here? 3094 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3095 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3096 Diag(Old->getLocation(), diag::note_previous_declaration); 3097 } 3098 } 3099 3100 // C++ doesn't have tentative definitions, so go right ahead and check here. 3101 const VarDecl *Def; 3102 if (getLangOpts().CPlusPlus && 3103 New->isThisDeclarationADefinition() == VarDecl::Definition && 3104 (Def = Old->getDefinition())) { 3105 Diag(New->getLocation(), diag::err_redefinition) << New; 3106 Diag(Def->getLocation(), diag::note_previous_definition); 3107 New->setInvalidDecl(); 3108 return; 3109 } 3110 3111 if (haveIncompatibleLanguageLinkages(Old, New)) { 3112 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3113 Diag(Old->getLocation(), diag::note_previous_definition); 3114 New->setInvalidDecl(); 3115 return; 3116 } 3117 3118 // Merge "used" flag. 3119 if (Old->getMostRecentDecl()->isUsed(false)) 3120 New->setIsUsed(); 3121 3122 // Keep a chain of previous declarations. 3123 New->setPreviousDecl(Old); 3124 if (NewTemplate) 3125 NewTemplate->setPreviousDecl(OldTemplate); 3126 3127 // Inherit access appropriately. 3128 New->setAccess(Old->getAccess()); 3129 if (NewTemplate) 3130 NewTemplate->setAccess(New->getAccess()); 3131 } 3132 3133 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3134 /// no declarator (e.g. "struct foo;") is parsed. 3135 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3136 DeclSpec &DS) { 3137 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3138 } 3139 3140 static void HandleTagNumbering(Sema &S, const TagDecl *Tag) { 3141 if (!S.Context.getLangOpts().CPlusPlus) 3142 return; 3143 3144 if (isa<CXXRecordDecl>(Tag->getParent())) { 3145 // If this tag is the direct child of a class, number it if 3146 // it is anonymous. 3147 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3148 return; 3149 MangleNumberingContext &MCtx = 3150 S.Context.getManglingNumberContext(Tag->getParent()); 3151 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag)); 3152 return; 3153 } 3154 3155 // If this tag isn't a direct child of a class, number it if it is local. 3156 Decl *ManglingContextDecl; 3157 if (MangleNumberingContext *MCtx = 3158 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3159 ManglingContextDecl)) { 3160 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag)); 3161 } 3162 } 3163 3164 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3165 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3166 /// parameters to cope with template friend declarations. 3167 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3168 DeclSpec &DS, 3169 MultiTemplateParamsArg TemplateParams, 3170 bool IsExplicitInstantiation) { 3171 Decl *TagD = 0; 3172 TagDecl *Tag = 0; 3173 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3174 DS.getTypeSpecType() == DeclSpec::TST_struct || 3175 DS.getTypeSpecType() == DeclSpec::TST_interface || 3176 DS.getTypeSpecType() == DeclSpec::TST_union || 3177 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3178 TagD = DS.getRepAsDecl(); 3179 3180 if (!TagD) // We probably had an error 3181 return 0; 3182 3183 // Note that the above type specs guarantee that the 3184 // type rep is a Decl, whereas in many of the others 3185 // it's a Type. 3186 if (isa<TagDecl>(TagD)) 3187 Tag = cast<TagDecl>(TagD); 3188 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3189 Tag = CTD->getTemplatedDecl(); 3190 } 3191 3192 if (Tag) { 3193 HandleTagNumbering(*this, Tag); 3194 Tag->setFreeStanding(); 3195 if (Tag->isInvalidDecl()) 3196 return Tag; 3197 } 3198 3199 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3200 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3201 // or incomplete types shall not be restrict-qualified." 3202 if (TypeQuals & DeclSpec::TQ_restrict) 3203 Diag(DS.getRestrictSpecLoc(), 3204 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3205 << DS.getSourceRange(); 3206 } 3207 3208 if (DS.isConstexprSpecified()) { 3209 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3210 // and definitions of functions and variables. 3211 if (Tag) 3212 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3213 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3214 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3215 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3216 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3217 else 3218 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3219 // Don't emit warnings after this error. 3220 return TagD; 3221 } 3222 3223 DiagnoseFunctionSpecifiers(DS); 3224 3225 if (DS.isFriendSpecified()) { 3226 // If we're dealing with a decl but not a TagDecl, assume that 3227 // whatever routines created it handled the friendship aspect. 3228 if (TagD && !Tag) 3229 return 0; 3230 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3231 } 3232 3233 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3234 bool IsExplicitSpecialization = 3235 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3236 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3237 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3238 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3239 // nested-name-specifier unless it is an explicit instantiation 3240 // or an explicit specialization. 3241 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3242 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3243 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3244 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3245 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3246 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3247 << SS.getRange(); 3248 return 0; 3249 } 3250 3251 // Track whether this decl-specifier declares anything. 3252 bool DeclaresAnything = true; 3253 3254 // Handle anonymous struct definitions. 3255 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3256 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3257 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3258 if (getLangOpts().CPlusPlus || 3259 Record->getDeclContext()->isRecord()) 3260 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3261 3262 DeclaresAnything = false; 3263 } 3264 } 3265 3266 // Check for Microsoft C extension: anonymous struct member. 3267 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3268 CurContext->isRecord() && 3269 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3270 // Handle 2 kinds of anonymous struct: 3271 // struct STRUCT; 3272 // and 3273 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3274 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3275 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3276 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3277 DS.getRepAsType().get()->isStructureType())) { 3278 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3279 << DS.getSourceRange(); 3280 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3281 } 3282 } 3283 3284 // Skip all the checks below if we have a type error. 3285 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3286 (TagD && TagD->isInvalidDecl())) 3287 return TagD; 3288 3289 if (getLangOpts().CPlusPlus && 3290 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3291 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3292 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3293 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3294 DeclaresAnything = false; 3295 3296 if (!DS.isMissingDeclaratorOk()) { 3297 // Customize diagnostic for a typedef missing a name. 3298 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3299 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3300 << DS.getSourceRange(); 3301 else 3302 DeclaresAnything = false; 3303 } 3304 3305 if (DS.isModulePrivateSpecified() && 3306 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3307 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3308 << Tag->getTagKind() 3309 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3310 3311 ActOnDocumentableDecl(TagD); 3312 3313 // C 6.7/2: 3314 // A declaration [...] shall declare at least a declarator [...], a tag, 3315 // or the members of an enumeration. 3316 // C++ [dcl.dcl]p3: 3317 // [If there are no declarators], and except for the declaration of an 3318 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3319 // names into the program, or shall redeclare a name introduced by a 3320 // previous declaration. 3321 if (!DeclaresAnything) { 3322 // In C, we allow this as a (popular) extension / bug. Don't bother 3323 // producing further diagnostics for redundant qualifiers after this. 3324 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3325 return TagD; 3326 } 3327 3328 // C++ [dcl.stc]p1: 3329 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3330 // init-declarator-list of the declaration shall not be empty. 3331 // C++ [dcl.fct.spec]p1: 3332 // If a cv-qualifier appears in a decl-specifier-seq, the 3333 // init-declarator-list of the declaration shall not be empty. 3334 // 3335 // Spurious qualifiers here appear to be valid in C. 3336 unsigned DiagID = diag::warn_standalone_specifier; 3337 if (getLangOpts().CPlusPlus) 3338 DiagID = diag::ext_standalone_specifier; 3339 3340 // Note that a linkage-specification sets a storage class, but 3341 // 'extern "C" struct foo;' is actually valid and not theoretically 3342 // useless. 3343 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3344 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3345 Diag(DS.getStorageClassSpecLoc(), DiagID) 3346 << DeclSpec::getSpecifierName(SCS); 3347 3348 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3349 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3350 << DeclSpec::getSpecifierName(TSCS); 3351 if (DS.getTypeQualifiers()) { 3352 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3353 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3354 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3355 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3356 // Restrict is covered above. 3357 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3358 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3359 } 3360 3361 // Warn about ignored type attributes, for example: 3362 // __attribute__((aligned)) struct A; 3363 // Attributes should be placed after tag to apply to type declaration. 3364 if (!DS.getAttributes().empty()) { 3365 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3366 if (TypeSpecType == DeclSpec::TST_class || 3367 TypeSpecType == DeclSpec::TST_struct || 3368 TypeSpecType == DeclSpec::TST_interface || 3369 TypeSpecType == DeclSpec::TST_union || 3370 TypeSpecType == DeclSpec::TST_enum) { 3371 AttributeList* attrs = DS.getAttributes().getList(); 3372 while (attrs) { 3373 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3374 << attrs->getName() 3375 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3376 TypeSpecType == DeclSpec::TST_struct ? 1 : 3377 TypeSpecType == DeclSpec::TST_union ? 2 : 3378 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3379 attrs = attrs->getNext(); 3380 } 3381 } 3382 } 3383 3384 return TagD; 3385 } 3386 3387 /// We are trying to inject an anonymous member into the given scope; 3388 /// check if there's an existing declaration that can't be overloaded. 3389 /// 3390 /// \return true if this is a forbidden redeclaration 3391 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3392 Scope *S, 3393 DeclContext *Owner, 3394 DeclarationName Name, 3395 SourceLocation NameLoc, 3396 unsigned diagnostic) { 3397 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3398 Sema::ForRedeclaration); 3399 if (!SemaRef.LookupName(R, S)) return false; 3400 3401 if (R.getAsSingle<TagDecl>()) 3402 return false; 3403 3404 // Pick a representative declaration. 3405 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3406 assert(PrevDecl && "Expected a non-null Decl"); 3407 3408 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3409 return false; 3410 3411 SemaRef.Diag(NameLoc, diagnostic) << Name; 3412 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3413 3414 return true; 3415 } 3416 3417 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3418 /// anonymous struct or union AnonRecord into the owning context Owner 3419 /// and scope S. This routine will be invoked just after we realize 3420 /// that an unnamed union or struct is actually an anonymous union or 3421 /// struct, e.g., 3422 /// 3423 /// @code 3424 /// union { 3425 /// int i; 3426 /// float f; 3427 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3428 /// // f into the surrounding scope.x 3429 /// @endcode 3430 /// 3431 /// This routine is recursive, injecting the names of nested anonymous 3432 /// structs/unions into the owning context and scope as well. 3433 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3434 DeclContext *Owner, 3435 RecordDecl *AnonRecord, 3436 AccessSpecifier AS, 3437 SmallVectorImpl<NamedDecl *> &Chaining, 3438 bool MSAnonStruct) { 3439 unsigned diagKind 3440 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3441 : diag::err_anonymous_struct_member_redecl; 3442 3443 bool Invalid = false; 3444 3445 // Look every FieldDecl and IndirectFieldDecl with a name. 3446 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3447 DEnd = AnonRecord->decls_end(); 3448 D != DEnd; ++D) { 3449 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3450 cast<NamedDecl>(*D)->getDeclName()) { 3451 ValueDecl *VD = cast<ValueDecl>(*D); 3452 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3453 VD->getLocation(), diagKind)) { 3454 // C++ [class.union]p2: 3455 // The names of the members of an anonymous union shall be 3456 // distinct from the names of any other entity in the 3457 // scope in which the anonymous union is declared. 3458 Invalid = true; 3459 } else { 3460 // C++ [class.union]p2: 3461 // For the purpose of name lookup, after the anonymous union 3462 // definition, the members of the anonymous union are 3463 // considered to have been defined in the scope in which the 3464 // anonymous union is declared. 3465 unsigned OldChainingSize = Chaining.size(); 3466 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3467 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3468 PE = IF->chain_end(); PI != PE; ++PI) 3469 Chaining.push_back(*PI); 3470 else 3471 Chaining.push_back(VD); 3472 3473 assert(Chaining.size() >= 2); 3474 NamedDecl **NamedChain = 3475 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3476 for (unsigned i = 0; i < Chaining.size(); i++) 3477 NamedChain[i] = Chaining[i]; 3478 3479 IndirectFieldDecl* IndirectField = 3480 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3481 VD->getIdentifier(), VD->getType(), 3482 NamedChain, Chaining.size()); 3483 3484 IndirectField->setAccess(AS); 3485 IndirectField->setImplicit(); 3486 SemaRef.PushOnScopeChains(IndirectField, S); 3487 3488 // That includes picking up the appropriate access specifier. 3489 if (AS != AS_none) IndirectField->setAccess(AS); 3490 3491 Chaining.resize(OldChainingSize); 3492 } 3493 } 3494 } 3495 3496 return Invalid; 3497 } 3498 3499 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3500 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3501 /// illegal input values are mapped to SC_None. 3502 static StorageClass 3503 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3504 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3505 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3506 "Parser allowed 'typedef' as storage class VarDecl."); 3507 switch (StorageClassSpec) { 3508 case DeclSpec::SCS_unspecified: return SC_None; 3509 case DeclSpec::SCS_extern: 3510 if (DS.isExternInLinkageSpec()) 3511 return SC_None; 3512 return SC_Extern; 3513 case DeclSpec::SCS_static: return SC_Static; 3514 case DeclSpec::SCS_auto: return SC_Auto; 3515 case DeclSpec::SCS_register: return SC_Register; 3516 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3517 // Illegal SCSs map to None: error reporting is up to the caller. 3518 case DeclSpec::SCS_mutable: // Fall through. 3519 case DeclSpec::SCS_typedef: return SC_None; 3520 } 3521 llvm_unreachable("unknown storage class specifier"); 3522 } 3523 3524 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3525 assert(Record->hasInClassInitializer()); 3526 3527 for (DeclContext::decl_iterator I = Record->decls_begin(), 3528 E = Record->decls_end(); 3529 I != E; ++I) { 3530 FieldDecl *FD = dyn_cast<FieldDecl>(*I); 3531 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) 3532 FD = IFD->getAnonField(); 3533 if (FD && FD->hasInClassInitializer()) 3534 return FD->getLocation(); 3535 } 3536 3537 llvm_unreachable("couldn't find in-class initializer"); 3538 } 3539 3540 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3541 SourceLocation DefaultInitLoc) { 3542 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3543 return; 3544 3545 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3546 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3547 } 3548 3549 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3550 CXXRecordDecl *AnonUnion) { 3551 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3552 return; 3553 3554 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3555 } 3556 3557 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3558 /// anonymous structure or union. Anonymous unions are a C++ feature 3559 /// (C++ [class.union]) and a C11 feature; anonymous structures 3560 /// are a C11 feature and GNU C++ extension. 3561 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3562 AccessSpecifier AS, 3563 RecordDecl *Record, 3564 const PrintingPolicy &Policy) { 3565 DeclContext *Owner = Record->getDeclContext(); 3566 3567 // Diagnose whether this anonymous struct/union is an extension. 3568 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3569 Diag(Record->getLocation(), diag::ext_anonymous_union); 3570 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3571 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3572 else if (!Record->isUnion() && !getLangOpts().C11) 3573 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3574 3575 // C and C++ require different kinds of checks for anonymous 3576 // structs/unions. 3577 bool Invalid = false; 3578 if (getLangOpts().CPlusPlus) { 3579 const char* PrevSpec = 0; 3580 unsigned DiagID; 3581 if (Record->isUnion()) { 3582 // C++ [class.union]p6: 3583 // Anonymous unions declared in a named namespace or in the 3584 // global namespace shall be declared static. 3585 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3586 (isa<TranslationUnitDecl>(Owner) || 3587 (isa<NamespaceDecl>(Owner) && 3588 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3589 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3590 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3591 3592 // Recover by adding 'static'. 3593 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3594 PrevSpec, DiagID, Policy); 3595 } 3596 // C++ [class.union]p6: 3597 // A storage class is not allowed in a declaration of an 3598 // anonymous union in a class scope. 3599 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3600 isa<RecordDecl>(Owner)) { 3601 Diag(DS.getStorageClassSpecLoc(), 3602 diag::err_anonymous_union_with_storage_spec) 3603 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3604 3605 // Recover by removing the storage specifier. 3606 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3607 SourceLocation(), 3608 PrevSpec, DiagID, Context.getPrintingPolicy()); 3609 } 3610 } 3611 3612 // Ignore const/volatile/restrict qualifiers. 3613 if (DS.getTypeQualifiers()) { 3614 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3615 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3616 << Record->isUnion() << "const" 3617 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3618 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3619 Diag(DS.getVolatileSpecLoc(), 3620 diag::ext_anonymous_struct_union_qualified) 3621 << Record->isUnion() << "volatile" 3622 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3623 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3624 Diag(DS.getRestrictSpecLoc(), 3625 diag::ext_anonymous_struct_union_qualified) 3626 << Record->isUnion() << "restrict" 3627 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3628 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3629 Diag(DS.getAtomicSpecLoc(), 3630 diag::ext_anonymous_struct_union_qualified) 3631 << Record->isUnion() << "_Atomic" 3632 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3633 3634 DS.ClearTypeQualifiers(); 3635 } 3636 3637 // C++ [class.union]p2: 3638 // The member-specification of an anonymous union shall only 3639 // define non-static data members. [Note: nested types and 3640 // functions cannot be declared within an anonymous union. ] 3641 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3642 MemEnd = Record->decls_end(); 3643 Mem != MemEnd; ++Mem) { 3644 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3645 // C++ [class.union]p3: 3646 // An anonymous union shall not have private or protected 3647 // members (clause 11). 3648 assert(FD->getAccess() != AS_none); 3649 if (FD->getAccess() != AS_public) { 3650 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3651 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3652 Invalid = true; 3653 } 3654 3655 // C++ [class.union]p1 3656 // An object of a class with a non-trivial constructor, a non-trivial 3657 // copy constructor, a non-trivial destructor, or a non-trivial copy 3658 // assignment operator cannot be a member of a union, nor can an 3659 // array of such objects. 3660 if (CheckNontrivialField(FD)) 3661 Invalid = true; 3662 } else if ((*Mem)->isImplicit()) { 3663 // Any implicit members are fine. 3664 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3665 // This is a type that showed up in an 3666 // elaborated-type-specifier inside the anonymous struct or 3667 // union, but which actually declares a type outside of the 3668 // anonymous struct or union. It's okay. 3669 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3670 if (!MemRecord->isAnonymousStructOrUnion() && 3671 MemRecord->getDeclName()) { 3672 // Visual C++ allows type definition in anonymous struct or union. 3673 if (getLangOpts().MicrosoftExt) 3674 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3675 << (int)Record->isUnion(); 3676 else { 3677 // This is a nested type declaration. 3678 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3679 << (int)Record->isUnion(); 3680 Invalid = true; 3681 } 3682 } else { 3683 // This is an anonymous type definition within another anonymous type. 3684 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3685 // not part of standard C++. 3686 Diag(MemRecord->getLocation(), 3687 diag::ext_anonymous_record_with_anonymous_type) 3688 << (int)Record->isUnion(); 3689 } 3690 } else if (isa<AccessSpecDecl>(*Mem)) { 3691 // Any access specifier is fine. 3692 } else { 3693 // We have something that isn't a non-static data 3694 // member. Complain about it. 3695 unsigned DK = diag::err_anonymous_record_bad_member; 3696 if (isa<TypeDecl>(*Mem)) 3697 DK = diag::err_anonymous_record_with_type; 3698 else if (isa<FunctionDecl>(*Mem)) 3699 DK = diag::err_anonymous_record_with_function; 3700 else if (isa<VarDecl>(*Mem)) 3701 DK = diag::err_anonymous_record_with_static; 3702 3703 // Visual C++ allows type definition in anonymous struct or union. 3704 if (getLangOpts().MicrosoftExt && 3705 DK == diag::err_anonymous_record_with_type) 3706 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3707 << (int)Record->isUnion(); 3708 else { 3709 Diag((*Mem)->getLocation(), DK) 3710 << (int)Record->isUnion(); 3711 Invalid = true; 3712 } 3713 } 3714 } 3715 3716 // C++11 [class.union]p8 (DR1460): 3717 // At most one variant member of a union may have a 3718 // brace-or-equal-initializer. 3719 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3720 Owner->isRecord()) 3721 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3722 cast<CXXRecordDecl>(Record)); 3723 } 3724 3725 if (!Record->isUnion() && !Owner->isRecord()) { 3726 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3727 << (int)getLangOpts().CPlusPlus; 3728 Invalid = true; 3729 } 3730 3731 // Mock up a declarator. 3732 Declarator Dc(DS, Declarator::MemberContext); 3733 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3734 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3735 3736 // Create a declaration for this anonymous struct/union. 3737 NamedDecl *Anon = 0; 3738 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3739 Anon = FieldDecl::Create(Context, OwningClass, 3740 DS.getLocStart(), 3741 Record->getLocation(), 3742 /*IdentifierInfo=*/0, 3743 Context.getTypeDeclType(Record), 3744 TInfo, 3745 /*BitWidth=*/0, /*Mutable=*/false, 3746 /*InitStyle=*/ICIS_NoInit); 3747 Anon->setAccess(AS); 3748 if (getLangOpts().CPlusPlus) 3749 FieldCollector->Add(cast<FieldDecl>(Anon)); 3750 } else { 3751 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3752 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3753 if (SCSpec == DeclSpec::SCS_mutable) { 3754 // mutable can only appear on non-static class members, so it's always 3755 // an error here 3756 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3757 Invalid = true; 3758 SC = SC_None; 3759 } 3760 3761 Anon = VarDecl::Create(Context, Owner, 3762 DS.getLocStart(), 3763 Record->getLocation(), /*IdentifierInfo=*/0, 3764 Context.getTypeDeclType(Record), 3765 TInfo, SC); 3766 3767 // Default-initialize the implicit variable. This initialization will be 3768 // trivial in almost all cases, except if a union member has an in-class 3769 // initializer: 3770 // union { int n = 0; }; 3771 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3772 } 3773 Anon->setImplicit(); 3774 3775 // Mark this as an anonymous struct/union type. 3776 Record->setAnonymousStructOrUnion(true); 3777 3778 // Add the anonymous struct/union object to the current 3779 // context. We'll be referencing this object when we refer to one of 3780 // its members. 3781 Owner->addDecl(Anon); 3782 3783 // Inject the members of the anonymous struct/union into the owning 3784 // context and into the identifier resolver chain for name lookup 3785 // purposes. 3786 SmallVector<NamedDecl*, 2> Chain; 3787 Chain.push_back(Anon); 3788 3789 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3790 Chain, false)) 3791 Invalid = true; 3792 3793 if (Invalid) 3794 Anon->setInvalidDecl(); 3795 3796 return Anon; 3797 } 3798 3799 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3800 /// Microsoft C anonymous structure. 3801 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3802 /// Example: 3803 /// 3804 /// struct A { int a; }; 3805 /// struct B { struct A; int b; }; 3806 /// 3807 /// void foo() { 3808 /// B var; 3809 /// var.a = 3; 3810 /// } 3811 /// 3812 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3813 RecordDecl *Record) { 3814 3815 // If there is no Record, get the record via the typedef. 3816 if (!Record) 3817 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3818 3819 // Mock up a declarator. 3820 Declarator Dc(DS, Declarator::TypeNameContext); 3821 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3822 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3823 3824 // Create a declaration for this anonymous struct. 3825 NamedDecl* Anon = FieldDecl::Create(Context, 3826 cast<RecordDecl>(CurContext), 3827 DS.getLocStart(), 3828 DS.getLocStart(), 3829 /*IdentifierInfo=*/0, 3830 Context.getTypeDeclType(Record), 3831 TInfo, 3832 /*BitWidth=*/0, /*Mutable=*/false, 3833 /*InitStyle=*/ICIS_NoInit); 3834 Anon->setImplicit(); 3835 3836 // Add the anonymous struct object to the current context. 3837 CurContext->addDecl(Anon); 3838 3839 // Inject the members of the anonymous struct into the current 3840 // context and into the identifier resolver chain for name lookup 3841 // purposes. 3842 SmallVector<NamedDecl*, 2> Chain; 3843 Chain.push_back(Anon); 3844 3845 RecordDecl *RecordDef = Record->getDefinition(); 3846 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3847 RecordDef, AS_none, 3848 Chain, true)) 3849 Anon->setInvalidDecl(); 3850 3851 return Anon; 3852 } 3853 3854 /// GetNameForDeclarator - Determine the full declaration name for the 3855 /// given Declarator. 3856 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3857 return GetNameFromUnqualifiedId(D.getName()); 3858 } 3859 3860 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3861 DeclarationNameInfo 3862 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3863 DeclarationNameInfo NameInfo; 3864 NameInfo.setLoc(Name.StartLocation); 3865 3866 switch (Name.getKind()) { 3867 3868 case UnqualifiedId::IK_ImplicitSelfParam: 3869 case UnqualifiedId::IK_Identifier: 3870 NameInfo.setName(Name.Identifier); 3871 NameInfo.setLoc(Name.StartLocation); 3872 return NameInfo; 3873 3874 case UnqualifiedId::IK_OperatorFunctionId: 3875 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3876 Name.OperatorFunctionId.Operator)); 3877 NameInfo.setLoc(Name.StartLocation); 3878 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3879 = Name.OperatorFunctionId.SymbolLocations[0]; 3880 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3881 = Name.EndLocation.getRawEncoding(); 3882 return NameInfo; 3883 3884 case UnqualifiedId::IK_LiteralOperatorId: 3885 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3886 Name.Identifier)); 3887 NameInfo.setLoc(Name.StartLocation); 3888 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3889 return NameInfo; 3890 3891 case UnqualifiedId::IK_ConversionFunctionId: { 3892 TypeSourceInfo *TInfo; 3893 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3894 if (Ty.isNull()) 3895 return DeclarationNameInfo(); 3896 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3897 Context.getCanonicalType(Ty))); 3898 NameInfo.setLoc(Name.StartLocation); 3899 NameInfo.setNamedTypeInfo(TInfo); 3900 return NameInfo; 3901 } 3902 3903 case UnqualifiedId::IK_ConstructorName: { 3904 TypeSourceInfo *TInfo; 3905 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3906 if (Ty.isNull()) 3907 return DeclarationNameInfo(); 3908 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3909 Context.getCanonicalType(Ty))); 3910 NameInfo.setLoc(Name.StartLocation); 3911 NameInfo.setNamedTypeInfo(TInfo); 3912 return NameInfo; 3913 } 3914 3915 case UnqualifiedId::IK_ConstructorTemplateId: { 3916 // In well-formed code, we can only have a constructor 3917 // template-id that refers to the current context, so go there 3918 // to find the actual type being constructed. 3919 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3920 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3921 return DeclarationNameInfo(); 3922 3923 // Determine the type of the class being constructed. 3924 QualType CurClassType = Context.getTypeDeclType(CurClass); 3925 3926 // FIXME: Check two things: that the template-id names the same type as 3927 // CurClassType, and that the template-id does not occur when the name 3928 // was qualified. 3929 3930 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3931 Context.getCanonicalType(CurClassType))); 3932 NameInfo.setLoc(Name.StartLocation); 3933 // FIXME: should we retrieve TypeSourceInfo? 3934 NameInfo.setNamedTypeInfo(0); 3935 return NameInfo; 3936 } 3937 3938 case UnqualifiedId::IK_DestructorName: { 3939 TypeSourceInfo *TInfo; 3940 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3941 if (Ty.isNull()) 3942 return DeclarationNameInfo(); 3943 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3944 Context.getCanonicalType(Ty))); 3945 NameInfo.setLoc(Name.StartLocation); 3946 NameInfo.setNamedTypeInfo(TInfo); 3947 return NameInfo; 3948 } 3949 3950 case UnqualifiedId::IK_TemplateId: { 3951 TemplateName TName = Name.TemplateId->Template.get(); 3952 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3953 return Context.getNameForTemplate(TName, TNameLoc); 3954 } 3955 3956 } // switch (Name.getKind()) 3957 3958 llvm_unreachable("Unknown name kind"); 3959 } 3960 3961 static QualType getCoreType(QualType Ty) { 3962 do { 3963 if (Ty->isPointerType() || Ty->isReferenceType()) 3964 Ty = Ty->getPointeeType(); 3965 else if (Ty->isArrayType()) 3966 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3967 else 3968 return Ty.withoutLocalFastQualifiers(); 3969 } while (true); 3970 } 3971 3972 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3973 /// and Definition have "nearly" matching parameters. This heuristic is 3974 /// used to improve diagnostics in the case where an out-of-line function 3975 /// definition doesn't match any declaration within the class or namespace. 3976 /// Also sets Params to the list of indices to the parameters that differ 3977 /// between the declaration and the definition. If hasSimilarParameters 3978 /// returns true and Params is empty, then all of the parameters match. 3979 static bool hasSimilarParameters(ASTContext &Context, 3980 FunctionDecl *Declaration, 3981 FunctionDecl *Definition, 3982 SmallVectorImpl<unsigned> &Params) { 3983 Params.clear(); 3984 if (Declaration->param_size() != Definition->param_size()) 3985 return false; 3986 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3987 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3988 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3989 3990 // The parameter types are identical 3991 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3992 continue; 3993 3994 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3995 QualType DefParamBaseTy = getCoreType(DefParamTy); 3996 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3997 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3998 3999 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4000 (DeclTyName && DeclTyName == DefTyName)) 4001 Params.push_back(Idx); 4002 else // The two parameters aren't even close 4003 return false; 4004 } 4005 4006 return true; 4007 } 4008 4009 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4010 /// declarator needs to be rebuilt in the current instantiation. 4011 /// Any bits of declarator which appear before the name are valid for 4012 /// consideration here. That's specifically the type in the decl spec 4013 /// and the base type in any member-pointer chunks. 4014 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4015 DeclarationName Name) { 4016 // The types we specifically need to rebuild are: 4017 // - typenames, typeofs, and decltypes 4018 // - types which will become injected class names 4019 // Of course, we also need to rebuild any type referencing such a 4020 // type. It's safest to just say "dependent", but we call out a 4021 // few cases here. 4022 4023 DeclSpec &DS = D.getMutableDeclSpec(); 4024 switch (DS.getTypeSpecType()) { 4025 case DeclSpec::TST_typename: 4026 case DeclSpec::TST_typeofType: 4027 case DeclSpec::TST_underlyingType: 4028 case DeclSpec::TST_atomic: { 4029 // Grab the type from the parser. 4030 TypeSourceInfo *TSI = 0; 4031 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4032 if (T.isNull() || !T->isDependentType()) break; 4033 4034 // Make sure there's a type source info. This isn't really much 4035 // of a waste; most dependent types should have type source info 4036 // attached already. 4037 if (!TSI) 4038 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4039 4040 // Rebuild the type in the current instantiation. 4041 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4042 if (!TSI) return true; 4043 4044 // Store the new type back in the decl spec. 4045 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4046 DS.UpdateTypeRep(LocType); 4047 break; 4048 } 4049 4050 case DeclSpec::TST_decltype: 4051 case DeclSpec::TST_typeofExpr: { 4052 Expr *E = DS.getRepAsExpr(); 4053 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4054 if (Result.isInvalid()) return true; 4055 DS.UpdateExprRep(Result.get()); 4056 break; 4057 } 4058 4059 default: 4060 // Nothing to do for these decl specs. 4061 break; 4062 } 4063 4064 // It doesn't matter what order we do this in. 4065 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4066 DeclaratorChunk &Chunk = D.getTypeObject(I); 4067 4068 // The only type information in the declarator which can come 4069 // before the declaration name is the base type of a member 4070 // pointer. 4071 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4072 continue; 4073 4074 // Rebuild the scope specifier in-place. 4075 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4076 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4077 return true; 4078 } 4079 4080 return false; 4081 } 4082 4083 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4084 D.setFunctionDefinitionKind(FDK_Declaration); 4085 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4086 4087 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4088 Dcl && Dcl->getDeclContext()->isFileContext()) 4089 Dcl->setTopLevelDeclInObjCContainer(); 4090 4091 return Dcl; 4092 } 4093 4094 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4095 /// If T is the name of a class, then each of the following shall have a 4096 /// name different from T: 4097 /// - every static data member of class T; 4098 /// - every member function of class T 4099 /// - every member of class T that is itself a type; 4100 /// \returns true if the declaration name violates these rules. 4101 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4102 DeclarationNameInfo NameInfo) { 4103 DeclarationName Name = NameInfo.getName(); 4104 4105 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4106 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4107 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4108 return true; 4109 } 4110 4111 return false; 4112 } 4113 4114 /// \brief Diagnose a declaration whose declarator-id has the given 4115 /// nested-name-specifier. 4116 /// 4117 /// \param SS The nested-name-specifier of the declarator-id. 4118 /// 4119 /// \param DC The declaration context to which the nested-name-specifier 4120 /// resolves. 4121 /// 4122 /// \param Name The name of the entity being declared. 4123 /// 4124 /// \param Loc The location of the name of the entity being declared. 4125 /// 4126 /// \returns true if we cannot safely recover from this error, false otherwise. 4127 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4128 DeclarationName Name, 4129 SourceLocation Loc) { 4130 DeclContext *Cur = CurContext; 4131 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4132 Cur = Cur->getParent(); 4133 4134 // If the user provided a superfluous scope specifier that refers back to the 4135 // class in which the entity is already declared, diagnose and ignore it. 4136 // 4137 // class X { 4138 // void X::f(); 4139 // }; 4140 // 4141 // Note, it was once ill-formed to give redundant qualification in all 4142 // contexts, but that rule was removed by DR482. 4143 if (Cur->Equals(DC)) { 4144 if (Cur->isRecord()) { 4145 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4146 : diag::err_member_extra_qualification) 4147 << Name << FixItHint::CreateRemoval(SS.getRange()); 4148 SS.clear(); 4149 } else { 4150 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4151 } 4152 return false; 4153 } 4154 4155 // Check whether the qualifying scope encloses the scope of the original 4156 // declaration. 4157 if (!Cur->Encloses(DC)) { 4158 if (Cur->isRecord()) 4159 Diag(Loc, diag::err_member_qualification) 4160 << Name << SS.getRange(); 4161 else if (isa<TranslationUnitDecl>(DC)) 4162 Diag(Loc, diag::err_invalid_declarator_global_scope) 4163 << Name << SS.getRange(); 4164 else if (isa<FunctionDecl>(Cur)) 4165 Diag(Loc, diag::err_invalid_declarator_in_function) 4166 << Name << SS.getRange(); 4167 else if (isa<BlockDecl>(Cur)) 4168 Diag(Loc, diag::err_invalid_declarator_in_block) 4169 << Name << SS.getRange(); 4170 else 4171 Diag(Loc, diag::err_invalid_declarator_scope) 4172 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4173 4174 return true; 4175 } 4176 4177 if (Cur->isRecord()) { 4178 // Cannot qualify members within a class. 4179 Diag(Loc, diag::err_member_qualification) 4180 << Name << SS.getRange(); 4181 SS.clear(); 4182 4183 // C++ constructors and destructors with incorrect scopes can break 4184 // our AST invariants by having the wrong underlying types. If 4185 // that's the case, then drop this declaration entirely. 4186 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4187 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4188 !Context.hasSameType(Name.getCXXNameType(), 4189 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4190 return true; 4191 4192 return false; 4193 } 4194 4195 // C++11 [dcl.meaning]p1: 4196 // [...] "The nested-name-specifier of the qualified declarator-id shall 4197 // not begin with a decltype-specifer" 4198 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4199 while (SpecLoc.getPrefix()) 4200 SpecLoc = SpecLoc.getPrefix(); 4201 if (dyn_cast_or_null<DecltypeType>( 4202 SpecLoc.getNestedNameSpecifier()->getAsType())) 4203 Diag(Loc, diag::err_decltype_in_declarator) 4204 << SpecLoc.getTypeLoc().getSourceRange(); 4205 4206 return false; 4207 } 4208 4209 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4210 MultiTemplateParamsArg TemplateParamLists) { 4211 // TODO: consider using NameInfo for diagnostic. 4212 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4213 DeclarationName Name = NameInfo.getName(); 4214 4215 // All of these full declarators require an identifier. If it doesn't have 4216 // one, the ParsedFreeStandingDeclSpec action should be used. 4217 if (!Name) { 4218 if (!D.isInvalidType()) // Reject this if we think it is valid. 4219 Diag(D.getDeclSpec().getLocStart(), 4220 diag::err_declarator_need_ident) 4221 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4222 return 0; 4223 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4224 return 0; 4225 4226 // The scope passed in may not be a decl scope. Zip up the scope tree until 4227 // we find one that is. 4228 while ((S->getFlags() & Scope::DeclScope) == 0 || 4229 (S->getFlags() & Scope::TemplateParamScope) != 0) 4230 S = S->getParent(); 4231 4232 DeclContext *DC = CurContext; 4233 if (D.getCXXScopeSpec().isInvalid()) 4234 D.setInvalidType(); 4235 else if (D.getCXXScopeSpec().isSet()) { 4236 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4237 UPPC_DeclarationQualifier)) 4238 return 0; 4239 4240 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4241 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4242 if (!DC || isa<EnumDecl>(DC)) { 4243 // If we could not compute the declaration context, it's because the 4244 // declaration context is dependent but does not refer to a class, 4245 // class template, or class template partial specialization. Complain 4246 // and return early, to avoid the coming semantic disaster. 4247 Diag(D.getIdentifierLoc(), 4248 diag::err_template_qualified_declarator_no_match) 4249 << D.getCXXScopeSpec().getScopeRep() 4250 << D.getCXXScopeSpec().getRange(); 4251 return 0; 4252 } 4253 bool IsDependentContext = DC->isDependentContext(); 4254 4255 if (!IsDependentContext && 4256 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4257 return 0; 4258 4259 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4260 Diag(D.getIdentifierLoc(), 4261 diag::err_member_def_undefined_record) 4262 << Name << DC << D.getCXXScopeSpec().getRange(); 4263 D.setInvalidType(); 4264 } else if (!D.getDeclSpec().isFriendSpecified()) { 4265 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4266 Name, D.getIdentifierLoc())) { 4267 if (DC->isRecord()) 4268 return 0; 4269 4270 D.setInvalidType(); 4271 } 4272 } 4273 4274 // Check whether we need to rebuild the type of the given 4275 // declaration in the current instantiation. 4276 if (EnteringContext && IsDependentContext && 4277 TemplateParamLists.size() != 0) { 4278 ContextRAII SavedContext(*this, DC); 4279 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4280 D.setInvalidType(); 4281 } 4282 } 4283 4284 if (DiagnoseClassNameShadow(DC, NameInfo)) 4285 // If this is a typedef, we'll end up spewing multiple diagnostics. 4286 // Just return early; it's safer. 4287 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4288 return 0; 4289 4290 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4291 QualType R = TInfo->getType(); 4292 4293 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4294 UPPC_DeclarationType)) 4295 D.setInvalidType(); 4296 4297 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4298 ForRedeclaration); 4299 4300 // See if this is a redefinition of a variable in the same scope. 4301 if (!D.getCXXScopeSpec().isSet()) { 4302 bool IsLinkageLookup = false; 4303 bool CreateBuiltins = false; 4304 4305 // If the declaration we're planning to build will be a function 4306 // or object with linkage, then look for another declaration with 4307 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4308 // 4309 // If the declaration we're planning to build will be declared with 4310 // external linkage in the translation unit, create any builtin with 4311 // the same name. 4312 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4313 /* Do nothing*/; 4314 else if (CurContext->isFunctionOrMethod() && 4315 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4316 R->isFunctionType())) { 4317 IsLinkageLookup = true; 4318 CreateBuiltins = 4319 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4320 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4321 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4322 CreateBuiltins = true; 4323 4324 if (IsLinkageLookup) 4325 Previous.clear(LookupRedeclarationWithLinkage); 4326 4327 LookupName(Previous, S, CreateBuiltins); 4328 } else { // Something like "int foo::x;" 4329 LookupQualifiedName(Previous, DC); 4330 4331 // C++ [dcl.meaning]p1: 4332 // When the declarator-id is qualified, the declaration shall refer to a 4333 // previously declared member of the class or namespace to which the 4334 // qualifier refers (or, in the case of a namespace, of an element of the 4335 // inline namespace set of that namespace (7.3.1)) or to a specialization 4336 // thereof; [...] 4337 // 4338 // Note that we already checked the context above, and that we do not have 4339 // enough information to make sure that Previous contains the declaration 4340 // we want to match. For example, given: 4341 // 4342 // class X { 4343 // void f(); 4344 // void f(float); 4345 // }; 4346 // 4347 // void X::f(int) { } // ill-formed 4348 // 4349 // In this case, Previous will point to the overload set 4350 // containing the two f's declared in X, but neither of them 4351 // matches. 4352 4353 // C++ [dcl.meaning]p1: 4354 // [...] the member shall not merely have been introduced by a 4355 // using-declaration in the scope of the class or namespace nominated by 4356 // the nested-name-specifier of the declarator-id. 4357 RemoveUsingDecls(Previous); 4358 } 4359 4360 if (Previous.isSingleResult() && 4361 Previous.getFoundDecl()->isTemplateParameter()) { 4362 // Maybe we will complain about the shadowed template parameter. 4363 if (!D.isInvalidType()) 4364 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4365 Previous.getFoundDecl()); 4366 4367 // Just pretend that we didn't see the previous declaration. 4368 Previous.clear(); 4369 } 4370 4371 // In C++, the previous declaration we find might be a tag type 4372 // (class or enum). In this case, the new declaration will hide the 4373 // tag type. Note that this does does not apply if we're declaring a 4374 // typedef (C++ [dcl.typedef]p4). 4375 if (Previous.isSingleTagDecl() && 4376 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4377 Previous.clear(); 4378 4379 // Check that there are no default arguments other than in the parameters 4380 // of a function declaration (C++ only). 4381 if (getLangOpts().CPlusPlus) 4382 CheckExtraCXXDefaultArguments(D); 4383 4384 NamedDecl *New; 4385 4386 bool AddToScope = true; 4387 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4388 if (TemplateParamLists.size()) { 4389 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4390 return 0; 4391 } 4392 4393 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4394 } else if (R->isFunctionType()) { 4395 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4396 TemplateParamLists, 4397 AddToScope); 4398 } else { 4399 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4400 AddToScope); 4401 } 4402 4403 if (New == 0) 4404 return 0; 4405 4406 // If this has an identifier and is not an invalid redeclaration or 4407 // function template specialization, add it to the scope stack. 4408 if (New->getDeclName() && AddToScope && 4409 !(D.isRedeclaration() && New->isInvalidDecl())) { 4410 // Only make a locally-scoped extern declaration visible if it is the first 4411 // declaration of this entity. Qualified lookup for such an entity should 4412 // only find this declaration if there is no visible declaration of it. 4413 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4414 PushOnScopeChains(New, S, AddToContext); 4415 if (!AddToContext) 4416 CurContext->addHiddenDecl(New); 4417 } 4418 4419 return New; 4420 } 4421 4422 /// Helper method to turn variable array types into constant array 4423 /// types in certain situations which would otherwise be errors (for 4424 /// GCC compatibility). 4425 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4426 ASTContext &Context, 4427 bool &SizeIsNegative, 4428 llvm::APSInt &Oversized) { 4429 // This method tries to turn a variable array into a constant 4430 // array even when the size isn't an ICE. This is necessary 4431 // for compatibility with code that depends on gcc's buggy 4432 // constant expression folding, like struct {char x[(int)(char*)2];} 4433 SizeIsNegative = false; 4434 Oversized = 0; 4435 4436 if (T->isDependentType()) 4437 return QualType(); 4438 4439 QualifierCollector Qs; 4440 const Type *Ty = Qs.strip(T); 4441 4442 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4443 QualType Pointee = PTy->getPointeeType(); 4444 QualType FixedType = 4445 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4446 Oversized); 4447 if (FixedType.isNull()) return FixedType; 4448 FixedType = Context.getPointerType(FixedType); 4449 return Qs.apply(Context, FixedType); 4450 } 4451 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4452 QualType Inner = PTy->getInnerType(); 4453 QualType FixedType = 4454 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4455 Oversized); 4456 if (FixedType.isNull()) return FixedType; 4457 FixedType = Context.getParenType(FixedType); 4458 return Qs.apply(Context, FixedType); 4459 } 4460 4461 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4462 if (!VLATy) 4463 return QualType(); 4464 // FIXME: We should probably handle this case 4465 if (VLATy->getElementType()->isVariablyModifiedType()) 4466 return QualType(); 4467 4468 llvm::APSInt Res; 4469 if (!VLATy->getSizeExpr() || 4470 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4471 return QualType(); 4472 4473 // Check whether the array size is negative. 4474 if (Res.isSigned() && Res.isNegative()) { 4475 SizeIsNegative = true; 4476 return QualType(); 4477 } 4478 4479 // Check whether the array is too large to be addressed. 4480 unsigned ActiveSizeBits 4481 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4482 Res); 4483 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4484 Oversized = Res; 4485 return QualType(); 4486 } 4487 4488 return Context.getConstantArrayType(VLATy->getElementType(), 4489 Res, ArrayType::Normal, 0); 4490 } 4491 4492 static void 4493 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4494 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4495 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4496 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4497 DstPTL.getPointeeLoc()); 4498 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4499 return; 4500 } 4501 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4502 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4503 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4504 DstPTL.getInnerLoc()); 4505 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4506 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4507 return; 4508 } 4509 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4510 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4511 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4512 TypeLoc DstElemTL = DstATL.getElementLoc(); 4513 DstElemTL.initializeFullCopy(SrcElemTL); 4514 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4515 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4516 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4517 } 4518 4519 /// Helper method to turn variable array types into constant array 4520 /// types in certain situations which would otherwise be errors (for 4521 /// GCC compatibility). 4522 static TypeSourceInfo* 4523 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4524 ASTContext &Context, 4525 bool &SizeIsNegative, 4526 llvm::APSInt &Oversized) { 4527 QualType FixedTy 4528 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4529 SizeIsNegative, Oversized); 4530 if (FixedTy.isNull()) 4531 return 0; 4532 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4533 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4534 FixedTInfo->getTypeLoc()); 4535 return FixedTInfo; 4536 } 4537 4538 /// \brief Register the given locally-scoped extern "C" declaration so 4539 /// that it can be found later for redeclarations. We include any extern "C" 4540 /// declaration that is not visible in the translation unit here, not just 4541 /// function-scope declarations. 4542 void 4543 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4544 if (!getLangOpts().CPlusPlus && 4545 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4546 // Don't need to track declarations in the TU in C. 4547 return; 4548 4549 // Note that we have a locally-scoped external with this name. 4550 // FIXME: There can be multiple such declarations if they are functions marked 4551 // __attribute__((overloadable)) declared in function scope in C. 4552 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4553 } 4554 4555 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4556 if (ExternalSource) { 4557 // Load locally-scoped external decls from the external source. 4558 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4559 SmallVector<NamedDecl *, 4> Decls; 4560 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4561 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4562 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4563 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4564 if (Pos == LocallyScopedExternCDecls.end()) 4565 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4566 } 4567 } 4568 4569 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4570 return D ? D->getMostRecentDecl() : 0; 4571 } 4572 4573 /// \brief Diagnose function specifiers on a declaration of an identifier that 4574 /// does not identify a function. 4575 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4576 // FIXME: We should probably indicate the identifier in question to avoid 4577 // confusion for constructs like "inline int a(), b;" 4578 if (DS.isInlineSpecified()) 4579 Diag(DS.getInlineSpecLoc(), 4580 diag::err_inline_non_function); 4581 4582 if (DS.isVirtualSpecified()) 4583 Diag(DS.getVirtualSpecLoc(), 4584 diag::err_virtual_non_function); 4585 4586 if (DS.isExplicitSpecified()) 4587 Diag(DS.getExplicitSpecLoc(), 4588 diag::err_explicit_non_function); 4589 4590 if (DS.isNoreturnSpecified()) 4591 Diag(DS.getNoreturnSpecLoc(), 4592 diag::err_noreturn_non_function); 4593 } 4594 4595 NamedDecl* 4596 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4597 TypeSourceInfo *TInfo, LookupResult &Previous) { 4598 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4599 if (D.getCXXScopeSpec().isSet()) { 4600 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4601 << D.getCXXScopeSpec().getRange(); 4602 D.setInvalidType(); 4603 // Pretend we didn't see the scope specifier. 4604 DC = CurContext; 4605 Previous.clear(); 4606 } 4607 4608 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4609 4610 if (D.getDeclSpec().isConstexprSpecified()) 4611 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4612 << 1; 4613 4614 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4615 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4616 << D.getName().getSourceRange(); 4617 return 0; 4618 } 4619 4620 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4621 if (!NewTD) return 0; 4622 4623 // Handle attributes prior to checking for duplicates in MergeVarDecl 4624 ProcessDeclAttributes(S, NewTD, D); 4625 4626 CheckTypedefForVariablyModifiedType(S, NewTD); 4627 4628 bool Redeclaration = D.isRedeclaration(); 4629 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4630 D.setRedeclaration(Redeclaration); 4631 return ND; 4632 } 4633 4634 void 4635 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4636 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4637 // then it shall have block scope. 4638 // Note that variably modified types must be fixed before merging the decl so 4639 // that redeclarations will match. 4640 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4641 QualType T = TInfo->getType(); 4642 if (T->isVariablyModifiedType()) { 4643 getCurFunction()->setHasBranchProtectedScope(); 4644 4645 if (S->getFnParent() == 0) { 4646 bool SizeIsNegative; 4647 llvm::APSInt Oversized; 4648 TypeSourceInfo *FixedTInfo = 4649 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4650 SizeIsNegative, 4651 Oversized); 4652 if (FixedTInfo) { 4653 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4654 NewTD->setTypeSourceInfo(FixedTInfo); 4655 } else { 4656 if (SizeIsNegative) 4657 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4658 else if (T->isVariableArrayType()) 4659 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4660 else if (Oversized.getBoolValue()) 4661 Diag(NewTD->getLocation(), diag::err_array_too_large) 4662 << Oversized.toString(10); 4663 else 4664 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4665 NewTD->setInvalidDecl(); 4666 } 4667 } 4668 } 4669 } 4670 4671 4672 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4673 /// declares a typedef-name, either using the 'typedef' type specifier or via 4674 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4675 NamedDecl* 4676 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4677 LookupResult &Previous, bool &Redeclaration) { 4678 // Merge the decl with the existing one if appropriate. If the decl is 4679 // in an outer scope, it isn't the same thing. 4680 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4681 /*AllowInlineNamespace*/false); 4682 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4683 if (!Previous.empty()) { 4684 Redeclaration = true; 4685 MergeTypedefNameDecl(NewTD, Previous); 4686 } 4687 4688 // If this is the C FILE type, notify the AST context. 4689 if (IdentifierInfo *II = NewTD->getIdentifier()) 4690 if (!NewTD->isInvalidDecl() && 4691 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4692 if (II->isStr("FILE")) 4693 Context.setFILEDecl(NewTD); 4694 else if (II->isStr("jmp_buf")) 4695 Context.setjmp_bufDecl(NewTD); 4696 else if (II->isStr("sigjmp_buf")) 4697 Context.setsigjmp_bufDecl(NewTD); 4698 else if (II->isStr("ucontext_t")) 4699 Context.setucontext_tDecl(NewTD); 4700 } 4701 4702 return NewTD; 4703 } 4704 4705 /// \brief Determines whether the given declaration is an out-of-scope 4706 /// previous declaration. 4707 /// 4708 /// This routine should be invoked when name lookup has found a 4709 /// previous declaration (PrevDecl) that is not in the scope where a 4710 /// new declaration by the same name is being introduced. If the new 4711 /// declaration occurs in a local scope, previous declarations with 4712 /// linkage may still be considered previous declarations (C99 4713 /// 6.2.2p4-5, C++ [basic.link]p6). 4714 /// 4715 /// \param PrevDecl the previous declaration found by name 4716 /// lookup 4717 /// 4718 /// \param DC the context in which the new declaration is being 4719 /// declared. 4720 /// 4721 /// \returns true if PrevDecl is an out-of-scope previous declaration 4722 /// for a new delcaration with the same name. 4723 static bool 4724 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4725 ASTContext &Context) { 4726 if (!PrevDecl) 4727 return false; 4728 4729 if (!PrevDecl->hasLinkage()) 4730 return false; 4731 4732 if (Context.getLangOpts().CPlusPlus) { 4733 // C++ [basic.link]p6: 4734 // If there is a visible declaration of an entity with linkage 4735 // having the same name and type, ignoring entities declared 4736 // outside the innermost enclosing namespace scope, the block 4737 // scope declaration declares that same entity and receives the 4738 // linkage of the previous declaration. 4739 DeclContext *OuterContext = DC->getRedeclContext(); 4740 if (!OuterContext->isFunctionOrMethod()) 4741 // This rule only applies to block-scope declarations. 4742 return false; 4743 4744 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4745 if (PrevOuterContext->isRecord()) 4746 // We found a member function: ignore it. 4747 return false; 4748 4749 // Find the innermost enclosing namespace for the new and 4750 // previous declarations. 4751 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4752 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4753 4754 // The previous declaration is in a different namespace, so it 4755 // isn't the same function. 4756 if (!OuterContext->Equals(PrevOuterContext)) 4757 return false; 4758 } 4759 4760 return true; 4761 } 4762 4763 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4764 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4765 if (!SS.isSet()) return; 4766 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4767 } 4768 4769 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4770 QualType type = decl->getType(); 4771 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4772 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4773 // Various kinds of declaration aren't allowed to be __autoreleasing. 4774 unsigned kind = -1U; 4775 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4776 if (var->hasAttr<BlocksAttr>()) 4777 kind = 0; // __block 4778 else if (!var->hasLocalStorage()) 4779 kind = 1; // global 4780 } else if (isa<ObjCIvarDecl>(decl)) { 4781 kind = 3; // ivar 4782 } else if (isa<FieldDecl>(decl)) { 4783 kind = 2; // field 4784 } 4785 4786 if (kind != -1U) { 4787 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4788 << kind; 4789 } 4790 } else if (lifetime == Qualifiers::OCL_None) { 4791 // Try to infer lifetime. 4792 if (!type->isObjCLifetimeType()) 4793 return false; 4794 4795 lifetime = type->getObjCARCImplicitLifetime(); 4796 type = Context.getLifetimeQualifiedType(type, lifetime); 4797 decl->setType(type); 4798 } 4799 4800 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4801 // Thread-local variables cannot have lifetime. 4802 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4803 var->getTLSKind()) { 4804 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4805 << var->getType(); 4806 return true; 4807 } 4808 } 4809 4810 return false; 4811 } 4812 4813 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4814 // Ensure that an auto decl is deduced otherwise the checks below might cache 4815 // the wrong linkage. 4816 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4817 4818 // 'weak' only applies to declarations with external linkage. 4819 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4820 if (!ND.isExternallyVisible()) { 4821 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4822 ND.dropAttr<WeakAttr>(); 4823 } 4824 } 4825 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4826 if (ND.isExternallyVisible()) { 4827 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4828 ND.dropAttr<WeakRefAttr>(); 4829 } 4830 } 4831 4832 // 'selectany' only applies to externally visible varable declarations. 4833 // It does not apply to functions. 4834 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4835 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4836 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4837 ND.dropAttr<SelectAnyAttr>(); 4838 } 4839 } 4840 } 4841 4842 /// Given that we are within the definition of the given function, 4843 /// will that definition behave like C99's 'inline', where the 4844 /// definition is discarded except for optimization purposes? 4845 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4846 // Try to avoid calling GetGVALinkageForFunction. 4847 4848 // All cases of this require the 'inline' keyword. 4849 if (!FD->isInlined()) return false; 4850 4851 // This is only possible in C++ with the gnu_inline attribute. 4852 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4853 return false; 4854 4855 // Okay, go ahead and call the relatively-more-expensive function. 4856 4857 #ifndef NDEBUG 4858 // AST quite reasonably asserts that it's working on a function 4859 // definition. We don't really have a way to tell it that we're 4860 // currently defining the function, so just lie to it in +Asserts 4861 // builds. This is an awful hack. 4862 FD->setLazyBody(1); 4863 #endif 4864 4865 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4866 4867 #ifndef NDEBUG 4868 FD->setLazyBody(0); 4869 #endif 4870 4871 return isC99Inline; 4872 } 4873 4874 /// Determine whether a variable is extern "C" prior to attaching 4875 /// an initializer. We can't just call isExternC() here, because that 4876 /// will also compute and cache whether the declaration is externally 4877 /// visible, which might change when we attach the initializer. 4878 /// 4879 /// This can only be used if the declaration is known to not be a 4880 /// redeclaration of an internal linkage declaration. 4881 /// 4882 /// For instance: 4883 /// 4884 /// auto x = []{}; 4885 /// 4886 /// Attaching the initializer here makes this declaration not externally 4887 /// visible, because its type has internal linkage. 4888 /// 4889 /// FIXME: This is a hack. 4890 template<typename T> 4891 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4892 if (S.getLangOpts().CPlusPlus) { 4893 // In C++, the overloadable attribute negates the effects of extern "C". 4894 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4895 return false; 4896 } 4897 return D->isExternC(); 4898 } 4899 4900 static bool shouldConsiderLinkage(const VarDecl *VD) { 4901 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4902 if (DC->isFunctionOrMethod()) 4903 return VD->hasExternalStorage(); 4904 if (DC->isFileContext()) 4905 return true; 4906 if (DC->isRecord()) 4907 return false; 4908 llvm_unreachable("Unexpected context"); 4909 } 4910 4911 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4912 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4913 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4914 return true; 4915 if (DC->isRecord()) 4916 return false; 4917 llvm_unreachable("Unexpected context"); 4918 } 4919 4920 /// Adjust the \c DeclContext for a function or variable that might be a 4921 /// function-local external declaration. 4922 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 4923 if (!DC->isFunctionOrMethod()) 4924 return false; 4925 4926 // If this is a local extern function or variable declared within a function 4927 // template, don't add it into the enclosing namespace scope until it is 4928 // instantiated; it might have a dependent type right now. 4929 if (DC->isDependentContext()) 4930 return true; 4931 4932 // C++11 [basic.link]p7: 4933 // When a block scope declaration of an entity with linkage is not found to 4934 // refer to some other declaration, then that entity is a member of the 4935 // innermost enclosing namespace. 4936 // 4937 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 4938 // semantically-enclosing namespace, not a lexically-enclosing one. 4939 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 4940 DC = DC->getParent(); 4941 return true; 4942 } 4943 4944 NamedDecl * 4945 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4946 TypeSourceInfo *TInfo, LookupResult &Previous, 4947 MultiTemplateParamsArg TemplateParamLists, 4948 bool &AddToScope) { 4949 QualType R = TInfo->getType(); 4950 DeclarationName Name = GetNameForDeclarator(D).getName(); 4951 4952 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4953 VarDecl::StorageClass SC = 4954 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 4955 4956 DeclContext *OriginalDC = DC; 4957 bool IsLocalExternDecl = SC == SC_Extern && 4958 adjustContextForLocalExternDecl(DC); 4959 4960 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) { 4961 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4962 // half array type (unless the cl_khr_fp16 extension is enabled). 4963 if (Context.getBaseElementType(R)->isHalfType()) { 4964 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4965 D.setInvalidType(); 4966 } 4967 } 4968 4969 if (SCSpec == DeclSpec::SCS_mutable) { 4970 // mutable can only appear on non-static class members, so it's always 4971 // an error here 4972 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4973 D.setInvalidType(); 4974 SC = SC_None; 4975 } 4976 4977 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 4978 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 4979 D.getDeclSpec().getStorageClassSpecLoc())) { 4980 // In C++11, the 'register' storage class specifier is deprecated. 4981 // Suppress the warning in system macros, it's used in macros in some 4982 // popular C system headers, such as in glibc's htonl() macro. 4983 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4984 diag::warn_deprecated_register) 4985 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4986 } 4987 4988 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4989 if (!II) { 4990 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4991 << Name; 4992 return 0; 4993 } 4994 4995 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4996 4997 if (!DC->isRecord() && S->getFnParent() == 0) { 4998 // C99 6.9p2: The storage-class specifiers auto and register shall not 4999 // appear in the declaration specifiers in an external declaration. 5000 if (SC == SC_Auto || SC == SC_Register) { 5001 // If this is a register variable with an asm label specified, then this 5002 // is a GNU extension. 5003 if (SC == SC_Register && D.getAsmLabel()) 5004 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 5005 else 5006 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5007 D.setInvalidType(); 5008 } 5009 } 5010 5011 if (getLangOpts().OpenCL) { 5012 // Set up the special work-group-local storage class for variables in the 5013 // OpenCL __local address space. 5014 if (R.getAddressSpace() == LangAS::opencl_local) { 5015 SC = SC_OpenCLWorkGroupLocal; 5016 } 5017 5018 // OpenCL v1.2 s6.9.b p4: 5019 // The sampler type cannot be used with the __local and __global address 5020 // space qualifiers. 5021 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5022 R.getAddressSpace() == LangAS::opencl_global)) { 5023 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5024 } 5025 5026 // OpenCL 1.2 spec, p6.9 r: 5027 // The event type cannot be used to declare a program scope variable. 5028 // The event type cannot be used with the __local, __constant and __global 5029 // address space qualifiers. 5030 if (R->isEventT()) { 5031 if (S->getParent() == 0) { 5032 Diag(D.getLocStart(), diag::err_event_t_global_var); 5033 D.setInvalidType(); 5034 } 5035 5036 if (R.getAddressSpace()) { 5037 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5038 D.setInvalidType(); 5039 } 5040 } 5041 } 5042 5043 bool IsExplicitSpecialization = false; 5044 bool IsVariableTemplateSpecialization = false; 5045 bool IsPartialSpecialization = false; 5046 bool IsVariableTemplate = false; 5047 VarDecl *NewVD = 0; 5048 VarTemplateDecl *NewTemplate = 0; 5049 TemplateParameterList *TemplateParams = 0; 5050 if (!getLangOpts().CPlusPlus) { 5051 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5052 D.getIdentifierLoc(), II, 5053 R, TInfo, SC); 5054 5055 if (D.isInvalidType()) 5056 NewVD->setInvalidDecl(); 5057 } else { 5058 bool Invalid = false; 5059 5060 if (DC->isRecord() && !CurContext->isRecord()) { 5061 // This is an out-of-line definition of a static data member. 5062 switch (SC) { 5063 case SC_None: 5064 break; 5065 case SC_Static: 5066 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5067 diag::err_static_out_of_line) 5068 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5069 break; 5070 case SC_Auto: 5071 case SC_Register: 5072 case SC_Extern: 5073 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5074 // to names of variables declared in a block or to function parameters. 5075 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5076 // of class members 5077 5078 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5079 diag::err_storage_class_for_static_member) 5080 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5081 break; 5082 case SC_PrivateExtern: 5083 llvm_unreachable("C storage class in c++!"); 5084 case SC_OpenCLWorkGroupLocal: 5085 llvm_unreachable("OpenCL storage class in c++!"); 5086 } 5087 } 5088 5089 if (SC == SC_Static && CurContext->isRecord()) { 5090 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5091 if (RD->isLocalClass()) 5092 Diag(D.getIdentifierLoc(), 5093 diag::err_static_data_member_not_allowed_in_local_class) 5094 << Name << RD->getDeclName(); 5095 5096 // C++98 [class.union]p1: If a union contains a static data member, 5097 // the program is ill-formed. C++11 drops this restriction. 5098 if (RD->isUnion()) 5099 Diag(D.getIdentifierLoc(), 5100 getLangOpts().CPlusPlus11 5101 ? diag::warn_cxx98_compat_static_data_member_in_union 5102 : diag::ext_static_data_member_in_union) << Name; 5103 // We conservatively disallow static data members in anonymous structs. 5104 else if (!RD->getDeclName()) 5105 Diag(D.getIdentifierLoc(), 5106 diag::err_static_data_member_not_allowed_in_anon_struct) 5107 << Name << RD->isUnion(); 5108 } 5109 } 5110 5111 // Match up the template parameter lists with the scope specifier, then 5112 // determine whether we have a template or a template specialization. 5113 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5114 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5115 D.getCXXScopeSpec(), TemplateParamLists, 5116 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5117 5118 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId && 5119 !TemplateParams) { 5120 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5121 5122 // We have encountered something that the user meant to be a 5123 // specialization (because it has explicitly-specified template 5124 // arguments) but that was not introduced with a "template<>" (or had 5125 // too few of them). 5126 // FIXME: Differentiate between attempts for explicit instantiations 5127 // (starting with "template") and the rest. 5128 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5129 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5130 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5131 "template<> "); 5132 IsExplicitSpecialization = true; 5133 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(), 5134 SourceLocation(), 0, 0, 5135 SourceLocation()); 5136 } 5137 5138 if (TemplateParams) { 5139 if (!TemplateParams->size() && 5140 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5141 // There is an extraneous 'template<>' for this variable. Complain 5142 // about it, but allow the declaration of the variable. 5143 Diag(TemplateParams->getTemplateLoc(), 5144 diag::err_template_variable_noparams) 5145 << II 5146 << SourceRange(TemplateParams->getTemplateLoc(), 5147 TemplateParams->getRAngleLoc()); 5148 TemplateParams = 0; 5149 } else { 5150 // Only C++1y supports variable templates (N3651). 5151 Diag(D.getIdentifierLoc(), 5152 getLangOpts().CPlusPlus1y 5153 ? diag::warn_cxx11_compat_variable_template 5154 : diag::ext_variable_template); 5155 5156 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5157 // This is an explicit specialization or a partial specialization. 5158 // FIXME: Check that we can declare a specialization here. 5159 IsVariableTemplateSpecialization = true; 5160 IsPartialSpecialization = TemplateParams->size() > 0; 5161 } else { // if (TemplateParams->size() > 0) 5162 // This is a template declaration. 5163 IsVariableTemplate = true; 5164 5165 // Check that we can declare a template here. 5166 if (CheckTemplateDeclScope(S, TemplateParams)) 5167 return 0; 5168 } 5169 } 5170 } 5171 5172 if (IsVariableTemplateSpecialization) { 5173 SourceLocation TemplateKWLoc = 5174 TemplateParamLists.size() > 0 5175 ? TemplateParamLists[0]->getTemplateLoc() 5176 : SourceLocation(); 5177 DeclResult Res = ActOnVarTemplateSpecialization( 5178 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5179 IsPartialSpecialization); 5180 if (Res.isInvalid()) 5181 return 0; 5182 NewVD = cast<VarDecl>(Res.get()); 5183 AddToScope = false; 5184 } else 5185 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5186 D.getIdentifierLoc(), II, R, TInfo, SC); 5187 5188 // If this is supposed to be a variable template, create it as such. 5189 if (IsVariableTemplate) { 5190 NewTemplate = 5191 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5192 TemplateParams, NewVD); 5193 NewVD->setDescribedVarTemplate(NewTemplate); 5194 } 5195 5196 // If this decl has an auto type in need of deduction, make a note of the 5197 // Decl so we can diagnose uses of it in its own initializer. 5198 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5199 ParsingInitForAutoVars.insert(NewVD); 5200 5201 if (D.isInvalidType() || Invalid) { 5202 NewVD->setInvalidDecl(); 5203 if (NewTemplate) 5204 NewTemplate->setInvalidDecl(); 5205 } 5206 5207 SetNestedNameSpecifier(NewVD, D); 5208 5209 // If we have any template parameter lists that don't directly belong to 5210 // the variable (matching the scope specifier), store them. 5211 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5212 if (TemplateParamLists.size() > VDTemplateParamLists) 5213 NewVD->setTemplateParameterListsInfo( 5214 Context, TemplateParamLists.size() - VDTemplateParamLists, 5215 TemplateParamLists.data()); 5216 5217 if (D.getDeclSpec().isConstexprSpecified()) 5218 NewVD->setConstexpr(true); 5219 } 5220 5221 // Set the lexical context. If the declarator has a C++ scope specifier, the 5222 // lexical context will be different from the semantic context. 5223 NewVD->setLexicalDeclContext(CurContext); 5224 if (NewTemplate) 5225 NewTemplate->setLexicalDeclContext(CurContext); 5226 5227 if (IsLocalExternDecl) 5228 NewVD->setLocalExternDecl(); 5229 5230 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5231 if (NewVD->hasLocalStorage()) { 5232 // C++11 [dcl.stc]p4: 5233 // When thread_local is applied to a variable of block scope the 5234 // storage-class-specifier static is implied if it does not appear 5235 // explicitly. 5236 // Core issue: 'static' is not implied if the variable is declared 5237 // 'extern'. 5238 if (SCSpec == DeclSpec::SCS_unspecified && 5239 TSCS == DeclSpec::TSCS_thread_local && 5240 DC->isFunctionOrMethod()) 5241 NewVD->setTSCSpec(TSCS); 5242 else 5243 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5244 diag::err_thread_non_global) 5245 << DeclSpec::getSpecifierName(TSCS); 5246 } else if (!Context.getTargetInfo().isTLSSupported()) 5247 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5248 diag::err_thread_unsupported); 5249 else 5250 NewVD->setTSCSpec(TSCS); 5251 } 5252 5253 // C99 6.7.4p3 5254 // An inline definition of a function with external linkage shall 5255 // not contain a definition of a modifiable object with static or 5256 // thread storage duration... 5257 // We only apply this when the function is required to be defined 5258 // elsewhere, i.e. when the function is not 'extern inline'. Note 5259 // that a local variable with thread storage duration still has to 5260 // be marked 'static'. Also note that it's possible to get these 5261 // semantics in C++ using __attribute__((gnu_inline)). 5262 if (SC == SC_Static && S->getFnParent() != 0 && 5263 !NewVD->getType().isConstQualified()) { 5264 FunctionDecl *CurFD = getCurFunctionDecl(); 5265 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5266 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5267 diag::warn_static_local_in_extern_inline); 5268 MaybeSuggestAddingStaticToDecl(CurFD); 5269 } 5270 } 5271 5272 if (D.getDeclSpec().isModulePrivateSpecified()) { 5273 if (IsVariableTemplateSpecialization) 5274 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5275 << (IsPartialSpecialization ? 1 : 0) 5276 << FixItHint::CreateRemoval( 5277 D.getDeclSpec().getModulePrivateSpecLoc()); 5278 else if (IsExplicitSpecialization) 5279 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5280 << 2 5281 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5282 else if (NewVD->hasLocalStorage()) 5283 Diag(NewVD->getLocation(), diag::err_module_private_local) 5284 << 0 << NewVD->getDeclName() 5285 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5286 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5287 else { 5288 NewVD->setModulePrivate(); 5289 if (NewTemplate) 5290 NewTemplate->setModulePrivate(); 5291 } 5292 } 5293 5294 // Handle attributes prior to checking for duplicates in MergeVarDecl 5295 ProcessDeclAttributes(S, NewVD, D); 5296 5297 if (NewVD->hasAttrs()) 5298 CheckAlignasUnderalignment(NewVD); 5299 5300 if (getLangOpts().CUDA) { 5301 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5302 // storage [duration]." 5303 if (SC == SC_None && S->getFnParent() != 0 && 5304 (NewVD->hasAttr<CUDASharedAttr>() || 5305 NewVD->hasAttr<CUDAConstantAttr>())) { 5306 NewVD->setStorageClass(SC_Static); 5307 } 5308 } 5309 5310 // In auto-retain/release, infer strong retension for variables of 5311 // retainable type. 5312 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5313 NewVD->setInvalidDecl(); 5314 5315 // Handle GNU asm-label extension (encoded as an attribute). 5316 if (Expr *E = (Expr*)D.getAsmLabel()) { 5317 // The parser guarantees this is a string. 5318 StringLiteral *SE = cast<StringLiteral>(E); 5319 StringRef Label = SE->getString(); 5320 if (S->getFnParent() != 0) { 5321 switch (SC) { 5322 case SC_None: 5323 case SC_Auto: 5324 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5325 break; 5326 case SC_Register: 5327 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5328 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5329 break; 5330 case SC_Static: 5331 case SC_Extern: 5332 case SC_PrivateExtern: 5333 case SC_OpenCLWorkGroupLocal: 5334 break; 5335 } 5336 } 5337 5338 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5339 Context, Label, 0)); 5340 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5341 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5342 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5343 if (I != ExtnameUndeclaredIdentifiers.end()) { 5344 NewVD->addAttr(I->second); 5345 ExtnameUndeclaredIdentifiers.erase(I); 5346 } 5347 } 5348 5349 // Diagnose shadowed variables before filtering for scope. 5350 if (D.getCXXScopeSpec().isEmpty()) 5351 CheckShadow(S, NewVD, Previous); 5352 5353 // Don't consider existing declarations that are in a different 5354 // scope and are out-of-semantic-context declarations (if the new 5355 // declaration has linkage). 5356 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5357 D.getCXXScopeSpec().isNotEmpty() || 5358 IsExplicitSpecialization || 5359 IsVariableTemplateSpecialization); 5360 5361 // Check whether the previous declaration is in the same block scope. This 5362 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5363 if (getLangOpts().CPlusPlus && 5364 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5365 NewVD->setPreviousDeclInSameBlockScope( 5366 Previous.isSingleResult() && !Previous.isShadowed() && 5367 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5368 5369 if (!getLangOpts().CPlusPlus) { 5370 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5371 } else { 5372 // If this is an explicit specialization of a static data member, check it. 5373 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5374 CheckMemberSpecialization(NewVD, Previous)) 5375 NewVD->setInvalidDecl(); 5376 5377 // Merge the decl with the existing one if appropriate. 5378 if (!Previous.empty()) { 5379 if (Previous.isSingleResult() && 5380 isa<FieldDecl>(Previous.getFoundDecl()) && 5381 D.getCXXScopeSpec().isSet()) { 5382 // The user tried to define a non-static data member 5383 // out-of-line (C++ [dcl.meaning]p1). 5384 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5385 << D.getCXXScopeSpec().getRange(); 5386 Previous.clear(); 5387 NewVD->setInvalidDecl(); 5388 } 5389 } else if (D.getCXXScopeSpec().isSet()) { 5390 // No previous declaration in the qualifying scope. 5391 Diag(D.getIdentifierLoc(), diag::err_no_member) 5392 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5393 << D.getCXXScopeSpec().getRange(); 5394 NewVD->setInvalidDecl(); 5395 } 5396 5397 if (!IsVariableTemplateSpecialization) 5398 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5399 5400 if (NewTemplate) { 5401 VarTemplateDecl *PrevVarTemplate = 5402 NewVD->getPreviousDecl() 5403 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5404 : 0; 5405 5406 // Check the template parameter list of this declaration, possibly 5407 // merging in the template parameter list from the previous variable 5408 // template declaration. 5409 if (CheckTemplateParameterList( 5410 TemplateParams, 5411 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5412 : 0, 5413 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5414 DC->isDependentContext()) 5415 ? TPC_ClassTemplateMember 5416 : TPC_VarTemplate)) 5417 NewVD->setInvalidDecl(); 5418 5419 // If we are providing an explicit specialization of a static variable 5420 // template, make a note of that. 5421 if (PrevVarTemplate && 5422 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5423 PrevVarTemplate->setMemberSpecialization(); 5424 } 5425 } 5426 5427 ProcessPragmaWeak(S, NewVD); 5428 5429 // If this is the first declaration of an extern C variable, update 5430 // the map of such variables. 5431 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5432 isIncompleteDeclExternC(*this, NewVD)) 5433 RegisterLocallyScopedExternCDecl(NewVD, S); 5434 5435 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5436 Decl *ManglingContextDecl; 5437 if (MangleNumberingContext *MCtx = 5438 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5439 ManglingContextDecl)) { 5440 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD)); 5441 } 5442 } 5443 5444 if (NewTemplate) { 5445 if (NewVD->isInvalidDecl()) 5446 NewTemplate->setInvalidDecl(); 5447 ActOnDocumentableDecl(NewTemplate); 5448 return NewTemplate; 5449 } 5450 5451 return NewVD; 5452 } 5453 5454 /// \brief Diagnose variable or built-in function shadowing. Implements 5455 /// -Wshadow. 5456 /// 5457 /// This method is called whenever a VarDecl is added to a "useful" 5458 /// scope. 5459 /// 5460 /// \param S the scope in which the shadowing name is being declared 5461 /// \param R the lookup of the name 5462 /// 5463 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5464 // Return if warning is ignored. 5465 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5466 DiagnosticsEngine::Ignored) 5467 return; 5468 5469 // Don't diagnose declarations at file scope. 5470 if (D->hasGlobalStorage()) 5471 return; 5472 5473 DeclContext *NewDC = D->getDeclContext(); 5474 5475 // Only diagnose if we're shadowing an unambiguous field or variable. 5476 if (R.getResultKind() != LookupResult::Found) 5477 return; 5478 5479 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5480 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5481 return; 5482 5483 // Fields are not shadowed by variables in C++ static methods. 5484 if (isa<FieldDecl>(ShadowedDecl)) 5485 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5486 if (MD->isStatic()) 5487 return; 5488 5489 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5490 if (shadowedVar->isExternC()) { 5491 // For shadowing external vars, make sure that we point to the global 5492 // declaration, not a locally scoped extern declaration. 5493 for (VarDecl::redecl_iterator 5494 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 5495 I != E; ++I) 5496 if (I->isFileVarDecl()) { 5497 ShadowedDecl = *I; 5498 break; 5499 } 5500 } 5501 5502 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5503 5504 // Only warn about certain kinds of shadowing for class members. 5505 if (NewDC && NewDC->isRecord()) { 5506 // In particular, don't warn about shadowing non-class members. 5507 if (!OldDC->isRecord()) 5508 return; 5509 5510 // TODO: should we warn about static data members shadowing 5511 // static data members from base classes? 5512 5513 // TODO: don't diagnose for inaccessible shadowed members. 5514 // This is hard to do perfectly because we might friend the 5515 // shadowing context, but that's just a false negative. 5516 } 5517 5518 // Determine what kind of declaration we're shadowing. 5519 unsigned Kind; 5520 if (isa<RecordDecl>(OldDC)) { 5521 if (isa<FieldDecl>(ShadowedDecl)) 5522 Kind = 3; // field 5523 else 5524 Kind = 2; // static data member 5525 } else if (OldDC->isFileContext()) 5526 Kind = 1; // global 5527 else 5528 Kind = 0; // local 5529 5530 DeclarationName Name = R.getLookupName(); 5531 5532 // Emit warning and note. 5533 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5534 return; 5535 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5536 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5537 } 5538 5539 /// \brief Check -Wshadow without the advantage of a previous lookup. 5540 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5541 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5542 DiagnosticsEngine::Ignored) 5543 return; 5544 5545 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5546 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5547 LookupName(R, S); 5548 CheckShadow(S, D, R); 5549 } 5550 5551 /// Check for conflict between this global or extern "C" declaration and 5552 /// previous global or extern "C" declarations. This is only used in C++. 5553 template<typename T> 5554 static bool checkGlobalOrExternCConflict( 5555 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5556 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5557 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5558 5559 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5560 // The common case: this global doesn't conflict with any extern "C" 5561 // declaration. 5562 return false; 5563 } 5564 5565 if (Prev) { 5566 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5567 // Both the old and new declarations have C language linkage. This is a 5568 // redeclaration. 5569 Previous.clear(); 5570 Previous.addDecl(Prev); 5571 return true; 5572 } 5573 5574 // This is a global, non-extern "C" declaration, and there is a previous 5575 // non-global extern "C" declaration. Diagnose if this is a variable 5576 // declaration. 5577 if (!isa<VarDecl>(ND)) 5578 return false; 5579 } else { 5580 // The declaration is extern "C". Check for any declaration in the 5581 // translation unit which might conflict. 5582 if (IsGlobal) { 5583 // We have already performed the lookup into the translation unit. 5584 IsGlobal = false; 5585 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5586 I != E; ++I) { 5587 if (isa<VarDecl>(*I)) { 5588 Prev = *I; 5589 break; 5590 } 5591 } 5592 } else { 5593 DeclContext::lookup_result R = 5594 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5595 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5596 I != E; ++I) { 5597 if (isa<VarDecl>(*I)) { 5598 Prev = *I; 5599 break; 5600 } 5601 // FIXME: If we have any other entity with this name in global scope, 5602 // the declaration is ill-formed, but that is a defect: it breaks the 5603 // 'stat' hack, for instance. Only variables can have mangled name 5604 // clashes with extern "C" declarations, so only they deserve a 5605 // diagnostic. 5606 } 5607 } 5608 5609 if (!Prev) 5610 return false; 5611 } 5612 5613 // Use the first declaration's location to ensure we point at something which 5614 // is lexically inside an extern "C" linkage-spec. 5615 assert(Prev && "should have found a previous declaration to diagnose"); 5616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5617 Prev = FD->getFirstDecl(); 5618 else 5619 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5620 5621 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5622 << IsGlobal << ND; 5623 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5624 << IsGlobal; 5625 return false; 5626 } 5627 5628 /// Apply special rules for handling extern "C" declarations. Returns \c true 5629 /// if we have found that this is a redeclaration of some prior entity. 5630 /// 5631 /// Per C++ [dcl.link]p6: 5632 /// Two declarations [for a function or variable] with C language linkage 5633 /// with the same name that appear in different scopes refer to the same 5634 /// [entity]. An entity with C language linkage shall not be declared with 5635 /// the same name as an entity in global scope. 5636 template<typename T> 5637 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5638 LookupResult &Previous) { 5639 if (!S.getLangOpts().CPlusPlus) { 5640 // In C, when declaring a global variable, look for a corresponding 'extern' 5641 // variable declared in function scope. We don't need this in C++, because 5642 // we find local extern decls in the surrounding file-scope DeclContext. 5643 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5644 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5645 Previous.clear(); 5646 Previous.addDecl(Prev); 5647 return true; 5648 } 5649 } 5650 return false; 5651 } 5652 5653 // A declaration in the translation unit can conflict with an extern "C" 5654 // declaration. 5655 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5656 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5657 5658 // An extern "C" declaration can conflict with a declaration in the 5659 // translation unit or can be a redeclaration of an extern "C" declaration 5660 // in another scope. 5661 if (isIncompleteDeclExternC(S,ND)) 5662 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5663 5664 // Neither global nor extern "C": nothing to do. 5665 return false; 5666 } 5667 5668 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5669 // If the decl is already known invalid, don't check it. 5670 if (NewVD->isInvalidDecl()) 5671 return; 5672 5673 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5674 QualType T = TInfo->getType(); 5675 5676 // Defer checking an 'auto' type until its initializer is attached. 5677 if (T->isUndeducedType()) 5678 return; 5679 5680 if (T->isObjCObjectType()) { 5681 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5682 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5683 T = Context.getObjCObjectPointerType(T); 5684 NewVD->setType(T); 5685 } 5686 5687 // Emit an error if an address space was applied to decl with local storage. 5688 // This includes arrays of objects with address space qualifiers, but not 5689 // automatic variables that point to other address spaces. 5690 // ISO/IEC TR 18037 S5.1.2 5691 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5692 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5693 NewVD->setInvalidDecl(); 5694 return; 5695 } 5696 5697 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5698 // __constant address space. 5699 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5700 && T.getAddressSpace() != LangAS::opencl_constant 5701 && !T->isSamplerT()){ 5702 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5703 NewVD->setInvalidDecl(); 5704 return; 5705 } 5706 5707 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5708 // scope. 5709 if ((getLangOpts().OpenCLVersion >= 120) 5710 && NewVD->isStaticLocal()) { 5711 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5712 NewVD->setInvalidDecl(); 5713 return; 5714 } 5715 5716 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5717 && !NewVD->hasAttr<BlocksAttr>()) { 5718 if (getLangOpts().getGC() != LangOptions::NonGC) 5719 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5720 else { 5721 assert(!getLangOpts().ObjCAutoRefCount); 5722 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5723 } 5724 } 5725 5726 bool isVM = T->isVariablyModifiedType(); 5727 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5728 NewVD->hasAttr<BlocksAttr>()) 5729 getCurFunction()->setHasBranchProtectedScope(); 5730 5731 if ((isVM && NewVD->hasLinkage()) || 5732 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5733 bool SizeIsNegative; 5734 llvm::APSInt Oversized; 5735 TypeSourceInfo *FixedTInfo = 5736 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5737 SizeIsNegative, Oversized); 5738 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5739 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5740 // FIXME: This won't give the correct result for 5741 // int a[10][n]; 5742 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5743 5744 if (NewVD->isFileVarDecl()) 5745 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5746 << SizeRange; 5747 else if (NewVD->isStaticLocal()) 5748 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5749 << SizeRange; 5750 else 5751 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5752 << SizeRange; 5753 NewVD->setInvalidDecl(); 5754 return; 5755 } 5756 5757 if (FixedTInfo == 0) { 5758 if (NewVD->isFileVarDecl()) 5759 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5760 else 5761 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5762 NewVD->setInvalidDecl(); 5763 return; 5764 } 5765 5766 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5767 NewVD->setType(FixedTInfo->getType()); 5768 NewVD->setTypeSourceInfo(FixedTInfo); 5769 } 5770 5771 if (T->isVoidType()) { 5772 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5773 // of objects and functions. 5774 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5775 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5776 << T; 5777 NewVD->setInvalidDecl(); 5778 return; 5779 } 5780 } 5781 5782 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5783 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5784 NewVD->setInvalidDecl(); 5785 return; 5786 } 5787 5788 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5789 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5790 NewVD->setInvalidDecl(); 5791 return; 5792 } 5793 5794 if (NewVD->isConstexpr() && !T->isDependentType() && 5795 RequireLiteralType(NewVD->getLocation(), T, 5796 diag::err_constexpr_var_non_literal)) { 5797 // Can't perform this check until the type is deduced. 5798 NewVD->setInvalidDecl(); 5799 return; 5800 } 5801 } 5802 5803 /// \brief Perform semantic checking on a newly-created variable 5804 /// declaration. 5805 /// 5806 /// This routine performs all of the type-checking required for a 5807 /// variable declaration once it has been built. It is used both to 5808 /// check variables after they have been parsed and their declarators 5809 /// have been translated into a declaration, and to check variables 5810 /// that have been instantiated from a template. 5811 /// 5812 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5813 /// 5814 /// Returns true if the variable declaration is a redeclaration. 5815 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5816 CheckVariableDeclarationType(NewVD); 5817 5818 // If the decl is already known invalid, don't check it. 5819 if (NewVD->isInvalidDecl()) 5820 return false; 5821 5822 // If we did not find anything by this name, look for a non-visible 5823 // extern "C" declaration with the same name. 5824 if (Previous.empty() && 5825 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5826 Previous.setShadowed(); 5827 5828 // Filter out any non-conflicting previous declarations. 5829 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5830 5831 if (!Previous.empty()) { 5832 MergeVarDecl(NewVD, Previous); 5833 return true; 5834 } 5835 return false; 5836 } 5837 5838 /// \brief Data used with FindOverriddenMethod 5839 struct FindOverriddenMethodData { 5840 Sema *S; 5841 CXXMethodDecl *Method; 5842 }; 5843 5844 /// \brief Member lookup function that determines whether a given C++ 5845 /// method overrides a method in a base class, to be used with 5846 /// CXXRecordDecl::lookupInBases(). 5847 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5848 CXXBasePath &Path, 5849 void *UserData) { 5850 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5851 5852 FindOverriddenMethodData *Data 5853 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5854 5855 DeclarationName Name = Data->Method->getDeclName(); 5856 5857 // FIXME: Do we care about other names here too? 5858 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5859 // We really want to find the base class destructor here. 5860 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5861 CanQualType CT = Data->S->Context.getCanonicalType(T); 5862 5863 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5864 } 5865 5866 for (Path.Decls = BaseRecord->lookup(Name); 5867 !Path.Decls.empty(); 5868 Path.Decls = Path.Decls.slice(1)) { 5869 NamedDecl *D = Path.Decls.front(); 5870 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5871 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5872 return true; 5873 } 5874 } 5875 5876 return false; 5877 } 5878 5879 namespace { 5880 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5881 } 5882 /// \brief Report an error regarding overriding, along with any relevant 5883 /// overriden methods. 5884 /// 5885 /// \param DiagID the primary error to report. 5886 /// \param MD the overriding method. 5887 /// \param OEK which overrides to include as notes. 5888 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5889 OverrideErrorKind OEK = OEK_All) { 5890 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5891 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5892 E = MD->end_overridden_methods(); 5893 I != E; ++I) { 5894 // This check (& the OEK parameter) could be replaced by a predicate, but 5895 // without lambdas that would be overkill. This is still nicer than writing 5896 // out the diag loop 3 times. 5897 if ((OEK == OEK_All) || 5898 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5899 (OEK == OEK_Deleted && (*I)->isDeleted())) 5900 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5901 } 5902 } 5903 5904 /// AddOverriddenMethods - See if a method overrides any in the base classes, 5905 /// and if so, check that it's a valid override and remember it. 5906 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5907 // Look for virtual methods in base classes that this method might override. 5908 CXXBasePaths Paths; 5909 FindOverriddenMethodData Data; 5910 Data.Method = MD; 5911 Data.S = this; 5912 bool hasDeletedOverridenMethods = false; 5913 bool hasNonDeletedOverridenMethods = false; 5914 bool AddedAny = false; 5915 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5916 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5917 E = Paths.found_decls_end(); I != E; ++I) { 5918 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5919 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5920 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5921 !CheckOverridingFunctionAttributes(MD, OldMD) && 5922 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5923 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5924 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5925 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5926 AddedAny = true; 5927 } 5928 } 5929 } 5930 } 5931 5932 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5933 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5934 } 5935 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5936 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5937 } 5938 5939 return AddedAny; 5940 } 5941 5942 namespace { 5943 // Struct for holding all of the extra arguments needed by 5944 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5945 struct ActOnFDArgs { 5946 Scope *S; 5947 Declarator &D; 5948 MultiTemplateParamsArg TemplateParamLists; 5949 bool AddToScope; 5950 }; 5951 } 5952 5953 namespace { 5954 5955 // Callback to only accept typo corrections that have a non-zero edit distance. 5956 // Also only accept corrections that have the same parent decl. 5957 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5958 public: 5959 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5960 CXXRecordDecl *Parent) 5961 : Context(Context), OriginalFD(TypoFD), 5962 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5963 5964 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5965 if (candidate.getEditDistance() == 0) 5966 return false; 5967 5968 SmallVector<unsigned, 1> MismatchedParams; 5969 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5970 CDeclEnd = candidate.end(); 5971 CDecl != CDeclEnd; ++CDecl) { 5972 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5973 5974 if (FD && !FD->hasBody() && 5975 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 5976 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 5977 CXXRecordDecl *Parent = MD->getParent(); 5978 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 5979 return true; 5980 } else if (!ExpectedParent) { 5981 return true; 5982 } 5983 } 5984 } 5985 5986 return false; 5987 } 5988 5989 private: 5990 ASTContext &Context; 5991 FunctionDecl *OriginalFD; 5992 CXXRecordDecl *ExpectedParent; 5993 }; 5994 5995 } 5996 5997 /// \brief Generate diagnostics for an invalid function redeclaration. 5998 /// 5999 /// This routine handles generating the diagnostic messages for an invalid 6000 /// function redeclaration, including finding possible similar declarations 6001 /// or performing typo correction if there are no previous declarations with 6002 /// the same name. 6003 /// 6004 /// Returns a NamedDecl iff typo correction was performed and substituting in 6005 /// the new declaration name does not cause new errors. 6006 static NamedDecl *DiagnoseInvalidRedeclaration( 6007 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6008 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6009 DeclarationName Name = NewFD->getDeclName(); 6010 DeclContext *NewDC = NewFD->getDeclContext(); 6011 SmallVector<unsigned, 1> MismatchedParams; 6012 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6013 TypoCorrection Correction; 6014 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6015 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6016 : diag::err_member_decl_does_not_match; 6017 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6018 IsLocalFriend ? Sema::LookupLocalFriendName 6019 : Sema::LookupOrdinaryName, 6020 Sema::ForRedeclaration); 6021 6022 NewFD->setInvalidDecl(); 6023 if (IsLocalFriend) 6024 SemaRef.LookupName(Prev, S); 6025 else 6026 SemaRef.LookupQualifiedName(Prev, NewDC); 6027 assert(!Prev.isAmbiguous() && 6028 "Cannot have an ambiguity in previous-declaration lookup"); 6029 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6030 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6031 MD ? MD->getParent() : 0); 6032 if (!Prev.empty()) { 6033 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6034 Func != FuncEnd; ++Func) { 6035 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6036 if (FD && 6037 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6038 // Add 1 to the index so that 0 can mean the mismatch didn't 6039 // involve a parameter 6040 unsigned ParamNum = 6041 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6042 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6043 } 6044 } 6045 // If the qualified name lookup yielded nothing, try typo correction 6046 } else if ((Correction = SemaRef.CorrectTypo( 6047 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6048 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6049 IsLocalFriend ? 0 : NewDC))) { 6050 // Set up everything for the call to ActOnFunctionDeclarator 6051 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6052 ExtraArgs.D.getIdentifierLoc()); 6053 Previous.clear(); 6054 Previous.setLookupName(Correction.getCorrection()); 6055 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6056 CDeclEnd = Correction.end(); 6057 CDecl != CDeclEnd; ++CDecl) { 6058 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6059 if (FD && !FD->hasBody() && 6060 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6061 Previous.addDecl(FD); 6062 } 6063 } 6064 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6065 6066 NamedDecl *Result; 6067 // Retry building the function declaration with the new previous 6068 // declarations, and with errors suppressed. 6069 { 6070 // Trap errors. 6071 Sema::SFINAETrap Trap(SemaRef); 6072 6073 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6074 // pieces need to verify the typo-corrected C++ declaration and hopefully 6075 // eliminate the need for the parameter pack ExtraArgs. 6076 Result = SemaRef.ActOnFunctionDeclarator( 6077 ExtraArgs.S, ExtraArgs.D, 6078 Correction.getCorrectionDecl()->getDeclContext(), 6079 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6080 ExtraArgs.AddToScope); 6081 6082 if (Trap.hasErrorOccurred()) 6083 Result = 0; 6084 } 6085 6086 if (Result) { 6087 // Determine which correction we picked. 6088 Decl *Canonical = Result->getCanonicalDecl(); 6089 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6090 I != E; ++I) 6091 if ((*I)->getCanonicalDecl() == Canonical) 6092 Correction.setCorrectionDecl(*I); 6093 6094 SemaRef.diagnoseTypo( 6095 Correction, 6096 SemaRef.PDiag(IsLocalFriend 6097 ? diag::err_no_matching_local_friend_suggest 6098 : diag::err_member_decl_does_not_match_suggest) 6099 << Name << NewDC << IsDefinition); 6100 return Result; 6101 } 6102 6103 // Pretend the typo correction never occurred 6104 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6105 ExtraArgs.D.getIdentifierLoc()); 6106 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6107 Previous.clear(); 6108 Previous.setLookupName(Name); 6109 } 6110 6111 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6112 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6113 6114 bool NewFDisConst = false; 6115 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6116 NewFDisConst = NewMD->isConst(); 6117 6118 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6119 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6120 NearMatch != NearMatchEnd; ++NearMatch) { 6121 FunctionDecl *FD = NearMatch->first; 6122 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6123 bool FDisConst = MD && MD->isConst(); 6124 bool IsMember = MD || !IsLocalFriend; 6125 6126 // FIXME: These notes are poorly worded for the local friend case. 6127 if (unsigned Idx = NearMatch->second) { 6128 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6129 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6130 if (Loc.isInvalid()) Loc = FD->getLocation(); 6131 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6132 : diag::note_local_decl_close_param_match) 6133 << Idx << FDParam->getType() 6134 << NewFD->getParamDecl(Idx - 1)->getType(); 6135 } else if (FDisConst != NewFDisConst) { 6136 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6137 << NewFDisConst << FD->getSourceRange().getEnd(); 6138 } else 6139 SemaRef.Diag(FD->getLocation(), 6140 IsMember ? diag::note_member_def_close_match 6141 : diag::note_local_decl_close_match); 6142 } 6143 return 0; 6144 } 6145 6146 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6147 Declarator &D) { 6148 switch (D.getDeclSpec().getStorageClassSpec()) { 6149 default: llvm_unreachable("Unknown storage class!"); 6150 case DeclSpec::SCS_auto: 6151 case DeclSpec::SCS_register: 6152 case DeclSpec::SCS_mutable: 6153 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6154 diag::err_typecheck_sclass_func); 6155 D.setInvalidType(); 6156 break; 6157 case DeclSpec::SCS_unspecified: break; 6158 case DeclSpec::SCS_extern: 6159 if (D.getDeclSpec().isExternInLinkageSpec()) 6160 return SC_None; 6161 return SC_Extern; 6162 case DeclSpec::SCS_static: { 6163 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6164 // C99 6.7.1p5: 6165 // The declaration of an identifier for a function that has 6166 // block scope shall have no explicit storage-class specifier 6167 // other than extern 6168 // See also (C++ [dcl.stc]p4). 6169 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6170 diag::err_static_block_func); 6171 break; 6172 } else 6173 return SC_Static; 6174 } 6175 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6176 } 6177 6178 // No explicit storage class has already been returned 6179 return SC_None; 6180 } 6181 6182 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6183 DeclContext *DC, QualType &R, 6184 TypeSourceInfo *TInfo, 6185 FunctionDecl::StorageClass SC, 6186 bool &IsVirtualOkay) { 6187 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6188 DeclarationName Name = NameInfo.getName(); 6189 6190 FunctionDecl *NewFD = 0; 6191 bool isInline = D.getDeclSpec().isInlineSpecified(); 6192 6193 if (!SemaRef.getLangOpts().CPlusPlus) { 6194 // Determine whether the function was written with a 6195 // prototype. This true when: 6196 // - there is a prototype in the declarator, or 6197 // - the type R of the function is some kind of typedef or other reference 6198 // to a type name (which eventually refers to a function type). 6199 bool HasPrototype = 6200 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6201 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6202 6203 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6204 D.getLocStart(), NameInfo, R, 6205 TInfo, SC, isInline, 6206 HasPrototype, false); 6207 if (D.isInvalidType()) 6208 NewFD->setInvalidDecl(); 6209 6210 // Set the lexical context. 6211 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6212 6213 return NewFD; 6214 } 6215 6216 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6217 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6218 6219 // Check that the return type is not an abstract class type. 6220 // For record types, this is done by the AbstractClassUsageDiagnoser once 6221 // the class has been completely parsed. 6222 if (!DC->isRecord() && 6223 SemaRef.RequireNonAbstractType( 6224 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6225 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6226 D.setInvalidType(); 6227 6228 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6229 // This is a C++ constructor declaration. 6230 assert(DC->isRecord() && 6231 "Constructors can only be declared in a member context"); 6232 6233 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6234 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6235 D.getLocStart(), NameInfo, 6236 R, TInfo, isExplicit, isInline, 6237 /*isImplicitlyDeclared=*/false, 6238 isConstexpr); 6239 6240 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6241 // This is a C++ destructor declaration. 6242 if (DC->isRecord()) { 6243 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6244 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6245 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6246 SemaRef.Context, Record, 6247 D.getLocStart(), 6248 NameInfo, R, TInfo, isInline, 6249 /*isImplicitlyDeclared=*/false); 6250 6251 // If the class is complete, then we now create the implicit exception 6252 // specification. If the class is incomplete or dependent, we can't do 6253 // it yet. 6254 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6255 Record->getDefinition() && !Record->isBeingDefined() && 6256 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6257 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6258 } 6259 6260 // The Microsoft ABI requires that we perform the destructor body 6261 // checks (i.e. operator delete() lookup) at every declaration, as 6262 // any translation unit may need to emit a deleting destructor. 6263 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() && 6264 !Record->isDependentType() && Record->getDefinition() && 6265 !Record->isBeingDefined() && !NewDD->isDeleted()) { 6266 SemaRef.CheckDestructor(NewDD); 6267 } 6268 6269 IsVirtualOkay = true; 6270 return NewDD; 6271 6272 } else { 6273 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6274 D.setInvalidType(); 6275 6276 // Create a FunctionDecl to satisfy the function definition parsing 6277 // code path. 6278 return FunctionDecl::Create(SemaRef.Context, DC, 6279 D.getLocStart(), 6280 D.getIdentifierLoc(), Name, R, TInfo, 6281 SC, isInline, 6282 /*hasPrototype=*/true, isConstexpr); 6283 } 6284 6285 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6286 if (!DC->isRecord()) { 6287 SemaRef.Diag(D.getIdentifierLoc(), 6288 diag::err_conv_function_not_member); 6289 return 0; 6290 } 6291 6292 SemaRef.CheckConversionDeclarator(D, R, SC); 6293 IsVirtualOkay = true; 6294 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6295 D.getLocStart(), NameInfo, 6296 R, TInfo, isInline, isExplicit, 6297 isConstexpr, SourceLocation()); 6298 6299 } else if (DC->isRecord()) { 6300 // If the name of the function is the same as the name of the record, 6301 // then this must be an invalid constructor that has a return type. 6302 // (The parser checks for a return type and makes the declarator a 6303 // constructor if it has no return type). 6304 if (Name.getAsIdentifierInfo() && 6305 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6306 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6307 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6308 << SourceRange(D.getIdentifierLoc()); 6309 return 0; 6310 } 6311 6312 // This is a C++ method declaration. 6313 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6314 cast<CXXRecordDecl>(DC), 6315 D.getLocStart(), NameInfo, R, 6316 TInfo, SC, isInline, 6317 isConstexpr, SourceLocation()); 6318 IsVirtualOkay = !Ret->isStatic(); 6319 return Ret; 6320 } else { 6321 // Determine whether the function was written with a 6322 // prototype. This true when: 6323 // - we're in C++ (where every function has a prototype), 6324 return FunctionDecl::Create(SemaRef.Context, DC, 6325 D.getLocStart(), 6326 NameInfo, R, TInfo, SC, isInline, 6327 true/*HasPrototype*/, isConstexpr); 6328 } 6329 } 6330 6331 void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 6332 // In C++, the empty parameter-type-list must be spelled "void"; a 6333 // typedef of void is not permitted. 6334 if (getLangOpts().CPlusPlus && 6335 Param->getType().getUnqualifiedType() != Context.VoidTy) { 6336 bool IsTypeAlias = false; 6337 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 6338 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 6339 else if (const TemplateSpecializationType *TST = 6340 Param->getType()->getAs<TemplateSpecializationType>()) 6341 IsTypeAlias = TST->isTypeAlias(); 6342 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 6343 << IsTypeAlias; 6344 } 6345 } 6346 6347 enum OpenCLParamType { 6348 ValidKernelParam, 6349 PtrPtrKernelParam, 6350 PtrKernelParam, 6351 InvalidKernelParam, 6352 RecordKernelParam 6353 }; 6354 6355 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6356 if (PT->isPointerType()) { 6357 QualType PointeeType = PT->getPointeeType(); 6358 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam; 6359 } 6360 6361 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6362 // be used as builtin types. 6363 6364 if (PT->isImageType()) 6365 return PtrKernelParam; 6366 6367 if (PT->isBooleanType()) 6368 return InvalidKernelParam; 6369 6370 if (PT->isEventT()) 6371 return InvalidKernelParam; 6372 6373 if (PT->isHalfType()) 6374 return InvalidKernelParam; 6375 6376 if (PT->isRecordType()) 6377 return RecordKernelParam; 6378 6379 return ValidKernelParam; 6380 } 6381 6382 static void checkIsValidOpenCLKernelParameter( 6383 Sema &S, 6384 Declarator &D, 6385 ParmVarDecl *Param, 6386 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6387 QualType PT = Param->getType(); 6388 6389 // Cache the valid types we encounter to avoid rechecking structs that are 6390 // used again 6391 if (ValidTypes.count(PT.getTypePtr())) 6392 return; 6393 6394 switch (getOpenCLKernelParameterType(PT)) { 6395 case PtrPtrKernelParam: 6396 // OpenCL v1.2 s6.9.a: 6397 // A kernel function argument cannot be declared as a 6398 // pointer to a pointer type. 6399 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6400 D.setInvalidType(); 6401 return; 6402 6403 // OpenCL v1.2 s6.9.k: 6404 // Arguments to kernel functions in a program cannot be declared with the 6405 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6406 // uintptr_t or a struct and/or union that contain fields declared to be 6407 // one of these built-in scalar types. 6408 6409 case InvalidKernelParam: 6410 // OpenCL v1.2 s6.8 n: 6411 // A kernel function argument cannot be declared 6412 // of event_t type. 6413 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6414 D.setInvalidType(); 6415 return; 6416 6417 case PtrKernelParam: 6418 case ValidKernelParam: 6419 ValidTypes.insert(PT.getTypePtr()); 6420 return; 6421 6422 case RecordKernelParam: 6423 break; 6424 } 6425 6426 // Track nested structs we will inspect 6427 SmallVector<const Decl *, 4> VisitStack; 6428 6429 // Track where we are in the nested structs. Items will migrate from 6430 // VisitStack to HistoryStack as we do the DFS for bad field. 6431 SmallVector<const FieldDecl *, 4> HistoryStack; 6432 HistoryStack.push_back((const FieldDecl *) 0); 6433 6434 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6435 VisitStack.push_back(PD); 6436 6437 assert(VisitStack.back() && "First decl null?"); 6438 6439 do { 6440 const Decl *Next = VisitStack.pop_back_val(); 6441 if (!Next) { 6442 assert(!HistoryStack.empty()); 6443 // Found a marker, we have gone up a level 6444 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6445 ValidTypes.insert(Hist->getType().getTypePtr()); 6446 6447 continue; 6448 } 6449 6450 // Adds everything except the original parameter declaration (which is not a 6451 // field itself) to the history stack. 6452 const RecordDecl *RD; 6453 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6454 HistoryStack.push_back(Field); 6455 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6456 } else { 6457 RD = cast<RecordDecl>(Next); 6458 } 6459 6460 // Add a null marker so we know when we've gone back up a level 6461 VisitStack.push_back((const Decl *) 0); 6462 6463 for (RecordDecl::field_iterator I = RD->field_begin(), 6464 E = RD->field_end(); I != E; ++I) { 6465 const FieldDecl *FD = *I; 6466 QualType QT = FD->getType(); 6467 6468 if (ValidTypes.count(QT.getTypePtr())) 6469 continue; 6470 6471 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6472 if (ParamType == ValidKernelParam) 6473 continue; 6474 6475 if (ParamType == RecordKernelParam) { 6476 VisitStack.push_back(FD); 6477 continue; 6478 } 6479 6480 // OpenCL v1.2 s6.9.p: 6481 // Arguments to kernel functions that are declared to be a struct or union 6482 // do not allow OpenCL objects to be passed as elements of the struct or 6483 // union. 6484 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) { 6485 S.Diag(Param->getLocation(), 6486 diag::err_record_with_pointers_kernel_param) 6487 << PT->isUnionType() 6488 << PT; 6489 } else { 6490 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6491 } 6492 6493 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6494 << PD->getDeclName(); 6495 6496 // We have an error, now let's go back up through history and show where 6497 // the offending field came from 6498 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6499 E = HistoryStack.end(); I != E; ++I) { 6500 const FieldDecl *OuterField = *I; 6501 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6502 << OuterField->getType(); 6503 } 6504 6505 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6506 << QT->isPointerType() 6507 << QT; 6508 D.setInvalidType(); 6509 return; 6510 } 6511 } while (!VisitStack.empty()); 6512 } 6513 6514 NamedDecl* 6515 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6516 TypeSourceInfo *TInfo, LookupResult &Previous, 6517 MultiTemplateParamsArg TemplateParamLists, 6518 bool &AddToScope) { 6519 QualType R = TInfo->getType(); 6520 6521 assert(R.getTypePtr()->isFunctionType()); 6522 6523 // TODO: consider using NameInfo for diagnostic. 6524 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6525 DeclarationName Name = NameInfo.getName(); 6526 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6527 6528 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6529 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6530 diag::err_invalid_thread) 6531 << DeclSpec::getSpecifierName(TSCS); 6532 6533 if (D.isFirstDeclarationOfMember()) 6534 adjustMemberFunctionCC(R, D.isStaticMember()); 6535 6536 bool isFriend = false; 6537 FunctionTemplateDecl *FunctionTemplate = 0; 6538 bool isExplicitSpecialization = false; 6539 bool isFunctionTemplateSpecialization = false; 6540 6541 bool isDependentClassScopeExplicitSpecialization = false; 6542 bool HasExplicitTemplateArgs = false; 6543 TemplateArgumentListInfo TemplateArgs; 6544 6545 bool isVirtualOkay = false; 6546 6547 DeclContext *OriginalDC = DC; 6548 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6549 6550 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6551 isVirtualOkay); 6552 if (!NewFD) return 0; 6553 6554 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6555 NewFD->setTopLevelDeclInObjCContainer(); 6556 6557 // Set the lexical context. If this is a function-scope declaration, or has a 6558 // C++ scope specifier, or is the object of a friend declaration, the lexical 6559 // context will be different from the semantic context. 6560 NewFD->setLexicalDeclContext(CurContext); 6561 6562 if (IsLocalExternDecl) 6563 NewFD->setLocalExternDecl(); 6564 6565 if (getLangOpts().CPlusPlus) { 6566 bool isInline = D.getDeclSpec().isInlineSpecified(); 6567 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6568 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6569 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6570 isFriend = D.getDeclSpec().isFriendSpecified(); 6571 if (isFriend && !isInline && D.isFunctionDefinition()) { 6572 // C++ [class.friend]p5 6573 // A function can be defined in a friend declaration of a 6574 // class . . . . Such a function is implicitly inline. 6575 NewFD->setImplicitlyInline(); 6576 } 6577 6578 // If this is a method defined in an __interface, and is not a constructor 6579 // or an overloaded operator, then set the pure flag (isVirtual will already 6580 // return true). 6581 if (const CXXRecordDecl *Parent = 6582 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6583 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6584 NewFD->setPure(true); 6585 } 6586 6587 SetNestedNameSpecifier(NewFD, D); 6588 isExplicitSpecialization = false; 6589 isFunctionTemplateSpecialization = false; 6590 if (D.isInvalidType()) 6591 NewFD->setInvalidDecl(); 6592 6593 // Match up the template parameter lists with the scope specifier, then 6594 // determine whether we have a template or a template specialization. 6595 bool Invalid = false; 6596 if (TemplateParameterList *TemplateParams = 6597 MatchTemplateParametersToScopeSpecifier( 6598 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6599 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6600 isExplicitSpecialization, Invalid)) { 6601 if (TemplateParams->size() > 0) { 6602 // This is a function template 6603 6604 // Check that we can declare a template here. 6605 if (CheckTemplateDeclScope(S, TemplateParams)) 6606 return 0; 6607 6608 // A destructor cannot be a template. 6609 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6610 Diag(NewFD->getLocation(), diag::err_destructor_template); 6611 return 0; 6612 } 6613 6614 // If we're adding a template to a dependent context, we may need to 6615 // rebuilding some of the types used within the template parameter list, 6616 // now that we know what the current instantiation is. 6617 if (DC->isDependentContext()) { 6618 ContextRAII SavedContext(*this, DC); 6619 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6620 Invalid = true; 6621 } 6622 6623 6624 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6625 NewFD->getLocation(), 6626 Name, TemplateParams, 6627 NewFD); 6628 FunctionTemplate->setLexicalDeclContext(CurContext); 6629 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6630 6631 // For source fidelity, store the other template param lists. 6632 if (TemplateParamLists.size() > 1) { 6633 NewFD->setTemplateParameterListsInfo(Context, 6634 TemplateParamLists.size() - 1, 6635 TemplateParamLists.data()); 6636 } 6637 } else { 6638 // This is a function template specialization. 6639 isFunctionTemplateSpecialization = true; 6640 // For source fidelity, store all the template param lists. 6641 NewFD->setTemplateParameterListsInfo(Context, 6642 TemplateParamLists.size(), 6643 TemplateParamLists.data()); 6644 6645 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6646 if (isFriend) { 6647 // We want to remove the "template<>", found here. 6648 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6649 6650 // If we remove the template<> and the name is not a 6651 // template-id, we're actually silently creating a problem: 6652 // the friend declaration will refer to an untemplated decl, 6653 // and clearly the user wants a template specialization. So 6654 // we need to insert '<>' after the name. 6655 SourceLocation InsertLoc; 6656 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6657 InsertLoc = D.getName().getSourceRange().getEnd(); 6658 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6659 } 6660 6661 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6662 << Name << RemoveRange 6663 << FixItHint::CreateRemoval(RemoveRange) 6664 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6665 } 6666 } 6667 } 6668 else { 6669 // All template param lists were matched against the scope specifier: 6670 // this is NOT (an explicit specialization of) a template. 6671 if (TemplateParamLists.size() > 0) 6672 // For source fidelity, store all the template param lists. 6673 NewFD->setTemplateParameterListsInfo(Context, 6674 TemplateParamLists.size(), 6675 TemplateParamLists.data()); 6676 } 6677 6678 if (Invalid) { 6679 NewFD->setInvalidDecl(); 6680 if (FunctionTemplate) 6681 FunctionTemplate->setInvalidDecl(); 6682 } 6683 6684 // C++ [dcl.fct.spec]p5: 6685 // The virtual specifier shall only be used in declarations of 6686 // nonstatic class member functions that appear within a 6687 // member-specification of a class declaration; see 10.3. 6688 // 6689 if (isVirtual && !NewFD->isInvalidDecl()) { 6690 if (!isVirtualOkay) { 6691 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6692 diag::err_virtual_non_function); 6693 } else if (!CurContext->isRecord()) { 6694 // 'virtual' was specified outside of the class. 6695 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6696 diag::err_virtual_out_of_class) 6697 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6698 } else if (NewFD->getDescribedFunctionTemplate()) { 6699 // C++ [temp.mem]p3: 6700 // A member function template shall not be virtual. 6701 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6702 diag::err_virtual_member_function_template) 6703 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6704 } else { 6705 // Okay: Add virtual to the method. 6706 NewFD->setVirtualAsWritten(true); 6707 } 6708 6709 if (getLangOpts().CPlusPlus1y && 6710 NewFD->getReturnType()->isUndeducedType()) 6711 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6712 } 6713 6714 if (getLangOpts().CPlusPlus1y && 6715 (NewFD->isDependentContext() || 6716 (isFriend && CurContext->isDependentContext())) && 6717 NewFD->getReturnType()->isUndeducedType()) { 6718 // If the function template is referenced directly (for instance, as a 6719 // member of the current instantiation), pretend it has a dependent type. 6720 // This is not really justified by the standard, but is the only sane 6721 // thing to do. 6722 // FIXME: For a friend function, we have not marked the function as being 6723 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6724 const FunctionProtoType *FPT = 6725 NewFD->getType()->castAs<FunctionProtoType>(); 6726 QualType Result = 6727 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6728 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6729 FPT->getExtProtoInfo())); 6730 } 6731 6732 // C++ [dcl.fct.spec]p3: 6733 // The inline specifier shall not appear on a block scope function 6734 // declaration. 6735 if (isInline && !NewFD->isInvalidDecl()) { 6736 if (CurContext->isFunctionOrMethod()) { 6737 // 'inline' is not allowed on block scope function declaration. 6738 Diag(D.getDeclSpec().getInlineSpecLoc(), 6739 diag::err_inline_declaration_block_scope) << Name 6740 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6741 } 6742 } 6743 6744 // C++ [dcl.fct.spec]p6: 6745 // The explicit specifier shall be used only in the declaration of a 6746 // constructor or conversion function within its class definition; 6747 // see 12.3.1 and 12.3.2. 6748 if (isExplicit && !NewFD->isInvalidDecl()) { 6749 if (!CurContext->isRecord()) { 6750 // 'explicit' was specified outside of the class. 6751 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6752 diag::err_explicit_out_of_class) 6753 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6754 } else if (!isa<CXXConstructorDecl>(NewFD) && 6755 !isa<CXXConversionDecl>(NewFD)) { 6756 // 'explicit' was specified on a function that wasn't a constructor 6757 // or conversion function. 6758 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6759 diag::err_explicit_non_ctor_or_conv_function) 6760 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6761 } 6762 } 6763 6764 if (isConstexpr) { 6765 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6766 // are implicitly inline. 6767 NewFD->setImplicitlyInline(); 6768 6769 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6770 // be either constructors or to return a literal type. Therefore, 6771 // destructors cannot be declared constexpr. 6772 if (isa<CXXDestructorDecl>(NewFD)) 6773 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6774 } 6775 6776 // If __module_private__ was specified, mark the function accordingly. 6777 if (D.getDeclSpec().isModulePrivateSpecified()) { 6778 if (isFunctionTemplateSpecialization) { 6779 SourceLocation ModulePrivateLoc 6780 = D.getDeclSpec().getModulePrivateSpecLoc(); 6781 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6782 << 0 6783 << FixItHint::CreateRemoval(ModulePrivateLoc); 6784 } else { 6785 NewFD->setModulePrivate(); 6786 if (FunctionTemplate) 6787 FunctionTemplate->setModulePrivate(); 6788 } 6789 } 6790 6791 if (isFriend) { 6792 if (FunctionTemplate) { 6793 FunctionTemplate->setObjectOfFriendDecl(); 6794 FunctionTemplate->setAccess(AS_public); 6795 } 6796 NewFD->setObjectOfFriendDecl(); 6797 NewFD->setAccess(AS_public); 6798 } 6799 6800 // If a function is defined as defaulted or deleted, mark it as such now. 6801 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6802 // definition kind to FDK_Definition. 6803 switch (D.getFunctionDefinitionKind()) { 6804 case FDK_Declaration: 6805 case FDK_Definition: 6806 break; 6807 6808 case FDK_Defaulted: 6809 NewFD->setDefaulted(); 6810 break; 6811 6812 case FDK_Deleted: 6813 NewFD->setDeletedAsWritten(); 6814 break; 6815 } 6816 6817 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6818 D.isFunctionDefinition()) { 6819 // C++ [class.mfct]p2: 6820 // A member function may be defined (8.4) in its class definition, in 6821 // which case it is an inline member function (7.1.2) 6822 NewFD->setImplicitlyInline(); 6823 } 6824 6825 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6826 !CurContext->isRecord()) { 6827 // C++ [class.static]p1: 6828 // A data or function member of a class may be declared static 6829 // in a class definition, in which case it is a static member of 6830 // the class. 6831 6832 // Complain about the 'static' specifier if it's on an out-of-line 6833 // member function definition. 6834 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6835 diag::err_static_out_of_line) 6836 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6837 } 6838 6839 // C++11 [except.spec]p15: 6840 // A deallocation function with no exception-specification is treated 6841 // as if it were specified with noexcept(true). 6842 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6843 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6844 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6845 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6846 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6847 EPI.ExceptionSpecType = EST_BasicNoexcept; 6848 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 6849 FPT->getParamTypes(), EPI)); 6850 } 6851 } 6852 6853 // Filter out previous declarations that don't match the scope. 6854 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6855 D.getCXXScopeSpec().isNotEmpty() || 6856 isExplicitSpecialization || 6857 isFunctionTemplateSpecialization); 6858 6859 // Handle GNU asm-label extension (encoded as an attribute). 6860 if (Expr *E = (Expr*) D.getAsmLabel()) { 6861 // The parser guarantees this is a string. 6862 StringLiteral *SE = cast<StringLiteral>(E); 6863 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6864 SE->getString(), 0)); 6865 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6866 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6867 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6868 if (I != ExtnameUndeclaredIdentifiers.end()) { 6869 NewFD->addAttr(I->second); 6870 ExtnameUndeclaredIdentifiers.erase(I); 6871 } 6872 } 6873 6874 // Copy the parameter declarations from the declarator D to the function 6875 // declaration NewFD, if they are available. First scavenge them into Params. 6876 SmallVector<ParmVarDecl*, 16> Params; 6877 if (D.isFunctionDeclarator()) { 6878 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6879 6880 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6881 // function that takes no arguments, not a function that takes a 6882 // single void argument. 6883 // We let through "const void" here because Sema::GetTypeForDeclarator 6884 // already checks for that case. 6885 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6886 FTI.ArgInfo[0].Param && 6887 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6888 // Empty arg list, don't push any params. 6889 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6890 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6891 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6892 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6893 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6894 Param->setDeclContext(NewFD); 6895 Params.push_back(Param); 6896 6897 if (Param->isInvalidDecl()) 6898 NewFD->setInvalidDecl(); 6899 } 6900 } 6901 6902 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6903 // When we're declaring a function with a typedef, typeof, etc as in the 6904 // following example, we'll need to synthesize (unnamed) 6905 // parameters for use in the declaration. 6906 // 6907 // @code 6908 // typedef void fn(int); 6909 // fn f; 6910 // @endcode 6911 6912 // Synthesize a parameter for each argument type. 6913 for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(), 6914 AE = FT->param_type_end(); 6915 AI != AE; ++AI) { 6916 ParmVarDecl *Param = 6917 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6918 Param->setScopeInfo(0, Params.size()); 6919 Params.push_back(Param); 6920 } 6921 } else { 6922 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6923 "Should not need args for typedef of non-prototype fn"); 6924 } 6925 6926 // Finally, we know we have the right number of parameters, install them. 6927 NewFD->setParams(Params); 6928 6929 // Find all anonymous symbols defined during the declaration of this function 6930 // and add to NewFD. This lets us track decls such 'enum Y' in: 6931 // 6932 // void f(enum Y {AA} x) {} 6933 // 6934 // which would otherwise incorrectly end up in the translation unit scope. 6935 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6936 DeclsInPrototypeScope.clear(); 6937 6938 if (D.getDeclSpec().isNoreturnSpecified()) 6939 NewFD->addAttr( 6940 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6941 Context, 0)); 6942 6943 // Functions returning a variably modified type violate C99 6.7.5.2p2 6944 // because all functions have linkage. 6945 if (!NewFD->isInvalidDecl() && 6946 NewFD->getReturnType()->isVariablyModifiedType()) { 6947 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6948 NewFD->setInvalidDecl(); 6949 } 6950 6951 // Handle attributes. 6952 ProcessDeclAttributes(S, NewFD, D); 6953 6954 QualType RetType = NewFD->getReturnType(); 6955 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6956 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6957 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6958 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6959 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6960 // Attach the attribute to the new decl. Don't apply the attribute if it 6961 // returns an instance of the class (e.g. assignment operators). 6962 if (!MD || MD->getParent() != Ret) { 6963 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 6964 } 6965 } 6966 6967 if (getLangOpts().OpenCL) { 6968 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 6969 // type declaration will generate a compilation error. 6970 unsigned AddressSpace = RetType.getAddressSpace(); 6971 if (AddressSpace == LangAS::opencl_local || 6972 AddressSpace == LangAS::opencl_global || 6973 AddressSpace == LangAS::opencl_constant) { 6974 Diag(NewFD->getLocation(), 6975 diag::err_opencl_return_value_with_address_space); 6976 NewFD->setInvalidDecl(); 6977 } 6978 } 6979 6980 if (!getLangOpts().CPlusPlus) { 6981 // Perform semantic checking on the function declaration. 6982 bool isExplicitSpecialization=false; 6983 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 6984 CheckMain(NewFD, D.getDeclSpec()); 6985 6986 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 6987 CheckMSVCRTEntryPoint(NewFD); 6988 6989 if (!NewFD->isInvalidDecl()) 6990 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 6991 isExplicitSpecialization)); 6992 else if (!Previous.empty()) 6993 // Make graceful recovery from an invalid redeclaration. 6994 D.setRedeclaration(true); 6995 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 6996 Previous.getResultKind() != LookupResult::FoundOverloaded) && 6997 "previous declaration set still overloaded"); 6998 } else { 6999 // C++11 [replacement.functions]p3: 7000 // The program's definitions shall not be specified as inline. 7001 // 7002 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7003 // 7004 // Suppress the diagnostic if the function is __attribute__((used)), since 7005 // that forces an external definition to be emitted. 7006 if (D.getDeclSpec().isInlineSpecified() && 7007 NewFD->isReplaceableGlobalAllocationFunction() && 7008 !NewFD->hasAttr<UsedAttr>()) 7009 Diag(D.getDeclSpec().getInlineSpecLoc(), 7010 diag::ext_operator_new_delete_declared_inline) 7011 << NewFD->getDeclName(); 7012 7013 // If the declarator is a template-id, translate the parser's template 7014 // argument list into our AST format. 7015 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7016 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7017 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7018 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7019 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7020 TemplateId->NumArgs); 7021 translateTemplateArguments(TemplateArgsPtr, 7022 TemplateArgs); 7023 7024 HasExplicitTemplateArgs = true; 7025 7026 if (NewFD->isInvalidDecl()) { 7027 HasExplicitTemplateArgs = false; 7028 } else if (FunctionTemplate) { 7029 // Function template with explicit template arguments. 7030 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7031 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7032 7033 HasExplicitTemplateArgs = false; 7034 } else if (!isFunctionTemplateSpecialization && 7035 !D.getDeclSpec().isFriendSpecified()) { 7036 // We have encountered something that the user meant to be a 7037 // specialization (because it has explicitly-specified template 7038 // arguments) but that was not introduced with a "template<>" (or had 7039 // too few of them). 7040 // FIXME: Differentiate between attempts for explicit instantiations 7041 // (starting with "template") and the rest. 7042 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7043 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7044 << FixItHint::CreateInsertion( 7045 D.getDeclSpec().getLocStart(), 7046 "template<> "); 7047 isFunctionTemplateSpecialization = true; 7048 } else { 7049 // "friend void foo<>(int);" is an implicit specialization decl. 7050 isFunctionTemplateSpecialization = true; 7051 } 7052 } else if (isFriend && isFunctionTemplateSpecialization) { 7053 // This combination is only possible in a recovery case; the user 7054 // wrote something like: 7055 // template <> friend void foo(int); 7056 // which we're recovering from as if the user had written: 7057 // friend void foo<>(int); 7058 // Go ahead and fake up a template id. 7059 HasExplicitTemplateArgs = true; 7060 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7061 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7062 } 7063 7064 // If it's a friend (and only if it's a friend), it's possible 7065 // that either the specialized function type or the specialized 7066 // template is dependent, and therefore matching will fail. In 7067 // this case, don't check the specialization yet. 7068 bool InstantiationDependent = false; 7069 if (isFunctionTemplateSpecialization && isFriend && 7070 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7071 TemplateSpecializationType::anyDependentTemplateArguments( 7072 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7073 InstantiationDependent))) { 7074 assert(HasExplicitTemplateArgs && 7075 "friend function specialization without template args"); 7076 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7077 Previous)) 7078 NewFD->setInvalidDecl(); 7079 } else if (isFunctionTemplateSpecialization) { 7080 if (CurContext->isDependentContext() && CurContext->isRecord() 7081 && !isFriend) { 7082 isDependentClassScopeExplicitSpecialization = true; 7083 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7084 diag::ext_function_specialization_in_class : 7085 diag::err_function_specialization_in_class) 7086 << NewFD->getDeclName(); 7087 } else if (CheckFunctionTemplateSpecialization(NewFD, 7088 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7089 Previous)) 7090 NewFD->setInvalidDecl(); 7091 7092 // C++ [dcl.stc]p1: 7093 // A storage-class-specifier shall not be specified in an explicit 7094 // specialization (14.7.3) 7095 FunctionTemplateSpecializationInfo *Info = 7096 NewFD->getTemplateSpecializationInfo(); 7097 if (Info && SC != SC_None) { 7098 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7099 Diag(NewFD->getLocation(), 7100 diag::err_explicit_specialization_inconsistent_storage_class) 7101 << SC 7102 << FixItHint::CreateRemoval( 7103 D.getDeclSpec().getStorageClassSpecLoc()); 7104 7105 else 7106 Diag(NewFD->getLocation(), 7107 diag::ext_explicit_specialization_storage_class) 7108 << FixItHint::CreateRemoval( 7109 D.getDeclSpec().getStorageClassSpecLoc()); 7110 } 7111 7112 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7113 if (CheckMemberSpecialization(NewFD, Previous)) 7114 NewFD->setInvalidDecl(); 7115 } 7116 7117 // Perform semantic checking on the function declaration. 7118 if (!isDependentClassScopeExplicitSpecialization) { 7119 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7120 CheckMain(NewFD, D.getDeclSpec()); 7121 7122 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7123 CheckMSVCRTEntryPoint(NewFD); 7124 7125 if (!NewFD->isInvalidDecl()) 7126 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7127 isExplicitSpecialization)); 7128 } 7129 7130 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7131 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7132 "previous declaration set still overloaded"); 7133 7134 NamedDecl *PrincipalDecl = (FunctionTemplate 7135 ? cast<NamedDecl>(FunctionTemplate) 7136 : NewFD); 7137 7138 if (isFriend && D.isRedeclaration()) { 7139 AccessSpecifier Access = AS_public; 7140 if (!NewFD->isInvalidDecl()) 7141 Access = NewFD->getPreviousDecl()->getAccess(); 7142 7143 NewFD->setAccess(Access); 7144 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7145 } 7146 7147 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7148 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7149 PrincipalDecl->setNonMemberOperator(); 7150 7151 // If we have a function template, check the template parameter 7152 // list. This will check and merge default template arguments. 7153 if (FunctionTemplate) { 7154 FunctionTemplateDecl *PrevTemplate = 7155 FunctionTemplate->getPreviousDecl(); 7156 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7157 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7158 D.getDeclSpec().isFriendSpecified() 7159 ? (D.isFunctionDefinition() 7160 ? TPC_FriendFunctionTemplateDefinition 7161 : TPC_FriendFunctionTemplate) 7162 : (D.getCXXScopeSpec().isSet() && 7163 DC && DC->isRecord() && 7164 DC->isDependentContext()) 7165 ? TPC_ClassTemplateMember 7166 : TPC_FunctionTemplate); 7167 } 7168 7169 if (NewFD->isInvalidDecl()) { 7170 // Ignore all the rest of this. 7171 } else if (!D.isRedeclaration()) { 7172 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7173 AddToScope }; 7174 // Fake up an access specifier if it's supposed to be a class member. 7175 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7176 NewFD->setAccess(AS_public); 7177 7178 // Qualified decls generally require a previous declaration. 7179 if (D.getCXXScopeSpec().isSet()) { 7180 // ...with the major exception of templated-scope or 7181 // dependent-scope friend declarations. 7182 7183 // TODO: we currently also suppress this check in dependent 7184 // contexts because (1) the parameter depth will be off when 7185 // matching friend templates and (2) we might actually be 7186 // selecting a friend based on a dependent factor. But there 7187 // are situations where these conditions don't apply and we 7188 // can actually do this check immediately. 7189 if (isFriend && 7190 (TemplateParamLists.size() || 7191 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7192 CurContext->isDependentContext())) { 7193 // ignore these 7194 } else { 7195 // The user tried to provide an out-of-line definition for a 7196 // function that is a member of a class or namespace, but there 7197 // was no such member function declared (C++ [class.mfct]p2, 7198 // C++ [namespace.memdef]p2). For example: 7199 // 7200 // class X { 7201 // void f() const; 7202 // }; 7203 // 7204 // void X::f() { } // ill-formed 7205 // 7206 // Complain about this problem, and attempt to suggest close 7207 // matches (e.g., those that differ only in cv-qualifiers and 7208 // whether the parameter types are references). 7209 7210 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7211 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7212 AddToScope = ExtraArgs.AddToScope; 7213 return Result; 7214 } 7215 } 7216 7217 // Unqualified local friend declarations are required to resolve 7218 // to something. 7219 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7220 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7221 *this, Previous, NewFD, ExtraArgs, true, S)) { 7222 AddToScope = ExtraArgs.AddToScope; 7223 return Result; 7224 } 7225 } 7226 7227 } else if (!D.isFunctionDefinition() && 7228 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7229 !isFriend && !isFunctionTemplateSpecialization && 7230 !isExplicitSpecialization) { 7231 // An out-of-line member function declaration must also be a 7232 // definition (C++ [class.mfct]p2). 7233 // Note that this is not the case for explicit specializations of 7234 // function templates or member functions of class templates, per 7235 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7236 // extension for compatibility with old SWIG code which likes to 7237 // generate them. 7238 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7239 << D.getCXXScopeSpec().getRange(); 7240 } 7241 } 7242 7243 ProcessPragmaWeak(S, NewFD); 7244 checkAttributesAfterMerging(*this, *NewFD); 7245 7246 AddKnownFunctionAttributes(NewFD); 7247 7248 if (NewFD->hasAttr<OverloadableAttr>() && 7249 !NewFD->getType()->getAs<FunctionProtoType>()) { 7250 Diag(NewFD->getLocation(), 7251 diag::err_attribute_overloadable_no_prototype) 7252 << NewFD; 7253 7254 // Turn this into a variadic function with no parameters. 7255 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7256 FunctionProtoType::ExtProtoInfo EPI( 7257 Context.getDefaultCallingConvention(true, false)); 7258 EPI.Variadic = true; 7259 EPI.ExtInfo = FT->getExtInfo(); 7260 7261 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7262 NewFD->setType(R); 7263 } 7264 7265 // If there's a #pragma GCC visibility in scope, and this isn't a class 7266 // member, set the visibility of this function. 7267 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7268 AddPushedVisibilityAttribute(NewFD); 7269 7270 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7271 // marking the function. 7272 AddCFAuditedAttribute(NewFD); 7273 7274 // If this is the first declaration of an extern C variable, update 7275 // the map of such variables. 7276 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7277 isIncompleteDeclExternC(*this, NewFD)) 7278 RegisterLocallyScopedExternCDecl(NewFD, S); 7279 7280 // Set this FunctionDecl's range up to the right paren. 7281 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7282 7283 if (getLangOpts().CPlusPlus) { 7284 if (FunctionTemplate) { 7285 if (NewFD->isInvalidDecl()) 7286 FunctionTemplate->setInvalidDecl(); 7287 return FunctionTemplate; 7288 } 7289 } 7290 7291 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7292 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7293 if ((getLangOpts().OpenCLVersion >= 120) 7294 && (SC == SC_Static)) { 7295 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7296 D.setInvalidType(); 7297 } 7298 7299 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7300 if (!NewFD->getReturnType()->isVoidType()) { 7301 Diag(D.getIdentifierLoc(), 7302 diag::err_expected_kernel_void_return_type); 7303 D.setInvalidType(); 7304 } 7305 7306 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7307 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 7308 PE = NewFD->param_end(); PI != PE; ++PI) { 7309 ParmVarDecl *Param = *PI; 7310 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7311 } 7312 } 7313 7314 MarkUnusedFileScopedDecl(NewFD); 7315 7316 if (getLangOpts().CUDA) 7317 if (IdentifierInfo *II = NewFD->getIdentifier()) 7318 if (!NewFD->isInvalidDecl() && 7319 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7320 if (II->isStr("cudaConfigureCall")) { 7321 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7322 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7323 7324 Context.setcudaConfigureCallDecl(NewFD); 7325 } 7326 } 7327 7328 // Here we have an function template explicit specialization at class scope. 7329 // The actually specialization will be postponed to template instatiation 7330 // time via the ClassScopeFunctionSpecializationDecl node. 7331 if (isDependentClassScopeExplicitSpecialization) { 7332 ClassScopeFunctionSpecializationDecl *NewSpec = 7333 ClassScopeFunctionSpecializationDecl::Create( 7334 Context, CurContext, SourceLocation(), 7335 cast<CXXMethodDecl>(NewFD), 7336 HasExplicitTemplateArgs, TemplateArgs); 7337 CurContext->addDecl(NewSpec); 7338 AddToScope = false; 7339 } 7340 7341 return NewFD; 7342 } 7343 7344 /// \brief Perform semantic checking of a new function declaration. 7345 /// 7346 /// Performs semantic analysis of the new function declaration 7347 /// NewFD. This routine performs all semantic checking that does not 7348 /// require the actual declarator involved in the declaration, and is 7349 /// used both for the declaration of functions as they are parsed 7350 /// (called via ActOnDeclarator) and for the declaration of functions 7351 /// that have been instantiated via C++ template instantiation (called 7352 /// via InstantiateDecl). 7353 /// 7354 /// \param IsExplicitSpecialization whether this new function declaration is 7355 /// an explicit specialization of the previous declaration. 7356 /// 7357 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7358 /// 7359 /// \returns true if the function declaration is a redeclaration. 7360 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7361 LookupResult &Previous, 7362 bool IsExplicitSpecialization) { 7363 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7364 "Variably modified return types are not handled here"); 7365 7366 // Determine whether the type of this function should be merged with 7367 // a previous visible declaration. This never happens for functions in C++, 7368 // and always happens in C if the previous declaration was visible. 7369 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7370 !Previous.isShadowed(); 7371 7372 // Filter out any non-conflicting previous declarations. 7373 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7374 7375 bool Redeclaration = false; 7376 NamedDecl *OldDecl = 0; 7377 7378 // Merge or overload the declaration with an existing declaration of 7379 // the same name, if appropriate. 7380 if (!Previous.empty()) { 7381 // Determine whether NewFD is an overload of PrevDecl or 7382 // a declaration that requires merging. If it's an overload, 7383 // there's no more work to do here; we'll just add the new 7384 // function to the scope. 7385 if (!AllowOverloadingOfFunction(Previous, Context)) { 7386 NamedDecl *Candidate = Previous.getFoundDecl(); 7387 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7388 Redeclaration = true; 7389 OldDecl = Candidate; 7390 } 7391 } else { 7392 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7393 /*NewIsUsingDecl*/ false)) { 7394 case Ovl_Match: 7395 Redeclaration = true; 7396 break; 7397 7398 case Ovl_NonFunction: 7399 Redeclaration = true; 7400 break; 7401 7402 case Ovl_Overload: 7403 Redeclaration = false; 7404 break; 7405 } 7406 7407 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7408 // If a function name is overloadable in C, then every function 7409 // with that name must be marked "overloadable". 7410 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7411 << Redeclaration << NewFD; 7412 NamedDecl *OverloadedDecl = 0; 7413 if (Redeclaration) 7414 OverloadedDecl = OldDecl; 7415 else if (!Previous.empty()) 7416 OverloadedDecl = Previous.getRepresentativeDecl(); 7417 if (OverloadedDecl) 7418 Diag(OverloadedDecl->getLocation(), 7419 diag::note_attribute_overloadable_prev_overload); 7420 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7421 } 7422 } 7423 } 7424 7425 // Check for a previous extern "C" declaration with this name. 7426 if (!Redeclaration && 7427 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7428 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7429 if (!Previous.empty()) { 7430 // This is an extern "C" declaration with the same name as a previous 7431 // declaration, and thus redeclares that entity... 7432 Redeclaration = true; 7433 OldDecl = Previous.getFoundDecl(); 7434 MergeTypeWithPrevious = false; 7435 7436 // ... except in the presence of __attribute__((overloadable)). 7437 if (OldDecl->hasAttr<OverloadableAttr>()) { 7438 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7439 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7440 << Redeclaration << NewFD; 7441 Diag(Previous.getFoundDecl()->getLocation(), 7442 diag::note_attribute_overloadable_prev_overload); 7443 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7444 } 7445 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7446 Redeclaration = false; 7447 OldDecl = 0; 7448 } 7449 } 7450 } 7451 } 7452 7453 // C++11 [dcl.constexpr]p8: 7454 // A constexpr specifier for a non-static member function that is not 7455 // a constructor declares that member function to be const. 7456 // 7457 // This needs to be delayed until we know whether this is an out-of-line 7458 // definition of a static member function. 7459 // 7460 // This rule is not present in C++1y, so we produce a backwards 7461 // compatibility warning whenever it happens in C++11. 7462 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7463 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7464 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7465 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7466 CXXMethodDecl *OldMD = 0; 7467 if (OldDecl) 7468 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7469 if (!OldMD || !OldMD->isStatic()) { 7470 const FunctionProtoType *FPT = 7471 MD->getType()->castAs<FunctionProtoType>(); 7472 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7473 EPI.TypeQuals |= Qualifiers::Const; 7474 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7475 FPT->getParamTypes(), EPI)); 7476 7477 // Warn that we did this, if we're not performing template instantiation. 7478 // In that case, we'll have warned already when the template was defined. 7479 if (ActiveTemplateInstantiations.empty()) { 7480 SourceLocation AddConstLoc; 7481 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7482 .IgnoreParens().getAs<FunctionTypeLoc>()) 7483 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7484 7485 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7486 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7487 } 7488 } 7489 } 7490 7491 if (Redeclaration) { 7492 // NewFD and OldDecl represent declarations that need to be 7493 // merged. 7494 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7495 NewFD->setInvalidDecl(); 7496 return Redeclaration; 7497 } 7498 7499 Previous.clear(); 7500 Previous.addDecl(OldDecl); 7501 7502 if (FunctionTemplateDecl *OldTemplateDecl 7503 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7504 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7505 FunctionTemplateDecl *NewTemplateDecl 7506 = NewFD->getDescribedFunctionTemplate(); 7507 assert(NewTemplateDecl && "Template/non-template mismatch"); 7508 if (CXXMethodDecl *Method 7509 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7510 Method->setAccess(OldTemplateDecl->getAccess()); 7511 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7512 } 7513 7514 // If this is an explicit specialization of a member that is a function 7515 // template, mark it as a member specialization. 7516 if (IsExplicitSpecialization && 7517 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7518 NewTemplateDecl->setMemberSpecialization(); 7519 assert(OldTemplateDecl->isMemberSpecialization()); 7520 } 7521 7522 } else { 7523 // This needs to happen first so that 'inline' propagates. 7524 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7525 7526 if (isa<CXXMethodDecl>(NewFD)) { 7527 // A valid redeclaration of a C++ method must be out-of-line, 7528 // but (unfortunately) it's not necessarily a definition 7529 // because of templates, which means that the previous 7530 // declaration is not necessarily from the class definition. 7531 7532 // For just setting the access, that doesn't matter. 7533 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7534 NewFD->setAccess(oldMethod->getAccess()); 7535 7536 // Update the key-function state if necessary for this ABI. 7537 if (NewFD->isInlined() && 7538 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7539 // setNonKeyFunction needs to work with the original 7540 // declaration from the class definition, and isVirtual() is 7541 // just faster in that case, so map back to that now. 7542 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7543 if (oldMethod->isVirtual()) { 7544 Context.setNonKeyFunction(oldMethod); 7545 } 7546 } 7547 } 7548 } 7549 } 7550 7551 // Semantic checking for this function declaration (in isolation). 7552 if (getLangOpts().CPlusPlus) { 7553 // C++-specific checks. 7554 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7555 CheckConstructor(Constructor); 7556 } else if (CXXDestructorDecl *Destructor = 7557 dyn_cast<CXXDestructorDecl>(NewFD)) { 7558 CXXRecordDecl *Record = Destructor->getParent(); 7559 QualType ClassType = Context.getTypeDeclType(Record); 7560 7561 // FIXME: Shouldn't we be able to perform this check even when the class 7562 // type is dependent? Both gcc and edg can handle that. 7563 if (!ClassType->isDependentType()) { 7564 DeclarationName Name 7565 = Context.DeclarationNames.getCXXDestructorName( 7566 Context.getCanonicalType(ClassType)); 7567 if (NewFD->getDeclName() != Name) { 7568 Diag(NewFD->getLocation(), diag::err_destructor_name); 7569 NewFD->setInvalidDecl(); 7570 return Redeclaration; 7571 } 7572 } 7573 } else if (CXXConversionDecl *Conversion 7574 = dyn_cast<CXXConversionDecl>(NewFD)) { 7575 ActOnConversionDeclarator(Conversion); 7576 } 7577 7578 // Find any virtual functions that this function overrides. 7579 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7580 if (!Method->isFunctionTemplateSpecialization() && 7581 !Method->getDescribedFunctionTemplate() && 7582 Method->isCanonicalDecl()) { 7583 if (AddOverriddenMethods(Method->getParent(), Method)) { 7584 // If the function was marked as "static", we have a problem. 7585 if (NewFD->getStorageClass() == SC_Static) { 7586 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7587 } 7588 } 7589 } 7590 7591 if (Method->isStatic()) 7592 checkThisInStaticMemberFunctionType(Method); 7593 } 7594 7595 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7596 if (NewFD->isOverloadedOperator() && 7597 CheckOverloadedOperatorDeclaration(NewFD)) { 7598 NewFD->setInvalidDecl(); 7599 return Redeclaration; 7600 } 7601 7602 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7603 if (NewFD->getLiteralIdentifier() && 7604 CheckLiteralOperatorDeclaration(NewFD)) { 7605 NewFD->setInvalidDecl(); 7606 return Redeclaration; 7607 } 7608 7609 // In C++, check default arguments now that we have merged decls. Unless 7610 // the lexical context is the class, because in this case this is done 7611 // during delayed parsing anyway. 7612 if (!CurContext->isRecord()) 7613 CheckCXXDefaultArguments(NewFD); 7614 7615 // If this function declares a builtin function, check the type of this 7616 // declaration against the expected type for the builtin. 7617 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7618 ASTContext::GetBuiltinTypeError Error; 7619 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7620 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7621 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7622 // The type of this function differs from the type of the builtin, 7623 // so forget about the builtin entirely. 7624 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7625 } 7626 } 7627 7628 // If this function is declared as being extern "C", then check to see if 7629 // the function returns a UDT (class, struct, or union type) that is not C 7630 // compatible, and if it does, warn the user. 7631 // But, issue any diagnostic on the first declaration only. 7632 if (NewFD->isExternC() && Previous.empty()) { 7633 QualType R = NewFD->getReturnType(); 7634 if (R->isIncompleteType() && !R->isVoidType()) 7635 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7636 << NewFD << R; 7637 else if (!R.isPODType(Context) && !R->isVoidType() && 7638 !R->isObjCObjectPointerType()) 7639 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7640 } 7641 } 7642 return Redeclaration; 7643 } 7644 7645 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7646 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7647 if (!TSI) 7648 return SourceRange(); 7649 7650 TypeLoc TL = TSI->getTypeLoc(); 7651 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7652 if (!FunctionTL) 7653 return SourceRange(); 7654 7655 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7656 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7657 return ResultTL.getSourceRange(); 7658 7659 return SourceRange(); 7660 } 7661 7662 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7663 // C++11 [basic.start.main]p3: 7664 // A program that [...] declares main to be inline, static or 7665 // constexpr is ill-formed. 7666 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7667 // appear in a declaration of main. 7668 // static main is not an error under C99, but we should warn about it. 7669 // We accept _Noreturn main as an extension. 7670 if (FD->getStorageClass() == SC_Static) 7671 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7672 ? diag::err_static_main : diag::warn_static_main) 7673 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7674 if (FD->isInlineSpecified()) 7675 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7676 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7677 if (DS.isNoreturnSpecified()) { 7678 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7679 SourceRange NoreturnRange(NoreturnLoc, 7680 PP.getLocForEndOfToken(NoreturnLoc)); 7681 Diag(NoreturnLoc, diag::ext_noreturn_main); 7682 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7683 << FixItHint::CreateRemoval(NoreturnRange); 7684 } 7685 if (FD->isConstexpr()) { 7686 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7687 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7688 FD->setConstexpr(false); 7689 } 7690 7691 if (getLangOpts().OpenCL) { 7692 Diag(FD->getLocation(), diag::err_opencl_no_main) 7693 << FD->hasAttr<OpenCLKernelAttr>(); 7694 FD->setInvalidDecl(); 7695 return; 7696 } 7697 7698 QualType T = FD->getType(); 7699 assert(T->isFunctionType() && "function decl is not of function type"); 7700 const FunctionType* FT = T->castAs<FunctionType>(); 7701 7702 // All the standards say that main() should should return 'int'. 7703 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7704 // In C and C++, main magically returns 0 if you fall off the end; 7705 // set the flag which tells us that. 7706 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7707 FD->setHasImplicitReturnZero(true); 7708 7709 // In C with GNU extensions we allow main() to have non-integer return 7710 // type, but we should warn about the extension, and we disable the 7711 // implicit-return-zero rule. 7712 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7713 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7714 7715 SourceRange ResultRange = getResultSourceRange(FD); 7716 if (ResultRange.isValid()) 7717 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7718 << FixItHint::CreateReplacement(ResultRange, "int"); 7719 7720 // Otherwise, this is just a flat-out error. 7721 } else { 7722 SourceRange ResultRange = getResultSourceRange(FD); 7723 if (ResultRange.isValid()) 7724 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7725 << FixItHint::CreateReplacement(ResultRange, "int"); 7726 else 7727 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7728 7729 FD->setInvalidDecl(true); 7730 } 7731 7732 // Treat protoless main() as nullary. 7733 if (isa<FunctionNoProtoType>(FT)) return; 7734 7735 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7736 unsigned nparams = FTP->getNumParams(); 7737 assert(FD->getNumParams() == nparams); 7738 7739 bool HasExtraParameters = (nparams > 3); 7740 7741 // Darwin passes an undocumented fourth argument of type char**. If 7742 // other platforms start sprouting these, the logic below will start 7743 // getting shifty. 7744 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7745 HasExtraParameters = false; 7746 7747 if (HasExtraParameters) { 7748 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7749 FD->setInvalidDecl(true); 7750 nparams = 3; 7751 } 7752 7753 // FIXME: a lot of the following diagnostics would be improved 7754 // if we had some location information about types. 7755 7756 QualType CharPP = 7757 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7758 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7759 7760 for (unsigned i = 0; i < nparams; ++i) { 7761 QualType AT = FTP->getParamType(i); 7762 7763 bool mismatch = true; 7764 7765 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7766 mismatch = false; 7767 else if (Expected[i] == CharPP) { 7768 // As an extension, the following forms are okay: 7769 // char const ** 7770 // char const * const * 7771 // char * const * 7772 7773 QualifierCollector qs; 7774 const PointerType* PT; 7775 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7776 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7777 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7778 Context.CharTy)) { 7779 qs.removeConst(); 7780 mismatch = !qs.empty(); 7781 } 7782 } 7783 7784 if (mismatch) { 7785 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7786 // TODO: suggest replacing given type with expected type 7787 FD->setInvalidDecl(true); 7788 } 7789 } 7790 7791 if (nparams == 1 && !FD->isInvalidDecl()) { 7792 Diag(FD->getLocation(), diag::warn_main_one_arg); 7793 } 7794 7795 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7796 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7797 FD->setInvalidDecl(); 7798 } 7799 } 7800 7801 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7802 QualType T = FD->getType(); 7803 assert(T->isFunctionType() && "function decl is not of function type"); 7804 const FunctionType *FT = T->castAs<FunctionType>(); 7805 7806 // Set an implicit return of 'zero' if the function can return some integral, 7807 // enumeration, pointer or nullptr type. 7808 if (FT->getReturnType()->isIntegralOrEnumerationType() || 7809 FT->getReturnType()->isAnyPointerType() || 7810 FT->getReturnType()->isNullPtrType()) 7811 // DllMain is exempt because a return value of zero means it failed. 7812 if (FD->getName() != "DllMain") 7813 FD->setHasImplicitReturnZero(true); 7814 7815 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7816 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7817 FD->setInvalidDecl(); 7818 } 7819 } 7820 7821 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7822 // FIXME: Need strict checking. In C89, we need to check for 7823 // any assignment, increment, decrement, function-calls, or 7824 // commas outside of a sizeof. In C99, it's the same list, 7825 // except that the aforementioned are allowed in unevaluated 7826 // expressions. Everything else falls under the 7827 // "may accept other forms of constant expressions" exception. 7828 // (We never end up here for C++, so the constant expression 7829 // rules there don't matter.) 7830 if (Init->isConstantInitializer(Context, false)) 7831 return false; 7832 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7833 << Init->getSourceRange(); 7834 return true; 7835 } 7836 7837 namespace { 7838 // Visits an initialization expression to see if OrigDecl is evaluated in 7839 // its own initialization and throws a warning if it does. 7840 class SelfReferenceChecker 7841 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7842 Sema &S; 7843 Decl *OrigDecl; 7844 bool isRecordType; 7845 bool isPODType; 7846 bool isReferenceType; 7847 7848 public: 7849 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7850 7851 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7852 S(S), OrigDecl(OrigDecl) { 7853 isPODType = false; 7854 isRecordType = false; 7855 isReferenceType = false; 7856 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7857 isPODType = VD->getType().isPODType(S.Context); 7858 isRecordType = VD->getType()->isRecordType(); 7859 isReferenceType = VD->getType()->isReferenceType(); 7860 } 7861 } 7862 7863 // For most expressions, the cast is directly above the DeclRefExpr. 7864 // For conditional operators, the cast can be outside the conditional 7865 // operator if both expressions are DeclRefExpr's. 7866 void HandleValue(Expr *E) { 7867 if (isReferenceType) 7868 return; 7869 E = E->IgnoreParenImpCasts(); 7870 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7871 HandleDeclRefExpr(DRE); 7872 return; 7873 } 7874 7875 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7876 HandleValue(CO->getTrueExpr()); 7877 HandleValue(CO->getFalseExpr()); 7878 return; 7879 } 7880 7881 if (isa<MemberExpr>(E)) { 7882 Expr *Base = E->IgnoreParenImpCasts(); 7883 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7884 // Check for static member variables and don't warn on them. 7885 if (!isa<FieldDecl>(ME->getMemberDecl())) 7886 return; 7887 Base = ME->getBase()->IgnoreParenImpCasts(); 7888 } 7889 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7890 HandleDeclRefExpr(DRE); 7891 return; 7892 } 7893 } 7894 7895 // Reference types are handled here since all uses of references are 7896 // bad, not just r-value uses. 7897 void VisitDeclRefExpr(DeclRefExpr *E) { 7898 if (isReferenceType) 7899 HandleDeclRefExpr(E); 7900 } 7901 7902 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7903 if (E->getCastKind() == CK_LValueToRValue || 7904 (isRecordType && E->getCastKind() == CK_NoOp)) 7905 HandleValue(E->getSubExpr()); 7906 7907 Inherited::VisitImplicitCastExpr(E); 7908 } 7909 7910 void VisitMemberExpr(MemberExpr *E) { 7911 // Don't warn on arrays since they can be treated as pointers. 7912 if (E->getType()->canDecayToPointerType()) return; 7913 7914 // Warn when a non-static method call is followed by non-static member 7915 // field accesses, which is followed by a DeclRefExpr. 7916 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7917 bool Warn = (MD && !MD->isStatic()); 7918 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7919 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7920 if (!isa<FieldDecl>(ME->getMemberDecl())) 7921 Warn = false; 7922 Base = ME->getBase()->IgnoreParenImpCasts(); 7923 } 7924 7925 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7926 if (Warn) 7927 HandleDeclRefExpr(DRE); 7928 return; 7929 } 7930 7931 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7932 // Visit that expression. 7933 Visit(Base); 7934 } 7935 7936 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7937 if (E->getNumArgs() > 0) 7938 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7939 HandleDeclRefExpr(DRE); 7940 7941 Inherited::VisitCXXOperatorCallExpr(E); 7942 } 7943 7944 void VisitUnaryOperator(UnaryOperator *E) { 7945 // For POD record types, addresses of its own members are well-defined. 7946 if (E->getOpcode() == UO_AddrOf && isRecordType && 7947 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7948 if (!isPODType) 7949 HandleValue(E->getSubExpr()); 7950 return; 7951 } 7952 Inherited::VisitUnaryOperator(E); 7953 } 7954 7955 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7956 7957 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7958 Decl* ReferenceDecl = DRE->getDecl(); 7959 if (OrigDecl != ReferenceDecl) return; 7960 unsigned diag; 7961 if (isReferenceType) { 7962 diag = diag::warn_uninit_self_reference_in_reference_init; 7963 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7964 diag = diag::warn_static_self_reference_in_init; 7965 } else { 7966 diag = diag::warn_uninit_self_reference_in_init; 7967 } 7968 7969 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7970 S.PDiag(diag) 7971 << DRE->getNameInfo().getName() 7972 << OrigDecl->getLocation() 7973 << DRE->getSourceRange()); 7974 } 7975 }; 7976 7977 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 7978 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 7979 bool DirectInit) { 7980 // Parameters arguments are occassionially constructed with itself, 7981 // for instance, in recursive functions. Skip them. 7982 if (isa<ParmVarDecl>(OrigDecl)) 7983 return; 7984 7985 E = E->IgnoreParens(); 7986 7987 // Skip checking T a = a where T is not a record or reference type. 7988 // Doing so is a way to silence uninitialized warnings. 7989 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 7990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 7991 if (ICE->getCastKind() == CK_LValueToRValue) 7992 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 7993 if (DRE->getDecl() == OrigDecl) 7994 return; 7995 7996 SelfReferenceChecker(S, OrigDecl).Visit(E); 7997 } 7998 } 7999 8000 /// AddInitializerToDecl - Adds the initializer Init to the 8001 /// declaration dcl. If DirectInit is true, this is C++ direct 8002 /// initialization rather than copy initialization. 8003 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8004 bool DirectInit, bool TypeMayContainAuto) { 8005 // If there is no declaration, there was an error parsing it. Just ignore 8006 // the initializer. 8007 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8008 return; 8009 8010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8011 // With declarators parsed the way they are, the parser cannot 8012 // distinguish between a normal initializer and a pure-specifier. 8013 // Thus this grotesque test. 8014 IntegerLiteral *IL; 8015 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8016 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8017 CheckPureMethod(Method, Init->getSourceRange()); 8018 else { 8019 Diag(Method->getLocation(), diag::err_member_function_initialization) 8020 << Method->getDeclName() << Init->getSourceRange(); 8021 Method->setInvalidDecl(); 8022 } 8023 return; 8024 } 8025 8026 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8027 if (!VDecl) { 8028 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8029 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8030 RealDecl->setInvalidDecl(); 8031 return; 8032 } 8033 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8034 8035 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8036 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8037 Expr *DeduceInit = Init; 8038 // Initializer could be a C++ direct-initializer. Deduction only works if it 8039 // contains exactly one expression. 8040 if (CXXDirectInit) { 8041 if (CXXDirectInit->getNumExprs() == 0) { 8042 // It isn't possible to write this directly, but it is possible to 8043 // end up in this situation with "auto x(some_pack...);" 8044 Diag(CXXDirectInit->getLocStart(), 8045 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8046 : diag::err_auto_var_init_no_expression) 8047 << VDecl->getDeclName() << VDecl->getType() 8048 << VDecl->getSourceRange(); 8049 RealDecl->setInvalidDecl(); 8050 return; 8051 } else if (CXXDirectInit->getNumExprs() > 1) { 8052 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8053 VDecl->isInitCapture() 8054 ? diag::err_init_capture_multiple_expressions 8055 : diag::err_auto_var_init_multiple_expressions) 8056 << VDecl->getDeclName() << VDecl->getType() 8057 << VDecl->getSourceRange(); 8058 RealDecl->setInvalidDecl(); 8059 return; 8060 } else { 8061 DeduceInit = CXXDirectInit->getExpr(0); 8062 } 8063 } 8064 8065 // Expressions default to 'id' when we're in a debugger. 8066 bool DefaultedToAuto = false; 8067 if (getLangOpts().DebuggerCastResultToId && 8068 Init->getType() == Context.UnknownAnyTy) { 8069 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8070 if (Result.isInvalid()) { 8071 VDecl->setInvalidDecl(); 8072 return; 8073 } 8074 Init = Result.take(); 8075 DefaultedToAuto = true; 8076 } 8077 8078 QualType DeducedType; 8079 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8080 DAR_Failed) 8081 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8082 if (DeducedType.isNull()) { 8083 RealDecl->setInvalidDecl(); 8084 return; 8085 } 8086 VDecl->setType(DeducedType); 8087 assert(VDecl->isLinkageValid()); 8088 8089 // In ARC, infer lifetime. 8090 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8091 VDecl->setInvalidDecl(); 8092 8093 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8094 // 'id' instead of a specific object type prevents most of our usual checks. 8095 // We only want to warn outside of template instantiations, though: 8096 // inside a template, the 'id' could have come from a parameter. 8097 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8098 DeducedType->isObjCIdType()) { 8099 SourceLocation Loc = 8100 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8101 Diag(Loc, diag::warn_auto_var_is_id) 8102 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8103 } 8104 8105 // If this is a redeclaration, check that the type we just deduced matches 8106 // the previously declared type. 8107 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8108 // We never need to merge the type, because we cannot form an incomplete 8109 // array of auto, nor deduce such a type. 8110 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8111 } 8112 8113 // Check the deduced type is valid for a variable declaration. 8114 CheckVariableDeclarationType(VDecl); 8115 if (VDecl->isInvalidDecl()) 8116 return; 8117 } 8118 8119 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8120 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8121 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8122 VDecl->setInvalidDecl(); 8123 return; 8124 } 8125 8126 if (!VDecl->getType()->isDependentType()) { 8127 // A definition must end up with a complete type, which means it must be 8128 // complete with the restriction that an array type might be completed by 8129 // the initializer; note that later code assumes this restriction. 8130 QualType BaseDeclType = VDecl->getType(); 8131 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8132 BaseDeclType = Array->getElementType(); 8133 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8134 diag::err_typecheck_decl_incomplete_type)) { 8135 RealDecl->setInvalidDecl(); 8136 return; 8137 } 8138 8139 // The variable can not have an abstract class type. 8140 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8141 diag::err_abstract_type_in_decl, 8142 AbstractVariableType)) 8143 VDecl->setInvalidDecl(); 8144 } 8145 8146 const VarDecl *Def; 8147 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8148 Diag(VDecl->getLocation(), diag::err_redefinition) 8149 << VDecl->getDeclName(); 8150 Diag(Def->getLocation(), diag::note_previous_definition); 8151 VDecl->setInvalidDecl(); 8152 return; 8153 } 8154 8155 const VarDecl* PrevInit = 0; 8156 if (getLangOpts().CPlusPlus) { 8157 // C++ [class.static.data]p4 8158 // If a static data member is of const integral or const 8159 // enumeration type, its declaration in the class definition can 8160 // specify a constant-initializer which shall be an integral 8161 // constant expression (5.19). In that case, the member can appear 8162 // in integral constant expressions. The member shall still be 8163 // defined in a namespace scope if it is used in the program and the 8164 // namespace scope definition shall not contain an initializer. 8165 // 8166 // We already performed a redefinition check above, but for static 8167 // data members we also need to check whether there was an in-class 8168 // declaration with an initializer. 8169 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8170 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8171 << VDecl->getDeclName(); 8172 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8173 return; 8174 } 8175 8176 if (VDecl->hasLocalStorage()) 8177 getCurFunction()->setHasBranchProtectedScope(); 8178 8179 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8180 VDecl->setInvalidDecl(); 8181 return; 8182 } 8183 } 8184 8185 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8186 // a kernel function cannot be initialized." 8187 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8188 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8189 VDecl->setInvalidDecl(); 8190 return; 8191 } 8192 8193 // Get the decls type and save a reference for later, since 8194 // CheckInitializerTypes may change it. 8195 QualType DclT = VDecl->getType(), SavT = DclT; 8196 8197 // Expressions default to 'id' when we're in a debugger 8198 // and we are assigning it to a variable of Objective-C pointer type. 8199 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8200 Init->getType() == Context.UnknownAnyTy) { 8201 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8202 if (Result.isInvalid()) { 8203 VDecl->setInvalidDecl(); 8204 return; 8205 } 8206 Init = Result.take(); 8207 } 8208 8209 // Perform the initialization. 8210 if (!VDecl->isInvalidDecl()) { 8211 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8212 InitializationKind Kind 8213 = DirectInit ? 8214 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8215 Init->getLocStart(), 8216 Init->getLocEnd()) 8217 : InitializationKind::CreateDirectList( 8218 VDecl->getLocation()) 8219 : InitializationKind::CreateCopy(VDecl->getLocation(), 8220 Init->getLocStart()); 8221 8222 MultiExprArg Args = Init; 8223 if (CXXDirectInit) 8224 Args = MultiExprArg(CXXDirectInit->getExprs(), 8225 CXXDirectInit->getNumExprs()); 8226 8227 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8228 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8229 if (Result.isInvalid()) { 8230 VDecl->setInvalidDecl(); 8231 return; 8232 } 8233 8234 Init = Result.takeAs<Expr>(); 8235 } 8236 8237 // Check for self-references within variable initializers. 8238 // Variables declared within a function/method body (except for references) 8239 // are handled by a dataflow analysis. 8240 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8241 VDecl->getType()->isReferenceType()) { 8242 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8243 } 8244 8245 // If the type changed, it means we had an incomplete type that was 8246 // completed by the initializer. For example: 8247 // int ary[] = { 1, 3, 5 }; 8248 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8249 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8250 VDecl->setType(DclT); 8251 8252 if (!VDecl->isInvalidDecl()) { 8253 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8254 8255 if (VDecl->hasAttr<BlocksAttr>()) 8256 checkRetainCycles(VDecl, Init); 8257 8258 // It is safe to assign a weak reference into a strong variable. 8259 // Although this code can still have problems: 8260 // id x = self.weakProp; 8261 // id y = self.weakProp; 8262 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8263 // paths through the function. This should be revisited if 8264 // -Wrepeated-use-of-weak is made flow-sensitive. 8265 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8266 DiagnosticsEngine::Level Level = 8267 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8268 Init->getLocStart()); 8269 if (Level != DiagnosticsEngine::Ignored) 8270 getCurFunction()->markSafeWeakUse(Init); 8271 } 8272 } 8273 8274 // The initialization is usually a full-expression. 8275 // 8276 // FIXME: If this is a braced initialization of an aggregate, it is not 8277 // an expression, and each individual field initializer is a separate 8278 // full-expression. For instance, in: 8279 // 8280 // struct Temp { ~Temp(); }; 8281 // struct S { S(Temp); }; 8282 // struct T { S a, b; } t = { Temp(), Temp() } 8283 // 8284 // we should destroy the first Temp before constructing the second. 8285 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8286 false, 8287 VDecl->isConstexpr()); 8288 if (Result.isInvalid()) { 8289 VDecl->setInvalidDecl(); 8290 return; 8291 } 8292 Init = Result.take(); 8293 8294 // Attach the initializer to the decl. 8295 VDecl->setInit(Init); 8296 8297 if (VDecl->isLocalVarDecl()) { 8298 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8299 // static storage duration shall be constant expressions or string literals. 8300 // C++ does not have this restriction. 8301 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8302 if (VDecl->getStorageClass() == SC_Static) 8303 CheckForConstantInitializer(Init, DclT); 8304 // C89 is stricter than C99 for non-static aggregate types. 8305 // C89 6.5.7p3: All the expressions [...] in an initializer list 8306 // for an object that has aggregate or union type shall be 8307 // constant expressions. 8308 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8309 isa<InitListExpr>(Init) && 8310 !Init->isConstantInitializer(Context, false)) 8311 Diag(Init->getExprLoc(), 8312 diag::ext_aggregate_init_not_constant) 8313 << Init->getSourceRange(); 8314 } 8315 } else if (VDecl->isStaticDataMember() && 8316 VDecl->getLexicalDeclContext()->isRecord()) { 8317 // This is an in-class initialization for a static data member, e.g., 8318 // 8319 // struct S { 8320 // static const int value = 17; 8321 // }; 8322 8323 // C++ [class.mem]p4: 8324 // A member-declarator can contain a constant-initializer only 8325 // if it declares a static member (9.4) of const integral or 8326 // const enumeration type, see 9.4.2. 8327 // 8328 // C++11 [class.static.data]p3: 8329 // If a non-volatile const static data member is of integral or 8330 // enumeration type, its declaration in the class definition can 8331 // specify a brace-or-equal-initializer in which every initalizer-clause 8332 // that is an assignment-expression is a constant expression. A static 8333 // data member of literal type can be declared in the class definition 8334 // with the constexpr specifier; if so, its declaration shall specify a 8335 // brace-or-equal-initializer in which every initializer-clause that is 8336 // an assignment-expression is a constant expression. 8337 8338 // Do nothing on dependent types. 8339 if (DclT->isDependentType()) { 8340 8341 // Allow any 'static constexpr' members, whether or not they are of literal 8342 // type. We separately check that every constexpr variable is of literal 8343 // type. 8344 } else if (VDecl->isConstexpr()) { 8345 8346 // Require constness. 8347 } else if (!DclT.isConstQualified()) { 8348 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8349 << Init->getSourceRange(); 8350 VDecl->setInvalidDecl(); 8351 8352 // We allow integer constant expressions in all cases. 8353 } else if (DclT->isIntegralOrEnumerationType()) { 8354 // Check whether the expression is a constant expression. 8355 SourceLocation Loc; 8356 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8357 // In C++11, a non-constexpr const static data member with an 8358 // in-class initializer cannot be volatile. 8359 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8360 else if (Init->isValueDependent()) 8361 ; // Nothing to check. 8362 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8363 ; // Ok, it's an ICE! 8364 else if (Init->isEvaluatable(Context)) { 8365 // If we can constant fold the initializer through heroics, accept it, 8366 // but report this as a use of an extension for -pedantic. 8367 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8368 << Init->getSourceRange(); 8369 } else { 8370 // Otherwise, this is some crazy unknown case. Report the issue at the 8371 // location provided by the isIntegerConstantExpr failed check. 8372 Diag(Loc, diag::err_in_class_initializer_non_constant) 8373 << Init->getSourceRange(); 8374 VDecl->setInvalidDecl(); 8375 } 8376 8377 // We allow foldable floating-point constants as an extension. 8378 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8379 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8380 // it anyway and provide a fixit to add the 'constexpr'. 8381 if (getLangOpts().CPlusPlus11) { 8382 Diag(VDecl->getLocation(), 8383 diag::ext_in_class_initializer_float_type_cxx11) 8384 << DclT << Init->getSourceRange(); 8385 Diag(VDecl->getLocStart(), 8386 diag::note_in_class_initializer_float_type_cxx11) 8387 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8388 } else { 8389 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8390 << DclT << Init->getSourceRange(); 8391 8392 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8393 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8394 << Init->getSourceRange(); 8395 VDecl->setInvalidDecl(); 8396 } 8397 } 8398 8399 // Suggest adding 'constexpr' in C++11 for literal types. 8400 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8401 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8402 << DclT << Init->getSourceRange() 8403 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8404 VDecl->setConstexpr(true); 8405 8406 } else { 8407 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8408 << DclT << Init->getSourceRange(); 8409 VDecl->setInvalidDecl(); 8410 } 8411 } else if (VDecl->isFileVarDecl()) { 8412 if (VDecl->getStorageClass() == SC_Extern && 8413 (!getLangOpts().CPlusPlus || 8414 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8415 VDecl->isExternC())) && 8416 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8417 Diag(VDecl->getLocation(), diag::warn_extern_init); 8418 8419 // C99 6.7.8p4. All file scoped initializers need to be constant. 8420 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8421 CheckForConstantInitializer(Init, DclT); 8422 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8423 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8424 !Init->isValueDependent() && !VDecl->isConstexpr() && 8425 !Init->isConstantInitializer( 8426 Context, VDecl->getType()->isReferenceType())) { 8427 // GNU C++98 edits for __thread, [basic.start.init]p4: 8428 // An object of thread storage duration shall not require dynamic 8429 // initialization. 8430 // FIXME: Need strict checking here. 8431 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8432 if (getLangOpts().CPlusPlus11) 8433 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8434 } 8435 } 8436 8437 // We will represent direct-initialization similarly to copy-initialization: 8438 // int x(1); -as-> int x = 1; 8439 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8440 // 8441 // Clients that want to distinguish between the two forms, can check for 8442 // direct initializer using VarDecl::getInitStyle(). 8443 // A major benefit is that clients that don't particularly care about which 8444 // exactly form was it (like the CodeGen) can handle both cases without 8445 // special case code. 8446 8447 // C++ 8.5p11: 8448 // The form of initialization (using parentheses or '=') is generally 8449 // insignificant, but does matter when the entity being initialized has a 8450 // class type. 8451 if (CXXDirectInit) { 8452 assert(DirectInit && "Call-style initializer must be direct init."); 8453 VDecl->setInitStyle(VarDecl::CallInit); 8454 } else if (DirectInit) { 8455 // This must be list-initialization. No other way is direct-initialization. 8456 VDecl->setInitStyle(VarDecl::ListInit); 8457 } 8458 8459 CheckCompleteVariableDeclaration(VDecl); 8460 } 8461 8462 /// ActOnInitializerError - Given that there was an error parsing an 8463 /// initializer for the given declaration, try to return to some form 8464 /// of sanity. 8465 void Sema::ActOnInitializerError(Decl *D) { 8466 // Our main concern here is re-establishing invariants like "a 8467 // variable's type is either dependent or complete". 8468 if (!D || D->isInvalidDecl()) return; 8469 8470 VarDecl *VD = dyn_cast<VarDecl>(D); 8471 if (!VD) return; 8472 8473 // Auto types are meaningless if we can't make sense of the initializer. 8474 if (ParsingInitForAutoVars.count(D)) { 8475 D->setInvalidDecl(); 8476 return; 8477 } 8478 8479 QualType Ty = VD->getType(); 8480 if (Ty->isDependentType()) return; 8481 8482 // Require a complete type. 8483 if (RequireCompleteType(VD->getLocation(), 8484 Context.getBaseElementType(Ty), 8485 diag::err_typecheck_decl_incomplete_type)) { 8486 VD->setInvalidDecl(); 8487 return; 8488 } 8489 8490 // Require an abstract type. 8491 if (RequireNonAbstractType(VD->getLocation(), Ty, 8492 diag::err_abstract_type_in_decl, 8493 AbstractVariableType)) { 8494 VD->setInvalidDecl(); 8495 return; 8496 } 8497 8498 // Don't bother complaining about constructors or destructors, 8499 // though. 8500 } 8501 8502 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8503 bool TypeMayContainAuto) { 8504 // If there is no declaration, there was an error parsing it. Just ignore it. 8505 if (RealDecl == 0) 8506 return; 8507 8508 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8509 QualType Type = Var->getType(); 8510 8511 // C++11 [dcl.spec.auto]p3 8512 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8513 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8514 << Var->getDeclName() << Type; 8515 Var->setInvalidDecl(); 8516 return; 8517 } 8518 8519 // C++11 [class.static.data]p3: A static data member can be declared with 8520 // the constexpr specifier; if so, its declaration shall specify 8521 // a brace-or-equal-initializer. 8522 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8523 // the definition of a variable [...] or the declaration of a static data 8524 // member. 8525 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8526 if (Var->isStaticDataMember()) 8527 Diag(Var->getLocation(), 8528 diag::err_constexpr_static_mem_var_requires_init) 8529 << Var->getDeclName(); 8530 else 8531 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8532 Var->setInvalidDecl(); 8533 return; 8534 } 8535 8536 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8537 // be initialized. 8538 if (!Var->isInvalidDecl() && 8539 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8540 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8541 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 8542 Var->setInvalidDecl(); 8543 return; 8544 } 8545 8546 switch (Var->isThisDeclarationADefinition()) { 8547 case VarDecl::Definition: 8548 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8549 break; 8550 8551 // We have an out-of-line definition of a static data member 8552 // that has an in-class initializer, so we type-check this like 8553 // a declaration. 8554 // 8555 // Fall through 8556 8557 case VarDecl::DeclarationOnly: 8558 // It's only a declaration. 8559 8560 // Block scope. C99 6.7p7: If an identifier for an object is 8561 // declared with no linkage (C99 6.2.2p6), the type for the 8562 // object shall be complete. 8563 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8564 !Var->hasLinkage() && !Var->isInvalidDecl() && 8565 RequireCompleteType(Var->getLocation(), Type, 8566 diag::err_typecheck_decl_incomplete_type)) 8567 Var->setInvalidDecl(); 8568 8569 // Make sure that the type is not abstract. 8570 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8571 RequireNonAbstractType(Var->getLocation(), Type, 8572 diag::err_abstract_type_in_decl, 8573 AbstractVariableType)) 8574 Var->setInvalidDecl(); 8575 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8576 Var->getStorageClass() == SC_PrivateExtern) { 8577 Diag(Var->getLocation(), diag::warn_private_extern); 8578 Diag(Var->getLocation(), diag::note_private_extern); 8579 } 8580 8581 return; 8582 8583 case VarDecl::TentativeDefinition: 8584 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8585 // object that has file scope without an initializer, and without a 8586 // storage-class specifier or with the storage-class specifier "static", 8587 // constitutes a tentative definition. Note: A tentative definition with 8588 // external linkage is valid (C99 6.2.2p5). 8589 if (!Var->isInvalidDecl()) { 8590 if (const IncompleteArrayType *ArrayT 8591 = Context.getAsIncompleteArrayType(Type)) { 8592 if (RequireCompleteType(Var->getLocation(), 8593 ArrayT->getElementType(), 8594 diag::err_illegal_decl_array_incomplete_type)) 8595 Var->setInvalidDecl(); 8596 } else if (Var->getStorageClass() == SC_Static) { 8597 // C99 6.9.2p3: If the declaration of an identifier for an object is 8598 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8599 // declared type shall not be an incomplete type. 8600 // NOTE: code such as the following 8601 // static struct s; 8602 // struct s { int a; }; 8603 // is accepted by gcc. Hence here we issue a warning instead of 8604 // an error and we do not invalidate the static declaration. 8605 // NOTE: to avoid multiple warnings, only check the first declaration. 8606 if (Var->isFirstDecl()) 8607 RequireCompleteType(Var->getLocation(), Type, 8608 diag::ext_typecheck_decl_incomplete_type); 8609 } 8610 } 8611 8612 // Record the tentative definition; we're done. 8613 if (!Var->isInvalidDecl()) 8614 TentativeDefinitions.push_back(Var); 8615 return; 8616 } 8617 8618 // Provide a specific diagnostic for uninitialized variable 8619 // definitions with incomplete array type. 8620 if (Type->isIncompleteArrayType()) { 8621 Diag(Var->getLocation(), 8622 diag::err_typecheck_incomplete_array_needs_initializer); 8623 Var->setInvalidDecl(); 8624 return; 8625 } 8626 8627 // Provide a specific diagnostic for uninitialized variable 8628 // definitions with reference type. 8629 if (Type->isReferenceType()) { 8630 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8631 << Var->getDeclName() 8632 << SourceRange(Var->getLocation(), Var->getLocation()); 8633 Var->setInvalidDecl(); 8634 return; 8635 } 8636 8637 // Do not attempt to type-check the default initializer for a 8638 // variable with dependent type. 8639 if (Type->isDependentType()) 8640 return; 8641 8642 if (Var->isInvalidDecl()) 8643 return; 8644 8645 if (RequireCompleteType(Var->getLocation(), 8646 Context.getBaseElementType(Type), 8647 diag::err_typecheck_decl_incomplete_type)) { 8648 Var->setInvalidDecl(); 8649 return; 8650 } 8651 8652 // The variable can not have an abstract class type. 8653 if (RequireNonAbstractType(Var->getLocation(), Type, 8654 diag::err_abstract_type_in_decl, 8655 AbstractVariableType)) { 8656 Var->setInvalidDecl(); 8657 return; 8658 } 8659 8660 // Check for jumps past the implicit initializer. C++0x 8661 // clarifies that this applies to a "variable with automatic 8662 // storage duration", not a "local variable". 8663 // C++11 [stmt.dcl]p3 8664 // A program that jumps from a point where a variable with automatic 8665 // storage duration is not in scope to a point where it is in scope is 8666 // ill-formed unless the variable has scalar type, class type with a 8667 // trivial default constructor and a trivial destructor, a cv-qualified 8668 // version of one of these types, or an array of one of the preceding 8669 // types and is declared without an initializer. 8670 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8671 if (const RecordType *Record 8672 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8673 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8674 // Mark the function for further checking even if the looser rules of 8675 // C++11 do not require such checks, so that we can diagnose 8676 // incompatibilities with C++98. 8677 if (!CXXRecord->isPOD()) 8678 getCurFunction()->setHasBranchProtectedScope(); 8679 } 8680 } 8681 8682 // C++03 [dcl.init]p9: 8683 // If no initializer is specified for an object, and the 8684 // object is of (possibly cv-qualified) non-POD class type (or 8685 // array thereof), the object shall be default-initialized; if 8686 // the object is of const-qualified type, the underlying class 8687 // type shall have a user-declared default 8688 // constructor. Otherwise, if no initializer is specified for 8689 // a non- static object, the object and its subobjects, if 8690 // any, have an indeterminate initial value); if the object 8691 // or any of its subobjects are of const-qualified type, the 8692 // program is ill-formed. 8693 // C++0x [dcl.init]p11: 8694 // If no initializer is specified for an object, the object is 8695 // default-initialized; [...]. 8696 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8697 InitializationKind Kind 8698 = InitializationKind::CreateDefault(Var->getLocation()); 8699 8700 InitializationSequence InitSeq(*this, Entity, Kind, None); 8701 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8702 if (Init.isInvalid()) 8703 Var->setInvalidDecl(); 8704 else if (Init.get()) { 8705 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8706 // This is important for template substitution. 8707 Var->setInitStyle(VarDecl::CallInit); 8708 } 8709 8710 CheckCompleteVariableDeclaration(Var); 8711 } 8712 } 8713 8714 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8715 VarDecl *VD = dyn_cast<VarDecl>(D); 8716 if (!VD) { 8717 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8718 D->setInvalidDecl(); 8719 return; 8720 } 8721 8722 VD->setCXXForRangeDecl(true); 8723 8724 // for-range-declaration cannot be given a storage class specifier. 8725 int Error = -1; 8726 switch (VD->getStorageClass()) { 8727 case SC_None: 8728 break; 8729 case SC_Extern: 8730 Error = 0; 8731 break; 8732 case SC_Static: 8733 Error = 1; 8734 break; 8735 case SC_PrivateExtern: 8736 Error = 2; 8737 break; 8738 case SC_Auto: 8739 Error = 3; 8740 break; 8741 case SC_Register: 8742 Error = 4; 8743 break; 8744 case SC_OpenCLWorkGroupLocal: 8745 llvm_unreachable("Unexpected storage class"); 8746 } 8747 if (VD->isConstexpr()) 8748 Error = 5; 8749 if (Error != -1) { 8750 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8751 << VD->getDeclName() << Error; 8752 D->setInvalidDecl(); 8753 } 8754 } 8755 8756 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8757 if (var->isInvalidDecl()) return; 8758 8759 // In ARC, don't allow jumps past the implicit initialization of a 8760 // local retaining variable. 8761 if (getLangOpts().ObjCAutoRefCount && 8762 var->hasLocalStorage()) { 8763 switch (var->getType().getObjCLifetime()) { 8764 case Qualifiers::OCL_None: 8765 case Qualifiers::OCL_ExplicitNone: 8766 case Qualifiers::OCL_Autoreleasing: 8767 break; 8768 8769 case Qualifiers::OCL_Weak: 8770 case Qualifiers::OCL_Strong: 8771 getCurFunction()->setHasBranchProtectedScope(); 8772 break; 8773 } 8774 } 8775 8776 // Warn about externally-visible variables being defined without a 8777 // prior declaration. We only want to do this for global 8778 // declarations, but we also specifically need to avoid doing it for 8779 // class members because the linkage of an anonymous class can 8780 // change if it's later given a typedef name. 8781 if (var->isThisDeclarationADefinition() && 8782 var->getDeclContext()->getRedeclContext()->isFileContext() && 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 checkAttributesAfterMerging(*this, *VD); 8896 8897 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 8898 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 8899 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 8900 VD->dropAttr<UsedAttr>(); 8901 } 8902 } 8903 8904 if (!VD->isInvalidDecl() && 8905 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 8906 if (const VarDecl *Def = VD->getDefinition()) { 8907 if (Def->hasAttr<AliasAttr>()) { 8908 Diag(VD->getLocation(), diag::err_tentative_after_alias) 8909 << VD->getDeclName(); 8910 Diag(Def->getLocation(), diag::note_previous_definition); 8911 VD->setInvalidDecl(); 8912 } 8913 } 8914 } 8915 8916 const DeclContext *DC = VD->getDeclContext(); 8917 // If there's a #pragma GCC visibility in scope, and this isn't a class 8918 // member, set the visibility of this variable. 8919 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 8920 AddPushedVisibilityAttribute(VD); 8921 8922 if (VD->isFileVarDecl()) 8923 MarkUnusedFileScopedDecl(VD); 8924 8925 // Now we have parsed the initializer and can update the table of magic 8926 // tag values. 8927 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8928 !VD->getType()->isIntegralOrEnumerationType()) 8929 return; 8930 8931 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8932 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8933 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8934 I != E; ++I) { 8935 const Expr *MagicValueExpr = VD->getInit(); 8936 if (!MagicValueExpr) { 8937 continue; 8938 } 8939 llvm::APSInt MagicValueInt; 8940 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8941 Diag(I->getRange().getBegin(), 8942 diag::err_type_tag_for_datatype_not_ice) 8943 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8944 continue; 8945 } 8946 if (MagicValueInt.getActiveBits() > 64) { 8947 Diag(I->getRange().getBegin(), 8948 diag::err_type_tag_for_datatype_too_large) 8949 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8950 continue; 8951 } 8952 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8953 RegisterTypeTagForDatatype(I->getArgumentKind(), 8954 MagicValue, 8955 I->getMatchingCType(), 8956 I->getLayoutCompatible(), 8957 I->getMustBeNull()); 8958 } 8959 } 8960 8961 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8962 ArrayRef<Decl *> Group) { 8963 SmallVector<Decl*, 8> Decls; 8964 8965 if (DS.isTypeSpecOwned()) 8966 Decls.push_back(DS.getRepAsDecl()); 8967 8968 DeclaratorDecl *FirstDeclaratorInGroup = 0; 8969 for (unsigned i = 0, e = Group.size(); i != e; ++i) 8970 if (Decl *D = Group[i]) { 8971 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 8972 if (!FirstDeclaratorInGroup) 8973 FirstDeclaratorInGroup = DD; 8974 Decls.push_back(D); 8975 } 8976 8977 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 8978 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 8979 HandleTagNumbering(*this, Tag); 8980 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 8981 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 8982 } 8983 } 8984 8985 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 8986 } 8987 8988 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 8989 /// group, performing any necessary semantic checking. 8990 Sema::DeclGroupPtrTy 8991 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 8992 bool TypeMayContainAuto) { 8993 // C++0x [dcl.spec.auto]p7: 8994 // If the type deduced for the template parameter U is not the same in each 8995 // deduction, the program is ill-formed. 8996 // FIXME: When initializer-list support is added, a distinction is needed 8997 // between the deduced type U and the deduced type which 'auto' stands for. 8998 // auto a = 0, b = { 1, 2, 3 }; 8999 // is legal because the deduced type U is 'int' in both cases. 9000 if (TypeMayContainAuto && Group.size() > 1) { 9001 QualType Deduced; 9002 CanQualType DeducedCanon; 9003 VarDecl *DeducedDecl = 0; 9004 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9005 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9006 AutoType *AT = D->getType()->getContainedAutoType(); 9007 // Don't reissue diagnostics when instantiating a template. 9008 if (AT && D->isInvalidDecl()) 9009 break; 9010 QualType U = AT ? AT->getDeducedType() : QualType(); 9011 if (!U.isNull()) { 9012 CanQualType UCanon = Context.getCanonicalType(U); 9013 if (Deduced.isNull()) { 9014 Deduced = U; 9015 DeducedCanon = UCanon; 9016 DeducedDecl = D; 9017 } else if (DeducedCanon != UCanon) { 9018 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9019 diag::err_auto_different_deductions) 9020 << (AT->isDecltypeAuto() ? 1 : 0) 9021 << Deduced << DeducedDecl->getDeclName() 9022 << U << D->getDeclName() 9023 << DeducedDecl->getInit()->getSourceRange() 9024 << D->getInit()->getSourceRange(); 9025 D->setInvalidDecl(); 9026 break; 9027 } 9028 } 9029 } 9030 } 9031 } 9032 9033 ActOnDocumentableDecls(Group); 9034 9035 return DeclGroupPtrTy::make( 9036 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9037 } 9038 9039 void Sema::ActOnDocumentableDecl(Decl *D) { 9040 ActOnDocumentableDecls(D); 9041 } 9042 9043 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9044 // Don't parse the comment if Doxygen diagnostics are ignored. 9045 if (Group.empty() || !Group[0]) 9046 return; 9047 9048 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9049 Group[0]->getLocation()) 9050 == DiagnosticsEngine::Ignored) 9051 return; 9052 9053 if (Group.size() >= 2) { 9054 // This is a decl group. Normally it will contain only declarations 9055 // produced from declarator list. But in case we have any definitions or 9056 // additional declaration references: 9057 // 'typedef struct S {} S;' 9058 // 'typedef struct S *S;' 9059 // 'struct S *pS;' 9060 // FinalizeDeclaratorGroup adds these as separate declarations. 9061 Decl *MaybeTagDecl = Group[0]; 9062 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9063 Group = Group.slice(1); 9064 } 9065 } 9066 9067 // See if there are any new comments that are not attached to a decl. 9068 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9069 if (!Comments.empty() && 9070 !Comments.back()->isAttached()) { 9071 // There is at least one comment that not attached to a decl. 9072 // Maybe it should be attached to one of these decls? 9073 // 9074 // Note that this way we pick up not only comments that precede the 9075 // declaration, but also comments that *follow* the declaration -- thanks to 9076 // the lookahead in the lexer: we've consumed the semicolon and looked 9077 // ahead through comments. 9078 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9079 Context.getCommentForDecl(Group[i], &PP); 9080 } 9081 } 9082 9083 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9084 /// to introduce parameters into function prototype scope. 9085 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9086 const DeclSpec &DS = D.getDeclSpec(); 9087 9088 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9089 9090 // C++03 [dcl.stc]p2 also permits 'auto'. 9091 VarDecl::StorageClass StorageClass = SC_None; 9092 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9093 StorageClass = SC_Register; 9094 } else if (getLangOpts().CPlusPlus && 9095 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9096 StorageClass = SC_Auto; 9097 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9098 Diag(DS.getStorageClassSpecLoc(), 9099 diag::err_invalid_storage_class_in_func_decl); 9100 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9101 } 9102 9103 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9104 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9105 << DeclSpec::getSpecifierName(TSCS); 9106 if (DS.isConstexprSpecified()) 9107 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9108 << 0; 9109 9110 DiagnoseFunctionSpecifiers(DS); 9111 9112 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9113 QualType parmDeclType = TInfo->getType(); 9114 9115 if (getLangOpts().CPlusPlus) { 9116 // Check that there are no default arguments inside the type of this 9117 // parameter. 9118 CheckExtraCXXDefaultArguments(D); 9119 9120 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9121 if (D.getCXXScopeSpec().isSet()) { 9122 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9123 << D.getCXXScopeSpec().getRange(); 9124 D.getCXXScopeSpec().clear(); 9125 } 9126 } 9127 9128 // Ensure we have a valid name 9129 IdentifierInfo *II = 0; 9130 if (D.hasName()) { 9131 II = D.getIdentifier(); 9132 if (!II) { 9133 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9134 << GetNameForDeclarator(D).getName(); 9135 D.setInvalidType(true); 9136 } 9137 } 9138 9139 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9140 if (II) { 9141 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9142 ForRedeclaration); 9143 LookupName(R, S); 9144 if (R.isSingleResult()) { 9145 NamedDecl *PrevDecl = R.getFoundDecl(); 9146 if (PrevDecl->isTemplateParameter()) { 9147 // Maybe we will complain about the shadowed template parameter. 9148 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9149 // Just pretend that we didn't see the previous declaration. 9150 PrevDecl = 0; 9151 } else if (S->isDeclScope(PrevDecl)) { 9152 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9153 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9154 9155 // Recover by removing the name 9156 II = 0; 9157 D.SetIdentifier(0, D.getIdentifierLoc()); 9158 D.setInvalidType(true); 9159 } 9160 } 9161 } 9162 9163 // Temporarily put parameter variables in the translation unit, not 9164 // the enclosing context. This prevents them from accidentally 9165 // looking like class members in C++. 9166 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9167 D.getLocStart(), 9168 D.getIdentifierLoc(), II, 9169 parmDeclType, TInfo, 9170 StorageClass); 9171 9172 if (D.isInvalidType()) 9173 New->setInvalidDecl(); 9174 9175 assert(S->isFunctionPrototypeScope()); 9176 assert(S->getFunctionPrototypeDepth() >= 1); 9177 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9178 S->getNextFunctionPrototypeIndex()); 9179 9180 // Add the parameter declaration into this scope. 9181 S->AddDecl(New); 9182 if (II) 9183 IdResolver.AddDecl(New); 9184 9185 ProcessDeclAttributes(S, New, D); 9186 9187 if (D.getDeclSpec().isModulePrivateSpecified()) 9188 Diag(New->getLocation(), diag::err_module_private_local) 9189 << 1 << New->getDeclName() 9190 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9191 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9192 9193 if (New->hasAttr<BlocksAttr>()) { 9194 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9195 } 9196 return New; 9197 } 9198 9199 /// \brief Synthesizes a variable for a parameter arising from a 9200 /// typedef. 9201 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9202 SourceLocation Loc, 9203 QualType T) { 9204 /* FIXME: setting StartLoc == Loc. 9205 Would it be worth to modify callers so as to provide proper source 9206 location for the unnamed parameters, embedding the parameter's type? */ 9207 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9208 T, Context.getTrivialTypeSourceInfo(T, Loc), 9209 SC_None, 0); 9210 Param->setImplicit(); 9211 return Param; 9212 } 9213 9214 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9215 ParmVarDecl * const *ParamEnd) { 9216 // Don't diagnose unused-parameter errors in template instantiations; we 9217 // will already have done so in the template itself. 9218 if (!ActiveTemplateInstantiations.empty()) 9219 return; 9220 9221 for (; Param != ParamEnd; ++Param) { 9222 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9223 !(*Param)->hasAttr<UnusedAttr>()) { 9224 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9225 << (*Param)->getDeclName(); 9226 } 9227 } 9228 } 9229 9230 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9231 ParmVarDecl * const *ParamEnd, 9232 QualType ReturnTy, 9233 NamedDecl *D) { 9234 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9235 return; 9236 9237 // Warn if the return value is pass-by-value and larger than the specified 9238 // threshold. 9239 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9240 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9241 if (Size > LangOpts.NumLargeByValueCopy) 9242 Diag(D->getLocation(), diag::warn_return_value_size) 9243 << D->getDeclName() << Size; 9244 } 9245 9246 // Warn if any parameter is pass-by-value and larger than the specified 9247 // threshold. 9248 for (; Param != ParamEnd; ++Param) { 9249 QualType T = (*Param)->getType(); 9250 if (T->isDependentType() || !T.isPODType(Context)) 9251 continue; 9252 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9253 if (Size > LangOpts.NumLargeByValueCopy) 9254 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9255 << (*Param)->getDeclName() << Size; 9256 } 9257 } 9258 9259 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9260 SourceLocation NameLoc, IdentifierInfo *Name, 9261 QualType T, TypeSourceInfo *TSInfo, 9262 VarDecl::StorageClass StorageClass) { 9263 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9264 if (getLangOpts().ObjCAutoRefCount && 9265 T.getObjCLifetime() == Qualifiers::OCL_None && 9266 T->isObjCLifetimeType()) { 9267 9268 Qualifiers::ObjCLifetime lifetime; 9269 9270 // Special cases for arrays: 9271 // - if it's const, use __unsafe_unretained 9272 // - otherwise, it's an error 9273 if (T->isArrayType()) { 9274 if (!T.isConstQualified()) { 9275 DelayedDiagnostics.add( 9276 sema::DelayedDiagnostic::makeForbiddenType( 9277 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9278 } 9279 lifetime = Qualifiers::OCL_ExplicitNone; 9280 } else { 9281 lifetime = T->getObjCARCImplicitLifetime(); 9282 } 9283 T = Context.getLifetimeQualifiedType(T, lifetime); 9284 } 9285 9286 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9287 Context.getAdjustedParameterType(T), 9288 TSInfo, 9289 StorageClass, 0); 9290 9291 // Parameters can not be abstract class types. 9292 // For record types, this is done by the AbstractClassUsageDiagnoser once 9293 // the class has been completely parsed. 9294 if (!CurContext->isRecord() && 9295 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9296 AbstractParamType)) 9297 New->setInvalidDecl(); 9298 9299 // Parameter declarators cannot be interface types. All ObjC objects are 9300 // passed by reference. 9301 if (T->isObjCObjectType()) { 9302 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9303 Diag(NameLoc, 9304 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9305 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9306 T = Context.getObjCObjectPointerType(T); 9307 New->setType(T); 9308 } 9309 9310 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9311 // duration shall not be qualified by an address-space qualifier." 9312 // Since all parameters have automatic store duration, they can not have 9313 // an address space. 9314 if (T.getAddressSpace() != 0) { 9315 Diag(NameLoc, diag::err_arg_with_address_space); 9316 New->setInvalidDecl(); 9317 } 9318 9319 return New; 9320 } 9321 9322 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9323 SourceLocation LocAfterDecls) { 9324 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9325 9326 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9327 // for a K&R function. 9328 if (!FTI.hasPrototype) { 9329 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 9330 --i; 9331 if (FTI.ArgInfo[i].Param == 0) { 9332 SmallString<256> Code; 9333 llvm::raw_svector_ostream(Code) << " int " 9334 << FTI.ArgInfo[i].Ident->getName() 9335 << ";\n"; 9336 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 9337 << FTI.ArgInfo[i].Ident 9338 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9339 9340 // Implicitly declare the argument as type 'int' for lack of a better 9341 // type. 9342 AttributeFactory attrs; 9343 DeclSpec DS(attrs); 9344 const char* PrevSpec; // unused 9345 unsigned DiagID; // unused 9346 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 9347 PrevSpec, DiagID, Context.getPrintingPolicy()); 9348 // Use the identifier location for the type source range. 9349 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 9350 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 9351 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9352 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 9353 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 9354 } 9355 } 9356 } 9357 } 9358 9359 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9360 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9361 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9362 Scope *ParentScope = FnBodyScope->getParent(); 9363 9364 D.setFunctionDefinitionKind(FDK_Definition); 9365 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9366 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9367 } 9368 9369 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9370 const FunctionDecl*& PossibleZeroParamPrototype) { 9371 // Don't warn about invalid declarations. 9372 if (FD->isInvalidDecl()) 9373 return false; 9374 9375 // Or declarations that aren't global. 9376 if (!FD->isGlobal()) 9377 return false; 9378 9379 // Don't warn about C++ member functions. 9380 if (isa<CXXMethodDecl>(FD)) 9381 return false; 9382 9383 // Don't warn about 'main'. 9384 if (FD->isMain()) 9385 return false; 9386 9387 // Don't warn about inline functions. 9388 if (FD->isInlined()) 9389 return false; 9390 9391 // Don't warn about function templates. 9392 if (FD->getDescribedFunctionTemplate()) 9393 return false; 9394 9395 // Don't warn about function template specializations. 9396 if (FD->isFunctionTemplateSpecialization()) 9397 return false; 9398 9399 // Don't warn for OpenCL kernels. 9400 if (FD->hasAttr<OpenCLKernelAttr>()) 9401 return false; 9402 9403 bool MissingPrototype = true; 9404 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9405 Prev; Prev = Prev->getPreviousDecl()) { 9406 // Ignore any declarations that occur in function or method 9407 // scope, because they aren't visible from the header. 9408 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9409 continue; 9410 9411 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9412 if (FD->getNumParams() == 0) 9413 PossibleZeroParamPrototype = Prev; 9414 break; 9415 } 9416 9417 return MissingPrototype; 9418 } 9419 9420 void 9421 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9422 const FunctionDecl *EffectiveDefinition) { 9423 // Don't complain if we're in GNU89 mode and the previous definition 9424 // was an extern inline function. 9425 const FunctionDecl *Definition = EffectiveDefinition; 9426 if (!Definition) 9427 if (!FD->isDefined(Definition)) 9428 return; 9429 9430 if (canRedefineFunction(Definition, getLangOpts())) 9431 return; 9432 9433 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9434 Definition->getStorageClass() == SC_Extern) 9435 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9436 << FD->getDeclName() << getLangOpts().CPlusPlus; 9437 else 9438 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9439 9440 Diag(Definition->getLocation(), diag::note_previous_definition); 9441 FD->setInvalidDecl(); 9442 } 9443 9444 9445 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9446 Sema &S) { 9447 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9448 9449 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9450 LSI->CallOperator = CallOperator; 9451 LSI->Lambda = LambdaClass; 9452 LSI->ReturnType = CallOperator->getReturnType(); 9453 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9454 9455 if (LCD == LCD_None) 9456 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9457 else if (LCD == LCD_ByCopy) 9458 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9459 else if (LCD == LCD_ByRef) 9460 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9461 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9462 9463 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9464 LSI->Mutable = !CallOperator->isConst(); 9465 9466 // Add the captures to the LSI so they can be noted as already 9467 // captured within tryCaptureVar. 9468 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(), 9469 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) { 9470 if (C->capturesVariable()) { 9471 VarDecl *VD = C->getCapturedVar(); 9472 if (VD->isInitCapture()) 9473 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9474 QualType CaptureType = VD->getType(); 9475 const bool ByRef = C->getCaptureKind() == LCK_ByRef; 9476 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9477 /*RefersToEnclosingLocal*/true, C->getLocation(), 9478 /*EllipsisLoc*/C->isPackExpansion() 9479 ? C->getEllipsisLoc() : SourceLocation(), 9480 CaptureType, /*Expr*/ 0); 9481 9482 } else if (C->capturesThis()) { 9483 LSI->addThisCapture(/*Nested*/ false, C->getLocation(), 9484 S.getCurrentThisType(), /*Expr*/ 0); 9485 } 9486 } 9487 } 9488 9489 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9490 // Clear the last template instantiation error context. 9491 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9492 9493 if (!D) 9494 return D; 9495 FunctionDecl *FD = 0; 9496 9497 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9498 FD = FunTmpl->getTemplatedDecl(); 9499 else 9500 FD = cast<FunctionDecl>(D); 9501 // If we are instantiating a generic lambda call operator, push 9502 // a LambdaScopeInfo onto the function stack. But use the information 9503 // that's already been calculated (ActOnLambdaExpr) to prime the current 9504 // LambdaScopeInfo. 9505 // When the template operator is being specialized, the LambdaScopeInfo, 9506 // has to be properly restored so that tryCaptureVariable doesn't try 9507 // and capture any new variables. In addition when calculating potential 9508 // captures during transformation of nested lambdas, it is necessary to 9509 // have the LSI properly restored. 9510 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9511 assert(ActiveTemplateInstantiations.size() && 9512 "There should be an active template instantiation on the stack " 9513 "when instantiating a generic lambda!"); 9514 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9515 } 9516 else 9517 // Enter a new function scope 9518 PushFunctionScope(); 9519 9520 // See if this is a redefinition. 9521 if (!FD->isLateTemplateParsed()) 9522 CheckForFunctionRedefinition(FD); 9523 9524 // Builtin functions cannot be defined. 9525 if (unsigned BuiltinID = FD->getBuiltinID()) { 9526 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9527 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9528 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9529 FD->setInvalidDecl(); 9530 } 9531 } 9532 9533 // The return type of a function definition must be complete 9534 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9535 QualType ResultType = FD->getReturnType(); 9536 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9537 !FD->isInvalidDecl() && 9538 RequireCompleteType(FD->getLocation(), ResultType, 9539 diag::err_func_def_incomplete_result)) 9540 FD->setInvalidDecl(); 9541 9542 // GNU warning -Wmissing-prototypes: 9543 // Warn if a global function is defined without a previous 9544 // prototype declaration. This warning is issued even if the 9545 // definition itself provides a prototype. The aim is to detect 9546 // global functions that fail to be declared in header files. 9547 const FunctionDecl *PossibleZeroParamPrototype = 0; 9548 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9549 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9550 9551 if (PossibleZeroParamPrototype) { 9552 // We found a declaration that is not a prototype, 9553 // but that could be a zero-parameter prototype 9554 if (TypeSourceInfo *TI = 9555 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9556 TypeLoc TL = TI->getTypeLoc(); 9557 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9558 Diag(PossibleZeroParamPrototype->getLocation(), 9559 diag::note_declaration_not_a_prototype) 9560 << PossibleZeroParamPrototype 9561 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9562 } 9563 } 9564 } 9565 9566 if (FnBodyScope) 9567 PushDeclContext(FnBodyScope, FD); 9568 9569 // Check the validity of our function parameters 9570 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9571 /*CheckParameterNames=*/true); 9572 9573 // Introduce our parameters into the function scope 9574 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 9575 ParmVarDecl *Param = FD->getParamDecl(p); 9576 Param->setOwningFunction(FD); 9577 9578 // If this has an identifier, add it to the scope stack. 9579 if (Param->getIdentifier() && FnBodyScope) { 9580 CheckShadow(FnBodyScope, Param); 9581 9582 PushOnScopeChains(Param, FnBodyScope); 9583 } 9584 } 9585 9586 // If we had any tags defined in the function prototype, 9587 // introduce them into the function scope. 9588 if (FnBodyScope) { 9589 for (ArrayRef<NamedDecl *>::iterator 9590 I = FD->getDeclsInPrototypeScope().begin(), 9591 E = FD->getDeclsInPrototypeScope().end(); 9592 I != E; ++I) { 9593 NamedDecl *D = *I; 9594 9595 // Some of these decls (like enums) may have been pinned to the translation unit 9596 // for lack of a real context earlier. If so, remove from the translation unit 9597 // and reattach to the current context. 9598 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9599 // Is the decl actually in the context? 9600 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 9601 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 9602 if (*DI == D) { 9603 Context.getTranslationUnitDecl()->removeDecl(D); 9604 break; 9605 } 9606 } 9607 // Either way, reassign the lexical decl context to our FunctionDecl. 9608 D->setLexicalDeclContext(CurContext); 9609 } 9610 9611 // If the decl has a non-null name, make accessible in the current scope. 9612 if (!D->getName().empty()) 9613 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9614 9615 // Similarly, dive into enums and fish their constants out, making them 9616 // accessible in this scope. 9617 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 9618 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 9619 EE = ED->enumerator_end(); EI != EE; ++EI) 9620 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 9621 } 9622 } 9623 } 9624 9625 // Ensure that the function's exception specification is instantiated. 9626 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9627 ResolveExceptionSpec(D->getLocation(), FPT); 9628 9629 // Checking attributes of current function definition 9630 // dllimport attribute. 9631 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9632 if (DA && (!FD->hasAttr<DLLExportAttr>())) { 9633 // dllimport attribute cannot be directly applied to definition. 9634 // Microsoft accepts dllimport for functions defined within class scope. 9635 if (!DA->isInherited() && 9636 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9637 Diag(FD->getLocation(), 9638 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9639 << DA; 9640 FD->setInvalidDecl(); 9641 return D; 9642 } 9643 9644 // Visual C++ appears to not think this is an issue, so only issue 9645 // a warning when Microsoft extensions are disabled. 9646 if (!LangOpts.MicrosoftExt) { 9647 // If a symbol previously declared dllimport is later defined, the 9648 // attribute is ignored in subsequent references, and a warning is 9649 // emitted. 9650 Diag(FD->getLocation(), 9651 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 9652 << FD << DA; 9653 } 9654 } 9655 // We want to attach documentation to original Decl (which might be 9656 // a function template). 9657 ActOnDocumentableDecl(D); 9658 return D; 9659 } 9660 9661 /// \brief Given the set of return statements within a function body, 9662 /// compute the variables that are subject to the named return value 9663 /// optimization. 9664 /// 9665 /// Each of the variables that is subject to the named return value 9666 /// optimization will be marked as NRVO variables in the AST, and any 9667 /// return statement that has a marked NRVO variable as its NRVO candidate can 9668 /// use the named return value optimization. 9669 /// 9670 /// This function applies a very simplistic algorithm for NRVO: if every return 9671 /// statement in the function has the same NRVO candidate, that candidate is 9672 /// the NRVO variable. 9673 /// 9674 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9675 /// statements and the lifetimes of the NRVO candidates. We should be able to 9676 /// find a maximal set of NRVO variables. 9677 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9678 ReturnStmt **Returns = Scope->Returns.data(); 9679 9680 const VarDecl *NRVOCandidate = 0; 9681 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9682 if (!Returns[I]->getNRVOCandidate()) 9683 return; 9684 9685 if (!NRVOCandidate) 9686 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9687 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9688 return; 9689 } 9690 9691 if (NRVOCandidate) 9692 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9693 } 9694 9695 bool Sema::canSkipFunctionBody(Decl *D) { 9696 // We cannot skip the body of a function (or function template) which is 9697 // constexpr, since we may need to evaluate its body in order to parse the 9698 // rest of the file. 9699 // We cannot skip the body of a function with an undeduced return type, 9700 // because any callers of that function need to know the type. 9701 if (const FunctionDecl *FD = D->getAsFunction()) 9702 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9703 return false; 9704 return Consumer.shouldSkipFunctionBody(D); 9705 } 9706 9707 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9708 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9709 FD->setHasSkippedBody(); 9710 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9711 MD->setHasSkippedBody(); 9712 return ActOnFinishFunctionBody(Decl, 0); 9713 } 9714 9715 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9716 return ActOnFinishFunctionBody(D, BodyArg, false); 9717 } 9718 9719 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9720 bool IsInstantiation) { 9721 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0; 9722 9723 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9724 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9725 9726 if (FD) { 9727 FD->setBody(Body); 9728 9729 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9730 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 9731 // If the function has a deduced result type but contains no 'return' 9732 // statements, the result type as written must be exactly 'auto', and 9733 // the deduced result type is 'void'. 9734 if (!FD->getReturnType()->getAs<AutoType>()) { 9735 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9736 << FD->getReturnType(); 9737 FD->setInvalidDecl(); 9738 } else { 9739 // Substitute 'void' for the 'auto' in the type. 9740 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9741 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 9742 Context.adjustDeducedFunctionResultType( 9743 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9744 } 9745 } 9746 9747 // The only way to be included in UndefinedButUsed is if there is an 9748 // ODR use before the definition. Avoid the expensive map lookup if this 9749 // is the first declaration. 9750 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9751 if (!FD->isExternallyVisible()) 9752 UndefinedButUsed.erase(FD); 9753 else if (FD->isInlined() && 9754 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9755 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9756 UndefinedButUsed.erase(FD); 9757 } 9758 9759 // If the function implicitly returns zero (like 'main') or is naked, 9760 // don't complain about missing return statements. 9761 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9762 WP.disableCheckFallThrough(); 9763 9764 // MSVC permits the use of pure specifier (=0) on function definition, 9765 // defined at class scope, warn about this non-standard construct. 9766 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9767 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9768 9769 if (!FD->isInvalidDecl()) { 9770 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9771 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9772 FD->getReturnType(), FD); 9773 9774 // If this is a constructor, we need a vtable. 9775 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9776 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9777 9778 // Try to apply the named return value optimization. We have to check 9779 // if we can do this here because lambdas keep return statements around 9780 // to deduce an implicit return type. 9781 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 9782 !FD->isDependentContext()) 9783 computeNRVO(Body, getCurFunction()); 9784 } 9785 9786 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9787 "Function parsing confused"); 9788 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9789 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9790 MD->setBody(Body); 9791 if (!MD->isInvalidDecl()) { 9792 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9793 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9794 MD->getReturnType(), MD); 9795 9796 if (Body) 9797 computeNRVO(Body, getCurFunction()); 9798 } 9799 if (getCurFunction()->ObjCShouldCallSuper) { 9800 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9801 << MD->getSelector().getAsString(); 9802 getCurFunction()->ObjCShouldCallSuper = false; 9803 } 9804 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 9805 const ObjCMethodDecl *InitMethod = 0; 9806 bool isDesignated = 9807 MD->isDesignatedInitializerForTheInterface(&InitMethod); 9808 assert(isDesignated && InitMethod); 9809 (void)isDesignated; 9810 Diag(MD->getLocation(), 9811 diag::warn_objc_designated_init_missing_super_call); 9812 Diag(InitMethod->getLocation(), 9813 diag::note_objc_designated_init_marked_here); 9814 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 9815 } 9816 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 9817 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 9818 getCurFunction()->ObjCWarnForNoInitDelegation = false; 9819 } 9820 } else { 9821 return 0; 9822 } 9823 9824 assert(!getCurFunction()->ObjCShouldCallSuper && 9825 "This should only be set for ObjC methods, which should have been " 9826 "handled in the block above."); 9827 9828 // Verify and clean out per-function state. 9829 if (Body) { 9830 // C++ constructors that have function-try-blocks can't have return 9831 // statements in the handlers of that block. (C++ [except.handle]p14) 9832 // Verify this. 9833 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 9834 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 9835 9836 // Verify that gotos and switch cases don't jump into scopes illegally. 9837 if (getCurFunction()->NeedsScopeChecking() && 9838 !dcl->isInvalidDecl() && 9839 !hasAnyUnrecoverableErrorsInThisFunction() && 9840 !PP.isCodeCompletionEnabled()) 9841 DiagnoseInvalidJumps(Body); 9842 9843 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 9844 if (!Destructor->getParent()->isDependentType()) 9845 CheckDestructor(Destructor); 9846 9847 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9848 Destructor->getParent()); 9849 } 9850 9851 // If any errors have occurred, clear out any temporaries that may have 9852 // been leftover. This ensures that these temporaries won't be picked up for 9853 // deletion in some later function. 9854 if (PP.getDiagnostics().hasErrorOccurred() || 9855 PP.getDiagnostics().getSuppressAllDiagnostics()) { 9856 DiscardCleanupsInEvaluationContext(); 9857 } 9858 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 9859 !isa<FunctionTemplateDecl>(dcl)) { 9860 // Since the body is valid, issue any analysis-based warnings that are 9861 // enabled. 9862 ActivePolicy = &WP; 9863 } 9864 9865 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 9866 (!CheckConstexprFunctionDecl(FD) || 9867 !CheckConstexprFunctionBody(FD, Body))) 9868 FD->setInvalidDecl(); 9869 9870 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 9871 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 9872 assert(MaybeODRUseExprs.empty() && 9873 "Leftover expressions for odr-use checking"); 9874 } 9875 9876 if (!IsInstantiation) 9877 PopDeclContext(); 9878 9879 PopFunctionScopeInfo(ActivePolicy, dcl); 9880 // If any errors have occurred, clear out any temporaries that may have 9881 // been leftover. This ensures that these temporaries won't be picked up for 9882 // deletion in some later function. 9883 if (getDiagnostics().hasErrorOccurred()) { 9884 DiscardCleanupsInEvaluationContext(); 9885 } 9886 9887 return dcl; 9888 } 9889 9890 9891 /// When we finish delayed parsing of an attribute, we must attach it to the 9892 /// relevant Decl. 9893 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 9894 ParsedAttributes &Attrs) { 9895 // Always attach attributes to the underlying decl. 9896 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9897 D = TD->getTemplatedDecl(); 9898 ProcessDeclAttributeList(S, D, Attrs.getList()); 9899 9900 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 9901 if (Method->isStatic()) 9902 checkThisInStaticMemberFunctionAttributes(Method); 9903 } 9904 9905 9906 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 9907 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 9908 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 9909 IdentifierInfo &II, Scope *S) { 9910 // Before we produce a declaration for an implicitly defined 9911 // function, see whether there was a locally-scoped declaration of 9912 // this name as a function or variable. If so, use that 9913 // (non-visible) declaration, and complain about it. 9914 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 9915 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 9916 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 9917 return ExternCPrev; 9918 } 9919 9920 // Extension in C99. Legal in C90, but warn about it. 9921 unsigned diag_id; 9922 if (II.getName().startswith("__builtin_")) 9923 diag_id = diag::warn_builtin_unknown; 9924 else if (getLangOpts().C99) 9925 diag_id = diag::ext_implicit_function_decl; 9926 else 9927 diag_id = diag::warn_implicit_function_decl; 9928 Diag(Loc, diag_id) << &II; 9929 9930 // Because typo correction is expensive, only do it if the implicit 9931 // function declaration is going to be treated as an error. 9932 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 9933 TypoCorrection Corrected; 9934 DeclFilterCCC<FunctionDecl> Validator; 9935 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 9936 LookupOrdinaryName, S, 0, Validator))) 9937 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 9938 /*ErrorRecovery*/false); 9939 } 9940 9941 // Set a Declarator for the implicit definition: int foo(); 9942 const char *Dummy; 9943 AttributeFactory attrFactory; 9944 DeclSpec DS(attrFactory); 9945 unsigned DiagID; 9946 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 9947 Context.getPrintingPolicy()); 9948 (void)Error; // Silence warning. 9949 assert(!Error && "Error setting up implicit decl!"); 9950 SourceLocation NoLoc; 9951 Declarator D(DS, Declarator::BlockContext); 9952 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 9953 /*IsAmbiguous=*/false, 9954 /*RParenLoc=*/NoLoc, 9955 /*ArgInfo=*/0, 9956 /*NumArgs=*/0, 9957 /*EllipsisLoc=*/NoLoc, 9958 /*RParenLoc=*/NoLoc, 9959 /*TypeQuals=*/0, 9960 /*RefQualifierIsLvalueRef=*/true, 9961 /*RefQualifierLoc=*/NoLoc, 9962 /*ConstQualifierLoc=*/NoLoc, 9963 /*VolatileQualifierLoc=*/NoLoc, 9964 /*MutableLoc=*/NoLoc, 9965 EST_None, 9966 /*ESpecLoc=*/NoLoc, 9967 /*Exceptions=*/0, 9968 /*ExceptionRanges=*/0, 9969 /*NumExceptions=*/0, 9970 /*NoexceptExpr=*/0, 9971 Loc, Loc, D), 9972 DS.getAttributes(), 9973 SourceLocation()); 9974 D.SetIdentifier(&II, Loc); 9975 9976 // Insert this function into translation-unit scope. 9977 9978 DeclContext *PrevDC = CurContext; 9979 CurContext = Context.getTranslationUnitDecl(); 9980 9981 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 9982 FD->setImplicit(); 9983 9984 CurContext = PrevDC; 9985 9986 AddKnownFunctionAttributes(FD); 9987 9988 return FD; 9989 } 9990 9991 /// \brief Adds any function attributes that we know a priori based on 9992 /// the declaration of this function. 9993 /// 9994 /// These attributes can apply both to implicitly-declared builtins 9995 /// (like __builtin___printf_chk) or to library-declared functions 9996 /// like NSLog or printf. 9997 /// 9998 /// We need to check for duplicate attributes both here and where user-written 9999 /// attributes are applied to declarations. 10000 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10001 if (FD->isInvalidDecl()) 10002 return; 10003 10004 // If this is a built-in function, map its builtin attributes to 10005 // actual attributes. 10006 if (unsigned BuiltinID = FD->getBuiltinID()) { 10007 // Handle printf-formatting attributes. 10008 unsigned FormatIdx; 10009 bool HasVAListArg; 10010 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10011 if (!FD->hasAttr<FormatAttr>()) { 10012 const char *fmt = "printf"; 10013 unsigned int NumParams = FD->getNumParams(); 10014 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10015 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10016 fmt = "NSString"; 10017 FD->addAttr(FormatAttr::CreateImplicit(Context, 10018 &Context.Idents.get(fmt), 10019 FormatIdx+1, 10020 HasVAListArg ? 0 : FormatIdx+2, 10021 FD->getLocation())); 10022 } 10023 } 10024 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10025 HasVAListArg)) { 10026 if (!FD->hasAttr<FormatAttr>()) 10027 FD->addAttr(FormatAttr::CreateImplicit(Context, 10028 &Context.Idents.get("scanf"), 10029 FormatIdx+1, 10030 HasVAListArg ? 0 : FormatIdx+2, 10031 FD->getLocation())); 10032 } 10033 10034 // Mark const if we don't care about errno and that is the only 10035 // thing preventing the function from being const. This allows 10036 // IRgen to use LLVM intrinsics for such functions. 10037 if (!getLangOpts().MathErrno && 10038 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10039 if (!FD->hasAttr<ConstAttr>()) 10040 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10041 } 10042 10043 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10044 !FD->hasAttr<ReturnsTwiceAttr>()) 10045 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10046 FD->getLocation())); 10047 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10048 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10049 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10050 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10051 } 10052 10053 IdentifierInfo *Name = FD->getIdentifier(); 10054 if (!Name) 10055 return; 10056 if ((!getLangOpts().CPlusPlus && 10057 FD->getDeclContext()->isTranslationUnit()) || 10058 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10059 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10060 LinkageSpecDecl::lang_c)) { 10061 // Okay: this could be a libc/libm/Objective-C function we know 10062 // about. 10063 } else 10064 return; 10065 10066 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10067 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10068 // target-specific builtins, perhaps? 10069 if (!FD->hasAttr<FormatAttr>()) 10070 FD->addAttr(FormatAttr::CreateImplicit(Context, 10071 &Context.Idents.get("printf"), 2, 10072 Name->isStr("vasprintf") ? 0 : 3, 10073 FD->getLocation())); 10074 } 10075 10076 if (Name->isStr("__CFStringMakeConstantString")) { 10077 // We already have a __builtin___CFStringMakeConstantString, 10078 // but builds that use -fno-constant-cfstrings don't go through that. 10079 if (!FD->hasAttr<FormatArgAttr>()) 10080 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10081 FD->getLocation())); 10082 } 10083 } 10084 10085 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10086 TypeSourceInfo *TInfo) { 10087 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10088 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10089 10090 if (!TInfo) { 10091 assert(D.isInvalidType() && "no declarator info for valid type"); 10092 TInfo = Context.getTrivialTypeSourceInfo(T); 10093 } 10094 10095 // Scope manipulation handled by caller. 10096 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10097 D.getLocStart(), 10098 D.getIdentifierLoc(), 10099 D.getIdentifier(), 10100 TInfo); 10101 10102 // Bail out immediately if we have an invalid declaration. 10103 if (D.isInvalidType()) { 10104 NewTD->setInvalidDecl(); 10105 return NewTD; 10106 } 10107 10108 if (D.getDeclSpec().isModulePrivateSpecified()) { 10109 if (CurContext->isFunctionOrMethod()) 10110 Diag(NewTD->getLocation(), diag::err_module_private_local) 10111 << 2 << NewTD->getDeclName() 10112 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10113 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10114 else 10115 NewTD->setModulePrivate(); 10116 } 10117 10118 // C++ [dcl.typedef]p8: 10119 // If the typedef declaration defines an unnamed class (or 10120 // enum), the first typedef-name declared by the declaration 10121 // to be that class type (or enum type) is used to denote the 10122 // class type (or enum type) for linkage purposes only. 10123 // We need to check whether the type was declared in the declaration. 10124 switch (D.getDeclSpec().getTypeSpecType()) { 10125 case TST_enum: 10126 case TST_struct: 10127 case TST_interface: 10128 case TST_union: 10129 case TST_class: { 10130 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10131 10132 // Do nothing if the tag is not anonymous or already has an 10133 // associated typedef (from an earlier typedef in this decl group). 10134 if (tagFromDeclSpec->getIdentifier()) break; 10135 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10136 10137 // A well-formed anonymous tag must always be a TUK_Definition. 10138 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10139 10140 // The type must match the tag exactly; no qualifiers allowed. 10141 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10142 break; 10143 10144 // Otherwise, set this is the anon-decl typedef for the tag. 10145 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10146 break; 10147 } 10148 10149 default: 10150 break; 10151 } 10152 10153 return NewTD; 10154 } 10155 10156 10157 /// \brief Check that this is a valid underlying type for an enum declaration. 10158 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10159 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10160 QualType T = TI->getType(); 10161 10162 if (T->isDependentType()) 10163 return false; 10164 10165 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10166 if (BT->isInteger()) 10167 return false; 10168 10169 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10170 return true; 10171 } 10172 10173 /// Check whether this is a valid redeclaration of a previous enumeration. 10174 /// \return true if the redeclaration was invalid. 10175 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10176 QualType EnumUnderlyingTy, 10177 const EnumDecl *Prev) { 10178 bool IsFixed = !EnumUnderlyingTy.isNull(); 10179 10180 if (IsScoped != Prev->isScoped()) { 10181 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10182 << Prev->isScoped(); 10183 Diag(Prev->getLocation(), diag::note_previous_declaration); 10184 return true; 10185 } 10186 10187 if (IsFixed && Prev->isFixed()) { 10188 if (!EnumUnderlyingTy->isDependentType() && 10189 !Prev->getIntegerType()->isDependentType() && 10190 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10191 Prev->getIntegerType())) { 10192 // TODO: Highlight the underlying type of the redeclaration. 10193 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10194 << EnumUnderlyingTy << Prev->getIntegerType(); 10195 Diag(Prev->getLocation(), diag::note_previous_declaration) 10196 << Prev->getIntegerTypeRange(); 10197 return true; 10198 } 10199 } else if (IsFixed != Prev->isFixed()) { 10200 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10201 << Prev->isFixed(); 10202 Diag(Prev->getLocation(), diag::note_previous_declaration); 10203 return true; 10204 } 10205 10206 return false; 10207 } 10208 10209 /// \brief Get diagnostic %select index for tag kind for 10210 /// redeclaration diagnostic message. 10211 /// WARNING: Indexes apply to particular diagnostics only! 10212 /// 10213 /// \returns diagnostic %select index. 10214 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10215 switch (Tag) { 10216 case TTK_Struct: return 0; 10217 case TTK_Interface: return 1; 10218 case TTK_Class: return 2; 10219 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10220 } 10221 } 10222 10223 /// \brief Determine if tag kind is a class-key compatible with 10224 /// class for redeclaration (class, struct, or __interface). 10225 /// 10226 /// \returns true iff the tag kind is compatible. 10227 static bool isClassCompatTagKind(TagTypeKind Tag) 10228 { 10229 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10230 } 10231 10232 /// \brief Determine whether a tag with a given kind is acceptable 10233 /// as a redeclaration of the given tag declaration. 10234 /// 10235 /// \returns true if the new tag kind is acceptable, false otherwise. 10236 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10237 TagTypeKind NewTag, bool isDefinition, 10238 SourceLocation NewTagLoc, 10239 const IdentifierInfo &Name) { 10240 // C++ [dcl.type.elab]p3: 10241 // The class-key or enum keyword present in the 10242 // elaborated-type-specifier shall agree in kind with the 10243 // declaration to which the name in the elaborated-type-specifier 10244 // refers. This rule also applies to the form of 10245 // elaborated-type-specifier that declares a class-name or 10246 // friend class since it can be construed as referring to the 10247 // definition of the class. Thus, in any 10248 // elaborated-type-specifier, the enum keyword shall be used to 10249 // refer to an enumeration (7.2), the union class-key shall be 10250 // used to refer to a union (clause 9), and either the class or 10251 // struct class-key shall be used to refer to a class (clause 9) 10252 // declared using the class or struct class-key. 10253 TagTypeKind OldTag = Previous->getTagKind(); 10254 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10255 if (OldTag == NewTag) 10256 return true; 10257 10258 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10259 // Warn about the struct/class tag mismatch. 10260 bool isTemplate = false; 10261 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10262 isTemplate = Record->getDescribedClassTemplate(); 10263 10264 if (!ActiveTemplateInstantiations.empty()) { 10265 // In a template instantiation, do not offer fix-its for tag mismatches 10266 // since they usually mess up the template instead of fixing the problem. 10267 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10268 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10269 << getRedeclDiagFromTagKind(OldTag); 10270 return true; 10271 } 10272 10273 if (isDefinition) { 10274 // On definitions, check previous tags and issue a fix-it for each 10275 // one that doesn't match the current tag. 10276 if (Previous->getDefinition()) { 10277 // Don't suggest fix-its for redefinitions. 10278 return true; 10279 } 10280 10281 bool previousMismatch = false; 10282 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 10283 E(Previous->redecls_end()); I != E; ++I) { 10284 if (I->getTagKind() != NewTag) { 10285 if (!previousMismatch) { 10286 previousMismatch = true; 10287 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10288 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10289 << getRedeclDiagFromTagKind(I->getTagKind()); 10290 } 10291 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10292 << getRedeclDiagFromTagKind(NewTag) 10293 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10294 TypeWithKeyword::getTagTypeKindName(NewTag)); 10295 } 10296 } 10297 return true; 10298 } 10299 10300 // Check for a previous definition. If current tag and definition 10301 // are same type, do nothing. If no definition, but disagree with 10302 // with previous tag type, give a warning, but no fix-it. 10303 const TagDecl *Redecl = Previous->getDefinition() ? 10304 Previous->getDefinition() : Previous; 10305 if (Redecl->getTagKind() == NewTag) { 10306 return true; 10307 } 10308 10309 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10310 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10311 << getRedeclDiagFromTagKind(OldTag); 10312 Diag(Redecl->getLocation(), diag::note_previous_use); 10313 10314 // If there is a previous definition, suggest a fix-it. 10315 if (Previous->getDefinition()) { 10316 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10317 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10318 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10319 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10320 } 10321 10322 return true; 10323 } 10324 return false; 10325 } 10326 10327 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10328 /// former case, Name will be non-null. In the later case, Name will be null. 10329 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10330 /// reference/declaration/definition of a tag. 10331 /// 10332 /// IsTypeSpecifier is true if this is a type-specifier (or 10333 /// trailing-type-specifier) other than one in an alias-declaration. 10334 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10335 SourceLocation KWLoc, CXXScopeSpec &SS, 10336 IdentifierInfo *Name, SourceLocation NameLoc, 10337 AttributeList *Attr, AccessSpecifier AS, 10338 SourceLocation ModulePrivateLoc, 10339 MultiTemplateParamsArg TemplateParameterLists, 10340 bool &OwnedDecl, bool &IsDependent, 10341 SourceLocation ScopedEnumKWLoc, 10342 bool ScopedEnumUsesClassTag, 10343 TypeResult UnderlyingType, 10344 bool IsTypeSpecifier) { 10345 // If this is not a definition, it must have a name. 10346 IdentifierInfo *OrigName = Name; 10347 assert((Name != 0 || TUK == TUK_Definition) && 10348 "Nameless record must be a definition!"); 10349 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10350 10351 OwnedDecl = false; 10352 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10353 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10354 10355 // FIXME: Check explicit specializations more carefully. 10356 bool isExplicitSpecialization = false; 10357 bool Invalid = false; 10358 10359 // We only need to do this matching if we have template parameters 10360 // or a scope specifier, which also conveniently avoids this work 10361 // for non-C++ cases. 10362 if (TemplateParameterLists.size() > 0 || 10363 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10364 if (TemplateParameterList *TemplateParams = 10365 MatchTemplateParametersToScopeSpecifier( 10366 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10367 isExplicitSpecialization, Invalid)) { 10368 if (Kind == TTK_Enum) { 10369 Diag(KWLoc, diag::err_enum_template); 10370 return 0; 10371 } 10372 10373 if (TemplateParams->size() > 0) { 10374 // This is a declaration or definition of a class template (which may 10375 // be a member of another template). 10376 10377 if (Invalid) 10378 return 0; 10379 10380 OwnedDecl = false; 10381 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10382 SS, Name, NameLoc, Attr, 10383 TemplateParams, AS, 10384 ModulePrivateLoc, 10385 TemplateParameterLists.size()-1, 10386 TemplateParameterLists.data()); 10387 return Result.get(); 10388 } else { 10389 // The "template<>" header is extraneous. 10390 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10391 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10392 isExplicitSpecialization = true; 10393 } 10394 } 10395 } 10396 10397 // Figure out the underlying type if this a enum declaration. We need to do 10398 // this early, because it's needed to detect if this is an incompatible 10399 // redeclaration. 10400 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10401 10402 if (Kind == TTK_Enum) { 10403 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10404 // No underlying type explicitly specified, or we failed to parse the 10405 // type, default to int. 10406 EnumUnderlying = Context.IntTy.getTypePtr(); 10407 else if (UnderlyingType.get()) { 10408 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10409 // integral type; any cv-qualification is ignored. 10410 TypeSourceInfo *TI = 0; 10411 GetTypeFromParser(UnderlyingType.get(), &TI); 10412 EnumUnderlying = TI; 10413 10414 if (CheckEnumUnderlyingType(TI)) 10415 // Recover by falling back to int. 10416 EnumUnderlying = Context.IntTy.getTypePtr(); 10417 10418 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10419 UPPC_FixedUnderlyingType)) 10420 EnumUnderlying = Context.IntTy.getTypePtr(); 10421 10422 } else if (getLangOpts().MSVCCompat) 10423 // Microsoft enums are always of int type. 10424 EnumUnderlying = Context.IntTy.getTypePtr(); 10425 } 10426 10427 DeclContext *SearchDC = CurContext; 10428 DeclContext *DC = CurContext; 10429 bool isStdBadAlloc = false; 10430 10431 RedeclarationKind Redecl = ForRedeclaration; 10432 if (TUK == TUK_Friend || TUK == TUK_Reference) 10433 Redecl = NotForRedeclaration; 10434 10435 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10436 bool FriendSawTagOutsideEnclosingNamespace = false; 10437 if (Name && SS.isNotEmpty()) { 10438 // We have a nested-name tag ('struct foo::bar'). 10439 10440 // Check for invalid 'foo::'. 10441 if (SS.isInvalid()) { 10442 Name = 0; 10443 goto CreateNewDecl; 10444 } 10445 10446 // If this is a friend or a reference to a class in a dependent 10447 // context, don't try to make a decl for it. 10448 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10449 DC = computeDeclContext(SS, false); 10450 if (!DC) { 10451 IsDependent = true; 10452 return 0; 10453 } 10454 } else { 10455 DC = computeDeclContext(SS, true); 10456 if (!DC) { 10457 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10458 << SS.getRange(); 10459 return 0; 10460 } 10461 } 10462 10463 if (RequireCompleteDeclContext(SS, DC)) 10464 return 0; 10465 10466 SearchDC = DC; 10467 // Look-up name inside 'foo::'. 10468 LookupQualifiedName(Previous, DC); 10469 10470 if (Previous.isAmbiguous()) 10471 return 0; 10472 10473 if (Previous.empty()) { 10474 // Name lookup did not find anything. However, if the 10475 // nested-name-specifier refers to the current instantiation, 10476 // and that current instantiation has any dependent base 10477 // classes, we might find something at instantiation time: treat 10478 // this as a dependent elaborated-type-specifier. 10479 // But this only makes any sense for reference-like lookups. 10480 if (Previous.wasNotFoundInCurrentInstantiation() && 10481 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10482 IsDependent = true; 10483 return 0; 10484 } 10485 10486 // A tag 'foo::bar' must already exist. 10487 Diag(NameLoc, diag::err_not_tag_in_scope) 10488 << Kind << Name << DC << SS.getRange(); 10489 Name = 0; 10490 Invalid = true; 10491 goto CreateNewDecl; 10492 } 10493 } else if (Name) { 10494 // If this is a named struct, check to see if there was a previous forward 10495 // declaration or definition. 10496 // FIXME: We're looking into outer scopes here, even when we 10497 // shouldn't be. Doing so can result in ambiguities that we 10498 // shouldn't be diagnosing. 10499 LookupName(Previous, S); 10500 10501 // When declaring or defining a tag, ignore ambiguities introduced 10502 // by types using'ed into this scope. 10503 if (Previous.isAmbiguous() && 10504 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10505 LookupResult::Filter F = Previous.makeFilter(); 10506 while (F.hasNext()) { 10507 NamedDecl *ND = F.next(); 10508 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10509 F.erase(); 10510 } 10511 F.done(); 10512 } 10513 10514 // C++11 [namespace.memdef]p3: 10515 // If the name in a friend declaration is neither qualified nor 10516 // a template-id and the declaration is a function or an 10517 // elaborated-type-specifier, the lookup to determine whether 10518 // the entity has been previously declared shall not consider 10519 // any scopes outside the innermost enclosing namespace. 10520 // 10521 // Does it matter that this should be by scope instead of by 10522 // semantic context? 10523 if (!Previous.empty() && TUK == TUK_Friend) { 10524 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10525 LookupResult::Filter F = Previous.makeFilter(); 10526 while (F.hasNext()) { 10527 NamedDecl *ND = F.next(); 10528 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10529 if (DC->isFileContext() && 10530 !EnclosingNS->Encloses(ND->getDeclContext())) { 10531 F.erase(); 10532 FriendSawTagOutsideEnclosingNamespace = true; 10533 } 10534 } 10535 F.done(); 10536 } 10537 10538 // Note: there used to be some attempt at recovery here. 10539 if (Previous.isAmbiguous()) 10540 return 0; 10541 10542 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10543 // FIXME: This makes sure that we ignore the contexts associated 10544 // with C structs, unions, and enums when looking for a matching 10545 // tag declaration or definition. See the similar lookup tweak 10546 // in Sema::LookupName; is there a better way to deal with this? 10547 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10548 SearchDC = SearchDC->getParent(); 10549 } 10550 } else if (S->isFunctionPrototypeScope()) { 10551 // If this is an enum declaration in function prototype scope, set its 10552 // initial context to the translation unit. 10553 // FIXME: [citation needed] 10554 SearchDC = Context.getTranslationUnitDecl(); 10555 } 10556 10557 if (Previous.isSingleResult() && 10558 Previous.getFoundDecl()->isTemplateParameter()) { 10559 // Maybe we will complain about the shadowed template parameter. 10560 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10561 // Just pretend that we didn't see the previous declaration. 10562 Previous.clear(); 10563 } 10564 10565 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10566 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10567 // This is a declaration of or a reference to "std::bad_alloc". 10568 isStdBadAlloc = true; 10569 10570 if (Previous.empty() && StdBadAlloc) { 10571 // std::bad_alloc has been implicitly declared (but made invisible to 10572 // name lookup). Fill in this implicit declaration as the previous 10573 // declaration, so that the declarations get chained appropriately. 10574 Previous.addDecl(getStdBadAlloc()); 10575 } 10576 } 10577 10578 // If we didn't find a previous declaration, and this is a reference 10579 // (or friend reference), move to the correct scope. In C++, we 10580 // also need to do a redeclaration lookup there, just in case 10581 // there's a shadow friend decl. 10582 if (Name && Previous.empty() && 10583 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10584 if (Invalid) goto CreateNewDecl; 10585 assert(SS.isEmpty()); 10586 10587 if (TUK == TUK_Reference) { 10588 // C++ [basic.scope.pdecl]p5: 10589 // -- for an elaborated-type-specifier of the form 10590 // 10591 // class-key identifier 10592 // 10593 // if the elaborated-type-specifier is used in the 10594 // decl-specifier-seq or parameter-declaration-clause of a 10595 // function defined in namespace scope, the identifier is 10596 // declared as a class-name in the namespace that contains 10597 // the declaration; otherwise, except as a friend 10598 // declaration, the identifier is declared in the smallest 10599 // non-class, non-function-prototype scope that contains the 10600 // declaration. 10601 // 10602 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10603 // C structs and unions. 10604 // 10605 // It is an error in C++ to declare (rather than define) an enum 10606 // type, including via an elaborated type specifier. We'll 10607 // diagnose that later; for now, declare the enum in the same 10608 // scope as we would have picked for any other tag type. 10609 // 10610 // GNU C also supports this behavior as part of its incomplete 10611 // enum types extension, while GNU C++ does not. 10612 // 10613 // Find the context where we'll be declaring the tag. 10614 // FIXME: We would like to maintain the current DeclContext as the 10615 // lexical context, 10616 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10617 SearchDC = SearchDC->getParent(); 10618 10619 // Find the scope where we'll be declaring the tag. 10620 while (S->isClassScope() || 10621 (getLangOpts().CPlusPlus && 10622 S->isFunctionPrototypeScope()) || 10623 ((S->getFlags() & Scope::DeclScope) == 0) || 10624 (S->getEntity() && S->getEntity()->isTransparentContext())) 10625 S = S->getParent(); 10626 } else { 10627 assert(TUK == TUK_Friend); 10628 // C++ [namespace.memdef]p3: 10629 // If a friend declaration in a non-local class first declares a 10630 // class or function, the friend class or function is a member of 10631 // the innermost enclosing namespace. 10632 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10633 } 10634 10635 // In C++, we need to do a redeclaration lookup to properly 10636 // diagnose some problems. 10637 if (getLangOpts().CPlusPlus) { 10638 Previous.setRedeclarationKind(ForRedeclaration); 10639 LookupQualifiedName(Previous, SearchDC); 10640 } 10641 } 10642 10643 if (!Previous.empty()) { 10644 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10645 NamedDecl *DirectPrevDecl = 10646 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10647 10648 // It's okay to have a tag decl in the same scope as a typedef 10649 // which hides a tag decl in the same scope. Finding this 10650 // insanity with a redeclaration lookup can only actually happen 10651 // in C++. 10652 // 10653 // This is also okay for elaborated-type-specifiers, which is 10654 // technically forbidden by the current standard but which is 10655 // okay according to the likely resolution of an open issue; 10656 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10657 if (getLangOpts().CPlusPlus) { 10658 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10659 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10660 TagDecl *Tag = TT->getDecl(); 10661 if (Tag->getDeclName() == Name && 10662 Tag->getDeclContext()->getRedeclContext() 10663 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10664 PrevDecl = Tag; 10665 Previous.clear(); 10666 Previous.addDecl(Tag); 10667 Previous.resolveKind(); 10668 } 10669 } 10670 } 10671 } 10672 10673 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10674 // If this is a use of a previous tag, or if the tag is already declared 10675 // in the same scope (so that the definition/declaration completes or 10676 // rementions the tag), reuse the decl. 10677 if (TUK == TUK_Reference || TUK == TUK_Friend || 10678 isDeclInScope(DirectPrevDecl, SearchDC, S, 10679 SS.isNotEmpty() || isExplicitSpecialization)) { 10680 // Make sure that this wasn't declared as an enum and now used as a 10681 // struct or something similar. 10682 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10683 TUK == TUK_Definition, KWLoc, 10684 *Name)) { 10685 bool SafeToContinue 10686 = (PrevTagDecl->getTagKind() != TTK_Enum && 10687 Kind != TTK_Enum); 10688 if (SafeToContinue) 10689 Diag(KWLoc, diag::err_use_with_wrong_tag) 10690 << Name 10691 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10692 PrevTagDecl->getKindName()); 10693 else 10694 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10695 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10696 10697 if (SafeToContinue) 10698 Kind = PrevTagDecl->getTagKind(); 10699 else { 10700 // Recover by making this an anonymous redefinition. 10701 Name = 0; 10702 Previous.clear(); 10703 Invalid = true; 10704 } 10705 } 10706 10707 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10708 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10709 10710 // If this is an elaborated-type-specifier for a scoped enumeration, 10711 // the 'class' keyword is not necessary and not permitted. 10712 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10713 if (ScopedEnum) 10714 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10715 << PrevEnum->isScoped() 10716 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10717 return PrevTagDecl; 10718 } 10719 10720 QualType EnumUnderlyingTy; 10721 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10722 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 10723 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10724 EnumUnderlyingTy = QualType(T, 0); 10725 10726 // All conflicts with previous declarations are recovered by 10727 // returning the previous declaration, unless this is a definition, 10728 // in which case we want the caller to bail out. 10729 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10730 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10731 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10732 } 10733 10734 // C++11 [class.mem]p1: 10735 // A member shall not be declared twice in the member-specification, 10736 // except that a nested class or member class template can be declared 10737 // and then later defined. 10738 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10739 S->isDeclScope(PrevDecl)) { 10740 Diag(NameLoc, diag::ext_member_redeclared); 10741 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10742 } 10743 10744 if (!Invalid) { 10745 // If this is a use, just return the declaration we found. 10746 10747 // FIXME: In the future, return a variant or some other clue 10748 // for the consumer of this Decl to know it doesn't own it. 10749 // For our current ASTs this shouldn't be a problem, but will 10750 // need to be changed with DeclGroups. 10751 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10752 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10753 return PrevTagDecl; 10754 10755 // Diagnose attempts to redefine a tag. 10756 if (TUK == TUK_Definition) { 10757 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10758 // If we're defining a specialization and the previous definition 10759 // is from an implicit instantiation, don't emit an error 10760 // here; we'll catch this in the general case below. 10761 bool IsExplicitSpecializationAfterInstantiation = false; 10762 if (isExplicitSpecialization) { 10763 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10764 IsExplicitSpecializationAfterInstantiation = 10765 RD->getTemplateSpecializationKind() != 10766 TSK_ExplicitSpecialization; 10767 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10768 IsExplicitSpecializationAfterInstantiation = 10769 ED->getTemplateSpecializationKind() != 10770 TSK_ExplicitSpecialization; 10771 } 10772 10773 if (!IsExplicitSpecializationAfterInstantiation) { 10774 // A redeclaration in function prototype scope in C isn't 10775 // visible elsewhere, so merely issue a warning. 10776 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10777 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10778 else 10779 Diag(NameLoc, diag::err_redefinition) << Name; 10780 Diag(Def->getLocation(), diag::note_previous_definition); 10781 // If this is a redefinition, recover by making this 10782 // struct be anonymous, which will make any later 10783 // references get the previous definition. 10784 Name = 0; 10785 Previous.clear(); 10786 Invalid = true; 10787 } 10788 } else { 10789 // If the type is currently being defined, complain 10790 // about a nested redefinition. 10791 const TagType *Tag 10792 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10793 if (Tag->isBeingDefined()) { 10794 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10795 Diag(PrevTagDecl->getLocation(), 10796 diag::note_previous_definition); 10797 Name = 0; 10798 Previous.clear(); 10799 Invalid = true; 10800 } 10801 } 10802 10803 // Okay, this is definition of a previously declared or referenced 10804 // tag PrevDecl. We're going to create a new Decl for it. 10805 } 10806 } 10807 // If we get here we have (another) forward declaration or we 10808 // have a definition. Just create a new decl. 10809 10810 } else { 10811 // If we get here, this is a definition of a new tag type in a nested 10812 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 10813 // new decl/type. We set PrevDecl to NULL so that the entities 10814 // have distinct types. 10815 Previous.clear(); 10816 } 10817 // If we get here, we're going to create a new Decl. If PrevDecl 10818 // is non-NULL, it's a definition of the tag declared by 10819 // PrevDecl. If it's NULL, we have a new definition. 10820 10821 10822 // Otherwise, PrevDecl is not a tag, but was found with tag 10823 // lookup. This is only actually possible in C++, where a few 10824 // things like templates still live in the tag namespace. 10825 } else { 10826 // Use a better diagnostic if an elaborated-type-specifier 10827 // found the wrong kind of type on the first 10828 // (non-redeclaration) lookup. 10829 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 10830 !Previous.isForRedeclaration()) { 10831 unsigned Kind = 0; 10832 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10833 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10834 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10835 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 10836 Diag(PrevDecl->getLocation(), diag::note_declared_at); 10837 Invalid = true; 10838 10839 // Otherwise, only diagnose if the declaration is in scope. 10840 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 10841 SS.isNotEmpty() || isExplicitSpecialization)) { 10842 // do nothing 10843 10844 // Diagnose implicit declarations introduced by elaborated types. 10845 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 10846 unsigned Kind = 0; 10847 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10848 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10849 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10850 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 10851 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10852 Invalid = true; 10853 10854 // Otherwise it's a declaration. Call out a particularly common 10855 // case here. 10856 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10857 unsigned Kind = 0; 10858 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 10859 Diag(NameLoc, diag::err_tag_definition_of_typedef) 10860 << Name << Kind << TND->getUnderlyingType(); 10861 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10862 Invalid = true; 10863 10864 // Otherwise, diagnose. 10865 } else { 10866 // The tag name clashes with something else in the target scope, 10867 // issue an error and recover by making this tag be anonymous. 10868 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 10869 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10870 Name = 0; 10871 Invalid = true; 10872 } 10873 10874 // The existing declaration isn't relevant to us; we're in a 10875 // new scope, so clear out the previous declaration. 10876 Previous.clear(); 10877 } 10878 } 10879 10880 CreateNewDecl: 10881 10882 TagDecl *PrevDecl = 0; 10883 if (Previous.isSingleResult()) 10884 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 10885 10886 // If there is an identifier, use the location of the identifier as the 10887 // location of the decl, otherwise use the location of the struct/union 10888 // keyword. 10889 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 10890 10891 // Otherwise, create a new declaration. If there is a previous 10892 // declaration of the same entity, the two will be linked via 10893 // PrevDecl. 10894 TagDecl *New; 10895 10896 bool IsForwardReference = false; 10897 if (Kind == TTK_Enum) { 10898 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10899 // enum X { A, B, C } D; D should chain to X. 10900 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 10901 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 10902 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 10903 // If this is an undefined enum, warn. 10904 if (TUK != TUK_Definition && !Invalid) { 10905 TagDecl *Def; 10906 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 10907 cast<EnumDecl>(New)->isFixed()) { 10908 // C++0x: 7.2p2: opaque-enum-declaration. 10909 // Conflicts are diagnosed above. Do nothing. 10910 } 10911 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 10912 Diag(Loc, diag::ext_forward_ref_enum_def) 10913 << New; 10914 Diag(Def->getLocation(), diag::note_previous_definition); 10915 } else { 10916 unsigned DiagID = diag::ext_forward_ref_enum; 10917 if (getLangOpts().MSVCCompat) 10918 DiagID = diag::ext_ms_forward_ref_enum; 10919 else if (getLangOpts().CPlusPlus) 10920 DiagID = diag::err_forward_ref_enum; 10921 Diag(Loc, DiagID); 10922 10923 // If this is a forward-declared reference to an enumeration, make a 10924 // note of it; we won't actually be introducing the declaration into 10925 // the declaration context. 10926 if (TUK == TUK_Reference) 10927 IsForwardReference = true; 10928 } 10929 } 10930 10931 if (EnumUnderlying) { 10932 EnumDecl *ED = cast<EnumDecl>(New); 10933 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10934 ED->setIntegerTypeSourceInfo(TI); 10935 else 10936 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 10937 ED->setPromotionType(ED->getIntegerType()); 10938 } 10939 10940 } else { 10941 // struct/union/class 10942 10943 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10944 // struct X { int A; } D; D should chain to X. 10945 if (getLangOpts().CPlusPlus) { 10946 // FIXME: Look for a way to use RecordDecl for simple structs. 10947 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10948 cast_or_null<CXXRecordDecl>(PrevDecl)); 10949 10950 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 10951 StdBadAlloc = cast<CXXRecordDecl>(New); 10952 } else 10953 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10954 cast_or_null<RecordDecl>(PrevDecl)); 10955 } 10956 10957 // C++11 [dcl.type]p3: 10958 // A type-specifier-seq shall not define a class or enumeration [...]. 10959 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 10960 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 10961 << Context.getTagDeclType(New); 10962 Invalid = true; 10963 } 10964 10965 // Maybe add qualifier info. 10966 if (SS.isNotEmpty()) { 10967 if (SS.isSet()) { 10968 // If this is either a declaration or a definition, check the 10969 // nested-name-specifier against the current context. We don't do this 10970 // for explicit specializations, because they have similar checking 10971 // (with more specific diagnostics) in the call to 10972 // CheckMemberSpecialization, below. 10973 if (!isExplicitSpecialization && 10974 (TUK == TUK_Definition || TUK == TUK_Declaration) && 10975 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 10976 Invalid = true; 10977 10978 New->setQualifierInfo(SS.getWithLocInContext(Context)); 10979 if (TemplateParameterLists.size() > 0) { 10980 New->setTemplateParameterListsInfo(Context, 10981 TemplateParameterLists.size(), 10982 TemplateParameterLists.data()); 10983 } 10984 } 10985 else 10986 Invalid = true; 10987 } 10988 10989 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 10990 // Add alignment attributes if necessary; these attributes are checked when 10991 // the ASTContext lays out the structure. 10992 // 10993 // It is important for implementing the correct semantics that this 10994 // happen here (in act on tag decl). The #pragma pack stack is 10995 // maintained as a result of parser callbacks which can occur at 10996 // many points during the parsing of a struct declaration (because 10997 // the #pragma tokens are effectively skipped over during the 10998 // parsing of the struct). 10999 if (TUK == TUK_Definition) { 11000 AddAlignmentAttributesForRecord(RD); 11001 AddMsStructLayoutForRecord(RD); 11002 } 11003 } 11004 11005 if (ModulePrivateLoc.isValid()) { 11006 if (isExplicitSpecialization) 11007 Diag(New->getLocation(), diag::err_module_private_specialization) 11008 << 2 11009 << FixItHint::CreateRemoval(ModulePrivateLoc); 11010 // __module_private__ does not apply to local classes. However, we only 11011 // diagnose this as an error when the declaration specifiers are 11012 // freestanding. Here, we just ignore the __module_private__. 11013 else if (!SearchDC->isFunctionOrMethod()) 11014 New->setModulePrivate(); 11015 } 11016 11017 // If this is a specialization of a member class (of a class template), 11018 // check the specialization. 11019 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11020 Invalid = true; 11021 11022 if (Invalid) 11023 New->setInvalidDecl(); 11024 11025 if (Attr) 11026 ProcessDeclAttributeList(S, New, Attr); 11027 11028 // If we're declaring or defining a tag in function prototype scope 11029 // in C, note that this type can only be used within the function. 11030 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 11031 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11032 11033 // Set the lexical context. If the tag has a C++ scope specifier, the 11034 // lexical context will be different from the semantic context. 11035 New->setLexicalDeclContext(CurContext); 11036 11037 // Mark this as a friend decl if applicable. 11038 // In Microsoft mode, a friend declaration also acts as a forward 11039 // declaration so we always pass true to setObjectOfFriendDecl to make 11040 // the tag name visible. 11041 if (TUK == TUK_Friend) 11042 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11043 getLangOpts().MicrosoftExt); 11044 11045 // Set the access specifier. 11046 if (!Invalid && SearchDC->isRecord()) 11047 SetMemberAccessSpecifier(New, PrevDecl, AS); 11048 11049 if (TUK == TUK_Definition) 11050 New->startDefinition(); 11051 11052 // If this has an identifier, add it to the scope stack. 11053 if (TUK == TUK_Friend) { 11054 // We might be replacing an existing declaration in the lookup tables; 11055 // if so, borrow its access specifier. 11056 if (PrevDecl) 11057 New->setAccess(PrevDecl->getAccess()); 11058 11059 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11060 DC->makeDeclVisibleInContext(New); 11061 if (Name) // can be null along some error paths 11062 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11063 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11064 } else if (Name) { 11065 S = getNonFieldDeclScope(S); 11066 PushOnScopeChains(New, S, !IsForwardReference); 11067 if (IsForwardReference) 11068 SearchDC->makeDeclVisibleInContext(New); 11069 11070 } else { 11071 CurContext->addDecl(New); 11072 } 11073 11074 // If this is the C FILE type, notify the AST context. 11075 if (IdentifierInfo *II = New->getIdentifier()) 11076 if (!New->isInvalidDecl() && 11077 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11078 II->isStr("FILE")) 11079 Context.setFILEDecl(New); 11080 11081 // If we were in function prototype scope (and not in C++ mode), add this 11082 // tag to the list of decls to inject into the function definition scope. 11083 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 11084 InFunctionDeclarator && Name) 11085 DeclsInPrototypeScope.push_back(New); 11086 11087 if (PrevDecl) 11088 mergeDeclAttributes(New, PrevDecl); 11089 11090 // If there's a #pragma GCC visibility in scope, set the visibility of this 11091 // record. 11092 AddPushedVisibilityAttribute(New); 11093 11094 OwnedDecl = true; 11095 // In C++, don't return an invalid declaration. We can't recover well from 11096 // the cases where we make the type anonymous. 11097 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11098 } 11099 11100 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11101 AdjustDeclIfTemplate(TagD); 11102 TagDecl *Tag = cast<TagDecl>(TagD); 11103 11104 // Enter the tag context. 11105 PushDeclContext(S, Tag); 11106 11107 ActOnDocumentableDecl(TagD); 11108 11109 // If there's a #pragma GCC visibility in scope, set the visibility of this 11110 // record. 11111 AddPushedVisibilityAttribute(Tag); 11112 } 11113 11114 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11115 assert(isa<ObjCContainerDecl>(IDecl) && 11116 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11117 DeclContext *OCD = cast<DeclContext>(IDecl); 11118 assert(getContainingDC(OCD) == CurContext && 11119 "The next DeclContext should be lexically contained in the current one."); 11120 CurContext = OCD; 11121 return IDecl; 11122 } 11123 11124 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11125 SourceLocation FinalLoc, 11126 bool IsFinalSpelledSealed, 11127 SourceLocation LBraceLoc) { 11128 AdjustDeclIfTemplate(TagD); 11129 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11130 11131 FieldCollector->StartClass(); 11132 11133 if (!Record->getIdentifier()) 11134 return; 11135 11136 if (FinalLoc.isValid()) 11137 Record->addAttr(new (Context) 11138 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11139 11140 // C++ [class]p2: 11141 // [...] The class-name is also inserted into the scope of the 11142 // class itself; this is known as the injected-class-name. For 11143 // purposes of access checking, the injected-class-name is treated 11144 // as if it were a public member name. 11145 CXXRecordDecl *InjectedClassName 11146 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11147 Record->getLocStart(), Record->getLocation(), 11148 Record->getIdentifier(), 11149 /*PrevDecl=*/0, 11150 /*DelayTypeCreation=*/true); 11151 Context.getTypeDeclType(InjectedClassName, Record); 11152 InjectedClassName->setImplicit(); 11153 InjectedClassName->setAccess(AS_public); 11154 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11155 InjectedClassName->setDescribedClassTemplate(Template); 11156 PushOnScopeChains(InjectedClassName, S); 11157 assert(InjectedClassName->isInjectedClassName() && 11158 "Broken injected-class-name"); 11159 } 11160 11161 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11162 SourceLocation RBraceLoc) { 11163 AdjustDeclIfTemplate(TagD); 11164 TagDecl *Tag = cast<TagDecl>(TagD); 11165 Tag->setRBraceLoc(RBraceLoc); 11166 11167 // Make sure we "complete" the definition even it is invalid. 11168 if (Tag->isBeingDefined()) { 11169 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11170 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11171 RD->completeDefinition(); 11172 } 11173 11174 if (isa<CXXRecordDecl>(Tag)) 11175 FieldCollector->FinishClass(); 11176 11177 // Exit this scope of this tag's definition. 11178 PopDeclContext(); 11179 11180 if (getCurLexicalContext()->isObjCContainer() && 11181 Tag->getDeclContext()->isFileContext()) 11182 Tag->setTopLevelDeclInObjCContainer(); 11183 11184 // Notify the consumer that we've defined a tag. 11185 if (!Tag->isInvalidDecl()) 11186 Consumer.HandleTagDeclDefinition(Tag); 11187 } 11188 11189 void Sema::ActOnObjCContainerFinishDefinition() { 11190 // Exit this scope of this interface definition. 11191 PopDeclContext(); 11192 } 11193 11194 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11195 assert(DC == CurContext && "Mismatch of container contexts"); 11196 OriginalLexicalContext = DC; 11197 ActOnObjCContainerFinishDefinition(); 11198 } 11199 11200 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11201 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11202 OriginalLexicalContext = 0; 11203 } 11204 11205 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11206 AdjustDeclIfTemplate(TagD); 11207 TagDecl *Tag = cast<TagDecl>(TagD); 11208 Tag->setInvalidDecl(); 11209 11210 // Make sure we "complete" the definition even it is invalid. 11211 if (Tag->isBeingDefined()) { 11212 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11213 RD->completeDefinition(); 11214 } 11215 11216 // We're undoing ActOnTagStartDefinition here, not 11217 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11218 // the FieldCollector. 11219 11220 PopDeclContext(); 11221 } 11222 11223 // Note that FieldName may be null for anonymous bitfields. 11224 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11225 IdentifierInfo *FieldName, 11226 QualType FieldTy, bool IsMsStruct, 11227 Expr *BitWidth, bool *ZeroWidth) { 11228 // Default to true; that shouldn't confuse checks for emptiness 11229 if (ZeroWidth) 11230 *ZeroWidth = true; 11231 11232 // C99 6.7.2.1p4 - verify the field type. 11233 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11234 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11235 // Handle incomplete types with specific error. 11236 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11237 return ExprError(); 11238 if (FieldName) 11239 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11240 << FieldName << FieldTy << BitWidth->getSourceRange(); 11241 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11242 << FieldTy << BitWidth->getSourceRange(); 11243 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11244 UPPC_BitFieldWidth)) 11245 return ExprError(); 11246 11247 // If the bit-width is type- or value-dependent, don't try to check 11248 // it now. 11249 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11250 return Owned(BitWidth); 11251 11252 llvm::APSInt Value; 11253 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11254 if (ICE.isInvalid()) 11255 return ICE; 11256 BitWidth = ICE.take(); 11257 11258 if (Value != 0 && ZeroWidth) 11259 *ZeroWidth = false; 11260 11261 // Zero-width bitfield is ok for anonymous field. 11262 if (Value == 0 && FieldName) 11263 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11264 11265 if (Value.isSigned() && Value.isNegative()) { 11266 if (FieldName) 11267 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11268 << FieldName << Value.toString(10); 11269 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11270 << Value.toString(10); 11271 } 11272 11273 if (!FieldTy->isDependentType()) { 11274 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11275 if (Value.getZExtValue() > TypeSize) { 11276 if (!getLangOpts().CPlusPlus || IsMsStruct || 11277 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11278 if (FieldName) 11279 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11280 << FieldName << (unsigned)Value.getZExtValue() 11281 << (unsigned)TypeSize; 11282 11283 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11284 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11285 } 11286 11287 if (FieldName) 11288 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11289 << FieldName << (unsigned)Value.getZExtValue() 11290 << (unsigned)TypeSize; 11291 else 11292 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11293 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11294 } 11295 } 11296 11297 return Owned(BitWidth); 11298 } 11299 11300 /// ActOnField - Each field of a C struct/union is passed into this in order 11301 /// to create a FieldDecl object for it. 11302 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11303 Declarator &D, Expr *BitfieldWidth) { 11304 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11305 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11306 /*InitStyle=*/ICIS_NoInit, AS_public); 11307 return Res; 11308 } 11309 11310 /// HandleField - Analyze a field of a C struct or a C++ data member. 11311 /// 11312 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11313 SourceLocation DeclStart, 11314 Declarator &D, Expr *BitWidth, 11315 InClassInitStyle InitStyle, 11316 AccessSpecifier AS) { 11317 IdentifierInfo *II = D.getIdentifier(); 11318 SourceLocation Loc = DeclStart; 11319 if (II) Loc = D.getIdentifierLoc(); 11320 11321 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11322 QualType T = TInfo->getType(); 11323 if (getLangOpts().CPlusPlus) { 11324 CheckExtraCXXDefaultArguments(D); 11325 11326 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11327 UPPC_DataMemberType)) { 11328 D.setInvalidType(); 11329 T = Context.IntTy; 11330 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11331 } 11332 } 11333 11334 // TR 18037 does not allow fields to be declared with address spaces. 11335 if (T.getQualifiers().hasAddressSpace()) { 11336 Diag(Loc, diag::err_field_with_address_space); 11337 D.setInvalidType(); 11338 } 11339 11340 // OpenCL 1.2 spec, s6.9 r: 11341 // The event type cannot be used to declare a structure or union field. 11342 if (LangOpts.OpenCL && T->isEventT()) { 11343 Diag(Loc, diag::err_event_t_struct_field); 11344 D.setInvalidType(); 11345 } 11346 11347 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11348 11349 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11350 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11351 diag::err_invalid_thread) 11352 << DeclSpec::getSpecifierName(TSCS); 11353 11354 // Check to see if this name was declared as a member previously 11355 NamedDecl *PrevDecl = 0; 11356 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11357 LookupName(Previous, S); 11358 switch (Previous.getResultKind()) { 11359 case LookupResult::Found: 11360 case LookupResult::FoundUnresolvedValue: 11361 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11362 break; 11363 11364 case LookupResult::FoundOverloaded: 11365 PrevDecl = Previous.getRepresentativeDecl(); 11366 break; 11367 11368 case LookupResult::NotFound: 11369 case LookupResult::NotFoundInCurrentInstantiation: 11370 case LookupResult::Ambiguous: 11371 break; 11372 } 11373 Previous.suppressDiagnostics(); 11374 11375 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11376 // Maybe we will complain about the shadowed template parameter. 11377 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11378 // Just pretend that we didn't see the previous declaration. 11379 PrevDecl = 0; 11380 } 11381 11382 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11383 PrevDecl = 0; 11384 11385 bool Mutable 11386 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11387 SourceLocation TSSL = D.getLocStart(); 11388 FieldDecl *NewFD 11389 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11390 TSSL, AS, PrevDecl, &D); 11391 11392 if (NewFD->isInvalidDecl()) 11393 Record->setInvalidDecl(); 11394 11395 if (D.getDeclSpec().isModulePrivateSpecified()) 11396 NewFD->setModulePrivate(); 11397 11398 if (NewFD->isInvalidDecl() && PrevDecl) { 11399 // Don't introduce NewFD into scope; there's already something 11400 // with the same name in the same scope. 11401 } else if (II) { 11402 PushOnScopeChains(NewFD, S); 11403 } else 11404 Record->addDecl(NewFD); 11405 11406 return NewFD; 11407 } 11408 11409 /// \brief Build a new FieldDecl and check its well-formedness. 11410 /// 11411 /// This routine builds a new FieldDecl given the fields name, type, 11412 /// record, etc. \p PrevDecl should refer to any previous declaration 11413 /// with the same name and in the same scope as the field to be 11414 /// created. 11415 /// 11416 /// \returns a new FieldDecl. 11417 /// 11418 /// \todo The Declarator argument is a hack. It will be removed once 11419 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11420 TypeSourceInfo *TInfo, 11421 RecordDecl *Record, SourceLocation Loc, 11422 bool Mutable, Expr *BitWidth, 11423 InClassInitStyle InitStyle, 11424 SourceLocation TSSL, 11425 AccessSpecifier AS, NamedDecl *PrevDecl, 11426 Declarator *D) { 11427 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11428 bool InvalidDecl = false; 11429 if (D) InvalidDecl = D->isInvalidType(); 11430 11431 // If we receive a broken type, recover by assuming 'int' and 11432 // marking this declaration as invalid. 11433 if (T.isNull()) { 11434 InvalidDecl = true; 11435 T = Context.IntTy; 11436 } 11437 11438 QualType EltTy = Context.getBaseElementType(T); 11439 if (!EltTy->isDependentType()) { 11440 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11441 // Fields of incomplete type force their record to be invalid. 11442 Record->setInvalidDecl(); 11443 InvalidDecl = true; 11444 } else { 11445 NamedDecl *Def; 11446 EltTy->isIncompleteType(&Def); 11447 if (Def && Def->isInvalidDecl()) { 11448 Record->setInvalidDecl(); 11449 InvalidDecl = true; 11450 } 11451 } 11452 } 11453 11454 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11455 if (BitWidth && getLangOpts().OpenCL) { 11456 Diag(Loc, diag::err_opencl_bitfields); 11457 InvalidDecl = true; 11458 } 11459 11460 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11461 // than a variably modified type. 11462 if (!InvalidDecl && T->isVariablyModifiedType()) { 11463 bool SizeIsNegative; 11464 llvm::APSInt Oversized; 11465 11466 TypeSourceInfo *FixedTInfo = 11467 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11468 SizeIsNegative, 11469 Oversized); 11470 if (FixedTInfo) { 11471 Diag(Loc, diag::warn_illegal_constant_array_size); 11472 TInfo = FixedTInfo; 11473 T = FixedTInfo->getType(); 11474 } else { 11475 if (SizeIsNegative) 11476 Diag(Loc, diag::err_typecheck_negative_array_size); 11477 else if (Oversized.getBoolValue()) 11478 Diag(Loc, diag::err_array_too_large) 11479 << Oversized.toString(10); 11480 else 11481 Diag(Loc, diag::err_typecheck_field_variable_size); 11482 InvalidDecl = true; 11483 } 11484 } 11485 11486 // Fields can not have abstract class types 11487 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11488 diag::err_abstract_type_in_decl, 11489 AbstractFieldType)) 11490 InvalidDecl = true; 11491 11492 bool ZeroWidth = false; 11493 // If this is declared as a bit-field, check the bit-field. 11494 if (!InvalidDecl && BitWidth) { 11495 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11496 &ZeroWidth).take(); 11497 if (!BitWidth) { 11498 InvalidDecl = true; 11499 BitWidth = 0; 11500 ZeroWidth = false; 11501 } 11502 } 11503 11504 // Check that 'mutable' is consistent with the type of the declaration. 11505 if (!InvalidDecl && Mutable) { 11506 unsigned DiagID = 0; 11507 if (T->isReferenceType()) 11508 DiagID = diag::err_mutable_reference; 11509 else if (T.isConstQualified()) 11510 DiagID = diag::err_mutable_const; 11511 11512 if (DiagID) { 11513 SourceLocation ErrLoc = Loc; 11514 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11515 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11516 Diag(ErrLoc, DiagID); 11517 Mutable = false; 11518 InvalidDecl = true; 11519 } 11520 } 11521 11522 // C++11 [class.union]p8 (DR1460): 11523 // At most one variant member of a union may have a 11524 // brace-or-equal-initializer. 11525 if (InitStyle != ICIS_NoInit) 11526 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11527 11528 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11529 BitWidth, Mutable, InitStyle); 11530 if (InvalidDecl) 11531 NewFD->setInvalidDecl(); 11532 11533 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11534 Diag(Loc, diag::err_duplicate_member) << II; 11535 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11536 NewFD->setInvalidDecl(); 11537 } 11538 11539 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11540 if (Record->isUnion()) { 11541 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11542 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11543 if (RDecl->getDefinition()) { 11544 // C++ [class.union]p1: An object of a class with a non-trivial 11545 // constructor, a non-trivial copy constructor, a non-trivial 11546 // destructor, or a non-trivial copy assignment operator 11547 // cannot be a member of a union, nor can an array of such 11548 // objects. 11549 if (CheckNontrivialField(NewFD)) 11550 NewFD->setInvalidDecl(); 11551 } 11552 } 11553 11554 // C++ [class.union]p1: If a union contains a member of reference type, 11555 // the program is ill-formed, except when compiling with MSVC extensions 11556 // enabled. 11557 if (EltTy->isReferenceType()) { 11558 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11559 diag::ext_union_member_of_reference_type : 11560 diag::err_union_member_of_reference_type) 11561 << NewFD->getDeclName() << EltTy; 11562 if (!getLangOpts().MicrosoftExt) 11563 NewFD->setInvalidDecl(); 11564 } 11565 } 11566 } 11567 11568 // FIXME: We need to pass in the attributes given an AST 11569 // representation, not a parser representation. 11570 if (D) { 11571 // FIXME: The current scope is almost... but not entirely... correct here. 11572 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11573 11574 if (NewFD->hasAttrs()) 11575 CheckAlignasUnderalignment(NewFD); 11576 } 11577 11578 // In auto-retain/release, infer strong retension for fields of 11579 // retainable type. 11580 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11581 NewFD->setInvalidDecl(); 11582 11583 if (T.isObjCGCWeak()) 11584 Diag(Loc, diag::warn_attribute_weak_on_field); 11585 11586 NewFD->setAccess(AS); 11587 return NewFD; 11588 } 11589 11590 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11591 assert(FD); 11592 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11593 11594 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11595 return false; 11596 11597 QualType EltTy = Context.getBaseElementType(FD->getType()); 11598 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11599 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11600 if (RDecl->getDefinition()) { 11601 // We check for copy constructors before constructors 11602 // because otherwise we'll never get complaints about 11603 // copy constructors. 11604 11605 CXXSpecialMember member = CXXInvalid; 11606 // We're required to check for any non-trivial constructors. Since the 11607 // implicit default constructor is suppressed if there are any 11608 // user-declared constructors, we just need to check that there is a 11609 // trivial default constructor and a trivial copy constructor. (We don't 11610 // worry about move constructors here, since this is a C++98 check.) 11611 if (RDecl->hasNonTrivialCopyConstructor()) 11612 member = CXXCopyConstructor; 11613 else if (!RDecl->hasTrivialDefaultConstructor()) 11614 member = CXXDefaultConstructor; 11615 else if (RDecl->hasNonTrivialCopyAssignment()) 11616 member = CXXCopyAssignment; 11617 else if (RDecl->hasNonTrivialDestructor()) 11618 member = CXXDestructor; 11619 11620 if (member != CXXInvalid) { 11621 if (!getLangOpts().CPlusPlus11 && 11622 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11623 // Objective-C++ ARC: it is an error to have a non-trivial field of 11624 // a union. However, system headers in Objective-C programs 11625 // occasionally have Objective-C lifetime objects within unions, 11626 // and rather than cause the program to fail, we make those 11627 // members unavailable. 11628 SourceLocation Loc = FD->getLocation(); 11629 if (getSourceManager().isInSystemHeader(Loc)) { 11630 if (!FD->hasAttr<UnavailableAttr>()) 11631 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11632 "this system field has retaining ownership", 11633 Loc)); 11634 return false; 11635 } 11636 } 11637 11638 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11639 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11640 diag::err_illegal_union_or_anon_struct_member) 11641 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11642 DiagnoseNontrivial(RDecl, member); 11643 return !getLangOpts().CPlusPlus11; 11644 } 11645 } 11646 } 11647 11648 return false; 11649 } 11650 11651 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11652 /// AST enum value. 11653 static ObjCIvarDecl::AccessControl 11654 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11655 switch (ivarVisibility) { 11656 default: llvm_unreachable("Unknown visitibility kind"); 11657 case tok::objc_private: return ObjCIvarDecl::Private; 11658 case tok::objc_public: return ObjCIvarDecl::Public; 11659 case tok::objc_protected: return ObjCIvarDecl::Protected; 11660 case tok::objc_package: return ObjCIvarDecl::Package; 11661 } 11662 } 11663 11664 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11665 /// in order to create an IvarDecl object for it. 11666 Decl *Sema::ActOnIvar(Scope *S, 11667 SourceLocation DeclStart, 11668 Declarator &D, Expr *BitfieldWidth, 11669 tok::ObjCKeywordKind Visibility) { 11670 11671 IdentifierInfo *II = D.getIdentifier(); 11672 Expr *BitWidth = (Expr*)BitfieldWidth; 11673 SourceLocation Loc = DeclStart; 11674 if (II) Loc = D.getIdentifierLoc(); 11675 11676 // FIXME: Unnamed fields can be handled in various different ways, for 11677 // example, unnamed unions inject all members into the struct namespace! 11678 11679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11680 QualType T = TInfo->getType(); 11681 11682 if (BitWidth) { 11683 // 6.7.2.1p3, 6.7.2.1p4 11684 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11685 if (!BitWidth) 11686 D.setInvalidType(); 11687 } else { 11688 // Not a bitfield. 11689 11690 // validate II. 11691 11692 } 11693 if (T->isReferenceType()) { 11694 Diag(Loc, diag::err_ivar_reference_type); 11695 D.setInvalidType(); 11696 } 11697 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11698 // than a variably modified type. 11699 else if (T->isVariablyModifiedType()) { 11700 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11701 D.setInvalidType(); 11702 } 11703 11704 // Get the visibility (access control) for this ivar. 11705 ObjCIvarDecl::AccessControl ac = 11706 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11707 : ObjCIvarDecl::None; 11708 // Must set ivar's DeclContext to its enclosing interface. 11709 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11710 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11711 return 0; 11712 ObjCContainerDecl *EnclosingContext; 11713 if (ObjCImplementationDecl *IMPDecl = 11714 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11715 if (LangOpts.ObjCRuntime.isFragile()) { 11716 // Case of ivar declared in an implementation. Context is that of its class. 11717 EnclosingContext = IMPDecl->getClassInterface(); 11718 assert(EnclosingContext && "Implementation has no class interface!"); 11719 } 11720 else 11721 EnclosingContext = EnclosingDecl; 11722 } else { 11723 if (ObjCCategoryDecl *CDecl = 11724 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11725 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11726 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11727 return 0; 11728 } 11729 } 11730 EnclosingContext = EnclosingDecl; 11731 } 11732 11733 // Construct the decl. 11734 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11735 DeclStart, Loc, II, T, 11736 TInfo, ac, (Expr *)BitfieldWidth); 11737 11738 if (II) { 11739 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11740 ForRedeclaration); 11741 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11742 && !isa<TagDecl>(PrevDecl)) { 11743 Diag(Loc, diag::err_duplicate_member) << II; 11744 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11745 NewID->setInvalidDecl(); 11746 } 11747 } 11748 11749 // Process attributes attached to the ivar. 11750 ProcessDeclAttributes(S, NewID, D); 11751 11752 if (D.isInvalidType()) 11753 NewID->setInvalidDecl(); 11754 11755 // In ARC, infer 'retaining' for ivars of retainable type. 11756 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11757 NewID->setInvalidDecl(); 11758 11759 if (D.getDeclSpec().isModulePrivateSpecified()) 11760 NewID->setModulePrivate(); 11761 11762 if (II) { 11763 // FIXME: When interfaces are DeclContexts, we'll need to add 11764 // these to the interface. 11765 S->AddDecl(NewID); 11766 IdResolver.AddDecl(NewID); 11767 } 11768 11769 if (LangOpts.ObjCRuntime.isNonFragile() && 11770 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11771 Diag(Loc, diag::warn_ivars_in_interface); 11772 11773 return NewID; 11774 } 11775 11776 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11777 /// class and class extensions. For every class \@interface and class 11778 /// extension \@interface, if the last ivar is a bitfield of any type, 11779 /// then add an implicit `char :0` ivar to the end of that interface. 11780 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11781 SmallVectorImpl<Decl *> &AllIvarDecls) { 11782 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11783 return; 11784 11785 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11786 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11787 11788 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11789 return; 11790 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11791 if (!ID) { 11792 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11793 if (!CD->IsClassExtension()) 11794 return; 11795 } 11796 // No need to add this to end of @implementation. 11797 else 11798 return; 11799 } 11800 // All conditions are met. Add a new bitfield to the tail end of ivars. 11801 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11802 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11803 11804 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11805 DeclLoc, DeclLoc, 0, 11806 Context.CharTy, 11807 Context.getTrivialTypeSourceInfo(Context.CharTy, 11808 DeclLoc), 11809 ObjCIvarDecl::Private, BW, 11810 true); 11811 AllIvarDecls.push_back(Ivar); 11812 } 11813 11814 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 11815 ArrayRef<Decl *> Fields, SourceLocation LBrac, 11816 SourceLocation RBrac, AttributeList *Attr) { 11817 assert(EnclosingDecl && "missing record or interface decl"); 11818 11819 // If this is an Objective-C @implementation or category and we have 11820 // new fields here we should reset the layout of the interface since 11821 // it will now change. 11822 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 11823 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 11824 switch (DC->getKind()) { 11825 default: break; 11826 case Decl::ObjCCategory: 11827 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 11828 break; 11829 case Decl::ObjCImplementation: 11830 Context. 11831 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 11832 break; 11833 } 11834 } 11835 11836 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 11837 11838 // Start counting up the number of named members; make sure to include 11839 // members of anonymous structs and unions in the total. 11840 unsigned NumNamedMembers = 0; 11841 if (Record) { 11842 for (RecordDecl::decl_iterator i = Record->decls_begin(), 11843 e = Record->decls_end(); i != e; i++) { 11844 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 11845 if (IFD->getDeclName()) 11846 ++NumNamedMembers; 11847 } 11848 } 11849 11850 // Verify that all the fields are okay. 11851 SmallVector<FieldDecl*, 32> RecFields; 11852 11853 bool ARCErrReported = false; 11854 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 11855 i != end; ++i) { 11856 FieldDecl *FD = cast<FieldDecl>(*i); 11857 11858 // Get the type for the field. 11859 const Type *FDTy = FD->getType().getTypePtr(); 11860 11861 if (!FD->isAnonymousStructOrUnion()) { 11862 // Remember all fields written by the user. 11863 RecFields.push_back(FD); 11864 } 11865 11866 // If the field is already invalid for some reason, don't emit more 11867 // diagnostics about it. 11868 if (FD->isInvalidDecl()) { 11869 EnclosingDecl->setInvalidDecl(); 11870 continue; 11871 } 11872 11873 // C99 6.7.2.1p2: 11874 // A structure or union shall not contain a member with 11875 // incomplete or function type (hence, a structure shall not 11876 // contain an instance of itself, but may contain a pointer to 11877 // an instance of itself), except that the last member of a 11878 // structure with more than one named member may have incomplete 11879 // array type; such a structure (and any union containing, 11880 // possibly recursively, a member that is such a structure) 11881 // shall not be a member of a structure or an element of an 11882 // array. 11883 if (FDTy->isFunctionType()) { 11884 // Field declared as a function. 11885 Diag(FD->getLocation(), diag::err_field_declared_as_function) 11886 << FD->getDeclName(); 11887 FD->setInvalidDecl(); 11888 EnclosingDecl->setInvalidDecl(); 11889 continue; 11890 } else if (FDTy->isIncompleteArrayType() && Record && 11891 ((i + 1 == Fields.end() && !Record->isUnion()) || 11892 ((getLangOpts().MicrosoftExt || 11893 getLangOpts().CPlusPlus) && 11894 (i + 1 == Fields.end() || Record->isUnion())))) { 11895 // Flexible array member. 11896 // Microsoft and g++ is more permissive regarding flexible array. 11897 // It will accept flexible array in union and also 11898 // as the sole element of a struct/class. 11899 unsigned DiagID = 0; 11900 if (Record->isUnion()) 11901 DiagID = getLangOpts().MicrosoftExt 11902 ? diag::ext_flexible_array_union_ms 11903 : getLangOpts().CPlusPlus 11904 ? diag::ext_flexible_array_union_gnu 11905 : diag::err_flexible_array_union; 11906 else if (Fields.size() == 1) 11907 DiagID = getLangOpts().MicrosoftExt 11908 ? diag::ext_flexible_array_empty_aggregate_ms 11909 : getLangOpts().CPlusPlus 11910 ? diag::ext_flexible_array_empty_aggregate_gnu 11911 : NumNamedMembers < 1 11912 ? diag::err_flexible_array_empty_aggregate 11913 : 0; 11914 11915 if (DiagID) 11916 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 11917 << Record->getTagKind(); 11918 // While the layout of types that contain virtual bases is not specified 11919 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 11920 // virtual bases after the derived members. This would make a flexible 11921 // array member declared at the end of an object not adjacent to the end 11922 // of the type. 11923 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 11924 if (RD->getNumVBases() != 0) 11925 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 11926 << FD->getDeclName() << Record->getTagKind(); 11927 if (!getLangOpts().C99) 11928 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11929 << FD->getDeclName() << Record->getTagKind(); 11930 11931 // If the element type has a non-trivial destructor, we would not 11932 // implicitly destroy the elements, so disallow it for now. 11933 // 11934 // FIXME: GCC allows this. We should probably either implicitly delete 11935 // the destructor of the containing class, or just allow this. 11936 QualType BaseElem = Context.getBaseElementType(FD->getType()); 11937 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 11938 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 11939 << FD->getDeclName() << FD->getType(); 11940 FD->setInvalidDecl(); 11941 EnclosingDecl->setInvalidDecl(); 11942 continue; 11943 } 11944 // Okay, we have a legal flexible array member at the end of the struct. 11945 if (Record) 11946 Record->setHasFlexibleArrayMember(true); 11947 } else if (!FDTy->isDependentType() && 11948 RequireCompleteType(FD->getLocation(), FD->getType(), 11949 diag::err_field_incomplete)) { 11950 // Incomplete type 11951 FD->setInvalidDecl(); 11952 EnclosingDecl->setInvalidDecl(); 11953 continue; 11954 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 11955 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 11956 // If this is a member of a union, then entire union becomes "flexible". 11957 if (Record && Record->isUnion()) { 11958 Record->setHasFlexibleArrayMember(true); 11959 } else { 11960 // If this is a struct/class and this is not the last element, reject 11961 // it. Note that GCC supports variable sized arrays in the middle of 11962 // structures. 11963 if (i + 1 != Fields.end()) 11964 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 11965 << FD->getDeclName() << FD->getType(); 11966 else { 11967 // We support flexible arrays at the end of structs in 11968 // other structs as an extension. 11969 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 11970 << FD->getDeclName(); 11971 if (Record) 11972 Record->setHasFlexibleArrayMember(true); 11973 } 11974 } 11975 } 11976 if (isa<ObjCContainerDecl>(EnclosingDecl) && 11977 RequireNonAbstractType(FD->getLocation(), FD->getType(), 11978 diag::err_abstract_type_in_decl, 11979 AbstractIvarType)) { 11980 // Ivars can not have abstract class types 11981 FD->setInvalidDecl(); 11982 } 11983 if (Record && FDTTy->getDecl()->hasObjectMember()) 11984 Record->setHasObjectMember(true); 11985 if (Record && FDTTy->getDecl()->hasVolatileMember()) 11986 Record->setHasVolatileMember(true); 11987 } else if (FDTy->isObjCObjectType()) { 11988 /// A field cannot be an Objective-c object 11989 Diag(FD->getLocation(), diag::err_statically_allocated_object) 11990 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 11991 QualType T = Context.getObjCObjectPointerType(FD->getType()); 11992 FD->setType(T); 11993 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 11994 (!getLangOpts().CPlusPlus || Record->isUnion())) { 11995 // It's an error in ARC if a field has lifetime. 11996 // We don't want to report this in a system header, though, 11997 // so we just make the field unavailable. 11998 // FIXME: that's really not sufficient; we need to make the type 11999 // itself invalid to, say, initialize or copy. 12000 QualType T = FD->getType(); 12001 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12002 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12003 SourceLocation loc = FD->getLocation(); 12004 if (getSourceManager().isInSystemHeader(loc)) { 12005 if (!FD->hasAttr<UnavailableAttr>()) { 12006 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12007 "this system field has retaining ownership", 12008 loc)); 12009 } 12010 } else { 12011 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12012 << T->isBlockPointerType() << Record->getTagKind(); 12013 } 12014 ARCErrReported = true; 12015 } 12016 } else if (getLangOpts().ObjC1 && 12017 getLangOpts().getGC() != LangOptions::NonGC && 12018 Record && !Record->hasObjectMember()) { 12019 if (FD->getType()->isObjCObjectPointerType() || 12020 FD->getType().isObjCGCStrong()) 12021 Record->setHasObjectMember(true); 12022 else if (Context.getAsArrayType(FD->getType())) { 12023 QualType BaseType = Context.getBaseElementType(FD->getType()); 12024 if (BaseType->isRecordType() && 12025 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12026 Record->setHasObjectMember(true); 12027 else if (BaseType->isObjCObjectPointerType() || 12028 BaseType.isObjCGCStrong()) 12029 Record->setHasObjectMember(true); 12030 } 12031 } 12032 if (Record && FD->getType().isVolatileQualified()) 12033 Record->setHasVolatileMember(true); 12034 // Keep track of the number of named members. 12035 if (FD->getIdentifier()) 12036 ++NumNamedMembers; 12037 } 12038 12039 // Okay, we successfully defined 'Record'. 12040 if (Record) { 12041 bool Completed = false; 12042 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12043 if (!CXXRecord->isInvalidDecl()) { 12044 // Set access bits correctly on the directly-declared conversions. 12045 for (CXXRecordDecl::conversion_iterator 12046 I = CXXRecord->conversion_begin(), 12047 E = CXXRecord->conversion_end(); I != E; ++I) 12048 I.setAccess((*I)->getAccess()); 12049 12050 if (!CXXRecord->isDependentType()) { 12051 if (CXXRecord->hasUserDeclaredDestructor()) { 12052 // Adjust user-defined destructor exception spec. 12053 if (getLangOpts().CPlusPlus11) 12054 AdjustDestructorExceptionSpec(CXXRecord, 12055 CXXRecord->getDestructor()); 12056 } 12057 12058 // Add any implicitly-declared members to this class. 12059 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12060 12061 // If we have virtual base classes, we may end up finding multiple 12062 // final overriders for a given virtual function. Check for this 12063 // problem now. 12064 if (CXXRecord->getNumVBases()) { 12065 CXXFinalOverriderMap FinalOverriders; 12066 CXXRecord->getFinalOverriders(FinalOverriders); 12067 12068 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12069 MEnd = FinalOverriders.end(); 12070 M != MEnd; ++M) { 12071 for (OverridingMethods::iterator SO = M->second.begin(), 12072 SOEnd = M->second.end(); 12073 SO != SOEnd; ++SO) { 12074 assert(SO->second.size() > 0 && 12075 "Virtual function without overridding functions?"); 12076 if (SO->second.size() == 1) 12077 continue; 12078 12079 // C++ [class.virtual]p2: 12080 // In a derived class, if a virtual member function of a base 12081 // class subobject has more than one final overrider the 12082 // program is ill-formed. 12083 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12084 << (const NamedDecl *)M->first << Record; 12085 Diag(M->first->getLocation(), 12086 diag::note_overridden_virtual_function); 12087 for (OverridingMethods::overriding_iterator 12088 OM = SO->second.begin(), 12089 OMEnd = SO->second.end(); 12090 OM != OMEnd; ++OM) 12091 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12092 << (const NamedDecl *)M->first << OM->Method->getParent(); 12093 12094 Record->setInvalidDecl(); 12095 } 12096 } 12097 CXXRecord->completeDefinition(&FinalOverriders); 12098 Completed = true; 12099 } 12100 } 12101 } 12102 } 12103 12104 if (!Completed) 12105 Record->completeDefinition(); 12106 12107 if (Record->hasAttrs()) 12108 CheckAlignasUnderalignment(Record); 12109 12110 // Check if the structure/union declaration is a type that can have zero 12111 // size in C. For C this is a language extension, for C++ it may cause 12112 // compatibility problems. 12113 bool CheckForZeroSize; 12114 if (!getLangOpts().CPlusPlus) { 12115 CheckForZeroSize = true; 12116 } else { 12117 // For C++ filter out types that cannot be referenced in C code. 12118 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12119 CheckForZeroSize = 12120 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12121 !CXXRecord->isDependentType() && 12122 CXXRecord->isCLike(); 12123 } 12124 if (CheckForZeroSize) { 12125 bool ZeroSize = true; 12126 bool IsEmpty = true; 12127 unsigned NonBitFields = 0; 12128 for (RecordDecl::field_iterator I = Record->field_begin(), 12129 E = Record->field_end(); 12130 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12131 IsEmpty = false; 12132 if (I->isUnnamedBitfield()) { 12133 if (I->getBitWidthValue(Context) > 0) 12134 ZeroSize = false; 12135 } else { 12136 ++NonBitFields; 12137 QualType FieldType = I->getType(); 12138 if (FieldType->isIncompleteType() || 12139 !Context.getTypeSizeInChars(FieldType).isZero()) 12140 ZeroSize = false; 12141 } 12142 } 12143 12144 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12145 // allowed in C++, but warn if its declaration is inside 12146 // extern "C" block. 12147 if (ZeroSize) { 12148 Diag(RecLoc, getLangOpts().CPlusPlus ? 12149 diag::warn_zero_size_struct_union_in_extern_c : 12150 diag::warn_zero_size_struct_union_compat) 12151 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12152 } 12153 12154 // Structs without named members are extension in C (C99 6.7.2.1p7), 12155 // but are accepted by GCC. 12156 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12157 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12158 diag::ext_no_named_members_in_struct_union) 12159 << Record->isUnion(); 12160 } 12161 } 12162 } else { 12163 ObjCIvarDecl **ClsFields = 12164 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12165 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12166 ID->setEndOfDefinitionLoc(RBrac); 12167 // Add ivar's to class's DeclContext. 12168 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12169 ClsFields[i]->setLexicalDeclContext(ID); 12170 ID->addDecl(ClsFields[i]); 12171 } 12172 // Must enforce the rule that ivars in the base classes may not be 12173 // duplicates. 12174 if (ID->getSuperClass()) 12175 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12176 } else if (ObjCImplementationDecl *IMPDecl = 12177 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12178 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12179 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12180 // Ivar declared in @implementation never belongs to the implementation. 12181 // Only it is in implementation's lexical context. 12182 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12183 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12184 IMPDecl->setIvarLBraceLoc(LBrac); 12185 IMPDecl->setIvarRBraceLoc(RBrac); 12186 } else if (ObjCCategoryDecl *CDecl = 12187 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12188 // case of ivars in class extension; all other cases have been 12189 // reported as errors elsewhere. 12190 // FIXME. Class extension does not have a LocEnd field. 12191 // CDecl->setLocEnd(RBrac); 12192 // Add ivar's to class extension's DeclContext. 12193 // Diagnose redeclaration of private ivars. 12194 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12195 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12196 if (IDecl) { 12197 if (const ObjCIvarDecl *ClsIvar = 12198 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12199 Diag(ClsFields[i]->getLocation(), 12200 diag::err_duplicate_ivar_declaration); 12201 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12202 continue; 12203 } 12204 for (ObjCInterfaceDecl::known_extensions_iterator 12205 Ext = IDecl->known_extensions_begin(), 12206 ExtEnd = IDecl->known_extensions_end(); 12207 Ext != ExtEnd; ++Ext) { 12208 if (const ObjCIvarDecl *ClsExtIvar 12209 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12210 Diag(ClsFields[i]->getLocation(), 12211 diag::err_duplicate_ivar_declaration); 12212 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12213 continue; 12214 } 12215 } 12216 } 12217 ClsFields[i]->setLexicalDeclContext(CDecl); 12218 CDecl->addDecl(ClsFields[i]); 12219 } 12220 CDecl->setIvarLBraceLoc(LBrac); 12221 CDecl->setIvarRBraceLoc(RBrac); 12222 } 12223 } 12224 12225 if (Attr) 12226 ProcessDeclAttributeList(S, Record, Attr); 12227 } 12228 12229 /// \brief Determine whether the given integral value is representable within 12230 /// the given type T. 12231 static bool isRepresentableIntegerValue(ASTContext &Context, 12232 llvm::APSInt &Value, 12233 QualType T) { 12234 assert(T->isIntegralType(Context) && "Integral type required!"); 12235 unsigned BitWidth = Context.getIntWidth(T); 12236 12237 if (Value.isUnsigned() || Value.isNonNegative()) { 12238 if (T->isSignedIntegerOrEnumerationType()) 12239 --BitWidth; 12240 return Value.getActiveBits() <= BitWidth; 12241 } 12242 return Value.getMinSignedBits() <= BitWidth; 12243 } 12244 12245 // \brief Given an integral type, return the next larger integral type 12246 // (or a NULL type of no such type exists). 12247 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12248 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12249 // enum checking below. 12250 assert(T->isIntegralType(Context) && "Integral type required!"); 12251 const unsigned NumTypes = 4; 12252 QualType SignedIntegralTypes[NumTypes] = { 12253 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12254 }; 12255 QualType UnsignedIntegralTypes[NumTypes] = { 12256 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12257 Context.UnsignedLongLongTy 12258 }; 12259 12260 unsigned BitWidth = Context.getTypeSize(T); 12261 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12262 : UnsignedIntegralTypes; 12263 for (unsigned I = 0; I != NumTypes; ++I) 12264 if (Context.getTypeSize(Types[I]) > BitWidth) 12265 return Types[I]; 12266 12267 return QualType(); 12268 } 12269 12270 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12271 EnumConstantDecl *LastEnumConst, 12272 SourceLocation IdLoc, 12273 IdentifierInfo *Id, 12274 Expr *Val) { 12275 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12276 llvm::APSInt EnumVal(IntWidth); 12277 QualType EltTy; 12278 12279 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12280 Val = 0; 12281 12282 if (Val) 12283 Val = DefaultLvalueConversion(Val).take(); 12284 12285 if (Val) { 12286 if (Enum->isDependentType() || Val->isTypeDependent()) 12287 EltTy = Context.DependentTy; 12288 else { 12289 SourceLocation ExpLoc; 12290 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12291 !getLangOpts().MSVCCompat) { 12292 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12293 // constant-expression in the enumerator-definition shall be a converted 12294 // constant expression of the underlying type. 12295 EltTy = Enum->getIntegerType(); 12296 ExprResult Converted = 12297 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12298 CCEK_Enumerator); 12299 if (Converted.isInvalid()) 12300 Val = 0; 12301 else 12302 Val = Converted.take(); 12303 } else if (!Val->isValueDependent() && 12304 !(Val = VerifyIntegerConstantExpression(Val, 12305 &EnumVal).take())) { 12306 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12307 } else { 12308 if (Enum->isFixed()) { 12309 EltTy = Enum->getIntegerType(); 12310 12311 // In Obj-C and Microsoft mode, require the enumeration value to be 12312 // representable in the underlying type of the enumeration. In C++11, 12313 // we perform a non-narrowing conversion as part of converted constant 12314 // expression checking. 12315 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12316 if (getLangOpts().MSVCCompat) { 12317 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12318 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12319 } else 12320 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12321 } else 12322 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12323 } else if (getLangOpts().CPlusPlus) { 12324 // C++11 [dcl.enum]p5: 12325 // If the underlying type is not fixed, the type of each enumerator 12326 // is the type of its initializing value: 12327 // - If an initializer is specified for an enumerator, the 12328 // initializing value has the same type as the expression. 12329 EltTy = Val->getType(); 12330 } else { 12331 // C99 6.7.2.2p2: 12332 // The expression that defines the value of an enumeration constant 12333 // shall be an integer constant expression that has a value 12334 // representable as an int. 12335 12336 // Complain if the value is not representable in an int. 12337 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12338 Diag(IdLoc, diag::ext_enum_value_not_int) 12339 << EnumVal.toString(10) << Val->getSourceRange() 12340 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12341 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12342 // Force the type of the expression to 'int'. 12343 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12344 } 12345 EltTy = Val->getType(); 12346 } 12347 } 12348 } 12349 } 12350 12351 if (!Val) { 12352 if (Enum->isDependentType()) 12353 EltTy = Context.DependentTy; 12354 else if (!LastEnumConst) { 12355 // C++0x [dcl.enum]p5: 12356 // If the underlying type is not fixed, the type of each enumerator 12357 // is the type of its initializing value: 12358 // - If no initializer is specified for the first enumerator, the 12359 // initializing value has an unspecified integral type. 12360 // 12361 // GCC uses 'int' for its unspecified integral type, as does 12362 // C99 6.7.2.2p3. 12363 if (Enum->isFixed()) { 12364 EltTy = Enum->getIntegerType(); 12365 } 12366 else { 12367 EltTy = Context.IntTy; 12368 } 12369 } else { 12370 // Assign the last value + 1. 12371 EnumVal = LastEnumConst->getInitVal(); 12372 ++EnumVal; 12373 EltTy = LastEnumConst->getType(); 12374 12375 // Check for overflow on increment. 12376 if (EnumVal < LastEnumConst->getInitVal()) { 12377 // C++0x [dcl.enum]p5: 12378 // If the underlying type is not fixed, the type of each enumerator 12379 // is the type of its initializing value: 12380 // 12381 // - Otherwise the type of the initializing value is the same as 12382 // the type of the initializing value of the preceding enumerator 12383 // unless the incremented value is not representable in that type, 12384 // in which case the type is an unspecified integral type 12385 // sufficient to contain the incremented value. If no such type 12386 // exists, the program is ill-formed. 12387 QualType T = getNextLargerIntegralType(Context, EltTy); 12388 if (T.isNull() || Enum->isFixed()) { 12389 // There is no integral type larger enough to represent this 12390 // value. Complain, then allow the value to wrap around. 12391 EnumVal = LastEnumConst->getInitVal(); 12392 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12393 ++EnumVal; 12394 if (Enum->isFixed()) 12395 // When the underlying type is fixed, this is ill-formed. 12396 Diag(IdLoc, diag::err_enumerator_wrapped) 12397 << EnumVal.toString(10) 12398 << EltTy; 12399 else 12400 Diag(IdLoc, diag::warn_enumerator_too_large) 12401 << EnumVal.toString(10); 12402 } else { 12403 EltTy = T; 12404 } 12405 12406 // Retrieve the last enumerator's value, extent that type to the 12407 // type that is supposed to be large enough to represent the incremented 12408 // value, then increment. 12409 EnumVal = LastEnumConst->getInitVal(); 12410 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12411 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12412 ++EnumVal; 12413 12414 // If we're not in C++, diagnose the overflow of enumerator values, 12415 // which in C99 means that the enumerator value is not representable in 12416 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12417 // permits enumerator values that are representable in some larger 12418 // integral type. 12419 if (!getLangOpts().CPlusPlus && !T.isNull()) 12420 Diag(IdLoc, diag::warn_enum_value_overflow); 12421 } else if (!getLangOpts().CPlusPlus && 12422 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12423 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12424 Diag(IdLoc, diag::ext_enum_value_not_int) 12425 << EnumVal.toString(10) << 1; 12426 } 12427 } 12428 } 12429 12430 if (!EltTy->isDependentType()) { 12431 // Make the enumerator value match the signedness and size of the 12432 // enumerator's type. 12433 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12434 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12435 } 12436 12437 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12438 Val, EnumVal); 12439 } 12440 12441 12442 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12443 SourceLocation IdLoc, IdentifierInfo *Id, 12444 AttributeList *Attr, 12445 SourceLocation EqualLoc, Expr *Val) { 12446 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12447 EnumConstantDecl *LastEnumConst = 12448 cast_or_null<EnumConstantDecl>(lastEnumConst); 12449 12450 // The scope passed in may not be a decl scope. Zip up the scope tree until 12451 // we find one that is. 12452 S = getNonFieldDeclScope(S); 12453 12454 // Verify that there isn't already something declared with this name in this 12455 // scope. 12456 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12457 ForRedeclaration); 12458 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12459 // Maybe we will complain about the shadowed template parameter. 12460 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12461 // Just pretend that we didn't see the previous declaration. 12462 PrevDecl = 0; 12463 } 12464 12465 if (PrevDecl) { 12466 // When in C++, we may get a TagDecl with the same name; in this case the 12467 // enum constant will 'hide' the tag. 12468 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12469 "Received TagDecl when not in C++!"); 12470 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12471 if (isa<EnumConstantDecl>(PrevDecl)) 12472 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12473 else 12474 Diag(IdLoc, diag::err_redefinition) << Id; 12475 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12476 return 0; 12477 } 12478 } 12479 12480 // C++ [class.mem]p15: 12481 // If T is the name of a class, then each of the following shall have a name 12482 // different from T: 12483 // - every enumerator of every member of class T that is an unscoped 12484 // enumerated type 12485 if (CXXRecordDecl *Record 12486 = dyn_cast<CXXRecordDecl>( 12487 TheEnumDecl->getDeclContext()->getRedeclContext())) 12488 if (!TheEnumDecl->isScoped() && 12489 Record->getIdentifier() && Record->getIdentifier() == Id) 12490 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12491 12492 EnumConstantDecl *New = 12493 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12494 12495 if (New) { 12496 // Process attributes. 12497 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12498 12499 // Register this decl in the current scope stack. 12500 New->setAccess(TheEnumDecl->getAccess()); 12501 PushOnScopeChains(New, S); 12502 } 12503 12504 ActOnDocumentableDecl(New); 12505 12506 return New; 12507 } 12508 12509 // Returns true when the enum initial expression does not trigger the 12510 // duplicate enum warning. A few common cases are exempted as follows: 12511 // Element2 = Element1 12512 // Element2 = Element1 + 1 12513 // Element2 = Element1 - 1 12514 // Where Element2 and Element1 are from the same enum. 12515 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12516 Expr *InitExpr = ECD->getInitExpr(); 12517 if (!InitExpr) 12518 return true; 12519 InitExpr = InitExpr->IgnoreImpCasts(); 12520 12521 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12522 if (!BO->isAdditiveOp()) 12523 return true; 12524 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12525 if (!IL) 12526 return true; 12527 if (IL->getValue() != 1) 12528 return true; 12529 12530 InitExpr = BO->getLHS(); 12531 } 12532 12533 // This checks if the elements are from the same enum. 12534 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12535 if (!DRE) 12536 return true; 12537 12538 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12539 if (!EnumConstant) 12540 return true; 12541 12542 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12543 Enum) 12544 return true; 12545 12546 return false; 12547 } 12548 12549 struct DupKey { 12550 int64_t val; 12551 bool isTombstoneOrEmptyKey; 12552 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12553 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12554 }; 12555 12556 static DupKey GetDupKey(const llvm::APSInt& Val) { 12557 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12558 false); 12559 } 12560 12561 struct DenseMapInfoDupKey { 12562 static DupKey getEmptyKey() { return DupKey(0, true); } 12563 static DupKey getTombstoneKey() { return DupKey(1, true); } 12564 static unsigned getHashValue(const DupKey Key) { 12565 return (unsigned)(Key.val * 37); 12566 } 12567 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12568 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12569 LHS.val == RHS.val; 12570 } 12571 }; 12572 12573 // Emits a warning when an element is implicitly set a value that 12574 // a previous element has already been set to. 12575 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12576 EnumDecl *Enum, 12577 QualType EnumType) { 12578 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12579 Enum->getLocation()) == 12580 DiagnosticsEngine::Ignored) 12581 return; 12582 // Avoid anonymous enums 12583 if (!Enum->getIdentifier()) 12584 return; 12585 12586 // Only check for small enums. 12587 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12588 return; 12589 12590 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12591 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12592 12593 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12594 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12595 ValueToVectorMap; 12596 12597 DuplicatesVector DupVector; 12598 ValueToVectorMap EnumMap; 12599 12600 // Populate the EnumMap with all values represented by enum constants without 12601 // an initialier. 12602 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12603 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12604 12605 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12606 // this constant. Skip this enum since it may be ill-formed. 12607 if (!ECD) { 12608 return; 12609 } 12610 12611 if (ECD->getInitExpr()) 12612 continue; 12613 12614 DupKey Key = GetDupKey(ECD->getInitVal()); 12615 DeclOrVector &Entry = EnumMap[Key]; 12616 12617 // First time encountering this value. 12618 if (Entry.isNull()) 12619 Entry = ECD; 12620 } 12621 12622 // Create vectors for any values that has duplicates. 12623 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12624 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12625 if (!ValidDuplicateEnum(ECD, Enum)) 12626 continue; 12627 12628 DupKey Key = GetDupKey(ECD->getInitVal()); 12629 12630 DeclOrVector& Entry = EnumMap[Key]; 12631 if (Entry.isNull()) 12632 continue; 12633 12634 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12635 // Ensure constants are different. 12636 if (D == ECD) 12637 continue; 12638 12639 // Create new vector and push values onto it. 12640 ECDVector *Vec = new ECDVector(); 12641 Vec->push_back(D); 12642 Vec->push_back(ECD); 12643 12644 // Update entry to point to the duplicates vector. 12645 Entry = Vec; 12646 12647 // Store the vector somewhere we can consult later for quick emission of 12648 // diagnostics. 12649 DupVector.push_back(Vec); 12650 continue; 12651 } 12652 12653 ECDVector *Vec = Entry.get<ECDVector*>(); 12654 // Make sure constants are not added more than once. 12655 if (*Vec->begin() == ECD) 12656 continue; 12657 12658 Vec->push_back(ECD); 12659 } 12660 12661 // Emit diagnostics. 12662 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12663 DupVectorEnd = DupVector.end(); 12664 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12665 ECDVector *Vec = *DupVectorIter; 12666 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12667 12668 // Emit warning for one enum constant. 12669 ECDVector::iterator I = Vec->begin(); 12670 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12671 << (*I)->getName() << (*I)->getInitVal().toString(10) 12672 << (*I)->getSourceRange(); 12673 ++I; 12674 12675 // Emit one note for each of the remaining enum constants with 12676 // the same value. 12677 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12678 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12679 << (*I)->getName() << (*I)->getInitVal().toString(10) 12680 << (*I)->getSourceRange(); 12681 delete Vec; 12682 } 12683 } 12684 12685 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12686 SourceLocation RBraceLoc, Decl *EnumDeclX, 12687 ArrayRef<Decl *> Elements, 12688 Scope *S, AttributeList *Attr) { 12689 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12690 QualType EnumType = Context.getTypeDeclType(Enum); 12691 12692 if (Attr) 12693 ProcessDeclAttributeList(S, Enum, Attr); 12694 12695 if (Enum->isDependentType()) { 12696 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12697 EnumConstantDecl *ECD = 12698 cast_or_null<EnumConstantDecl>(Elements[i]); 12699 if (!ECD) continue; 12700 12701 ECD->setType(EnumType); 12702 } 12703 12704 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12705 return; 12706 } 12707 12708 // TODO: If the result value doesn't fit in an int, it must be a long or long 12709 // long value. ISO C does not support this, but GCC does as an extension, 12710 // emit a warning. 12711 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12712 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12713 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12714 12715 // Verify that all the values are okay, compute the size of the values, and 12716 // reverse the list. 12717 unsigned NumNegativeBits = 0; 12718 unsigned NumPositiveBits = 0; 12719 12720 // Keep track of whether all elements have type int. 12721 bool AllElementsInt = true; 12722 12723 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12724 EnumConstantDecl *ECD = 12725 cast_or_null<EnumConstantDecl>(Elements[i]); 12726 if (!ECD) continue; // Already issued a diagnostic. 12727 12728 const llvm::APSInt &InitVal = ECD->getInitVal(); 12729 12730 // Keep track of the size of positive and negative values. 12731 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12732 NumPositiveBits = std::max(NumPositiveBits, 12733 (unsigned)InitVal.getActiveBits()); 12734 else 12735 NumNegativeBits = std::max(NumNegativeBits, 12736 (unsigned)InitVal.getMinSignedBits()); 12737 12738 // Keep track of whether every enum element has type int (very commmon). 12739 if (AllElementsInt) 12740 AllElementsInt = ECD->getType() == Context.IntTy; 12741 } 12742 12743 // Figure out the type that should be used for this enum. 12744 QualType BestType; 12745 unsigned BestWidth; 12746 12747 // C++0x N3000 [conv.prom]p3: 12748 // An rvalue of an unscoped enumeration type whose underlying 12749 // type is not fixed can be converted to an rvalue of the first 12750 // of the following types that can represent all the values of 12751 // the enumeration: int, unsigned int, long int, unsigned long 12752 // int, long long int, or unsigned long long int. 12753 // C99 6.4.4.3p2: 12754 // An identifier declared as an enumeration constant has type int. 12755 // The C99 rule is modified by a gcc extension 12756 QualType BestPromotionType; 12757 12758 bool Packed = Enum->hasAttr<PackedAttr>(); 12759 // -fshort-enums is the equivalent to specifying the packed attribute on all 12760 // enum definitions. 12761 if (LangOpts.ShortEnums) 12762 Packed = true; 12763 12764 if (Enum->isFixed()) { 12765 BestType = Enum->getIntegerType(); 12766 if (BestType->isPromotableIntegerType()) 12767 BestPromotionType = Context.getPromotedIntegerType(BestType); 12768 else 12769 BestPromotionType = BestType; 12770 // We don't need to set BestWidth, because BestType is going to be the type 12771 // of the enumerators, but we do anyway because otherwise some compilers 12772 // warn that it might be used uninitialized. 12773 BestWidth = CharWidth; 12774 } 12775 else if (NumNegativeBits) { 12776 // If there is a negative value, figure out the smallest integer type (of 12777 // int/long/longlong) that fits. 12778 // If it's packed, check also if it fits a char or a short. 12779 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12780 BestType = Context.SignedCharTy; 12781 BestWidth = CharWidth; 12782 } else if (Packed && NumNegativeBits <= ShortWidth && 12783 NumPositiveBits < ShortWidth) { 12784 BestType = Context.ShortTy; 12785 BestWidth = ShortWidth; 12786 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12787 BestType = Context.IntTy; 12788 BestWidth = IntWidth; 12789 } else { 12790 BestWidth = Context.getTargetInfo().getLongWidth(); 12791 12792 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12793 BestType = Context.LongTy; 12794 } else { 12795 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12796 12797 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12798 Diag(Enum->getLocation(), diag::warn_enum_too_large); 12799 BestType = Context.LongLongTy; 12800 } 12801 } 12802 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12803 } else { 12804 // If there is no negative value, figure out the smallest type that fits 12805 // all of the enumerator values. 12806 // If it's packed, check also if it fits a char or a short. 12807 if (Packed && NumPositiveBits <= CharWidth) { 12808 BestType = Context.UnsignedCharTy; 12809 BestPromotionType = Context.IntTy; 12810 BestWidth = CharWidth; 12811 } else if (Packed && NumPositiveBits <= ShortWidth) { 12812 BestType = Context.UnsignedShortTy; 12813 BestPromotionType = Context.IntTy; 12814 BestWidth = ShortWidth; 12815 } else if (NumPositiveBits <= IntWidth) { 12816 BestType = Context.UnsignedIntTy; 12817 BestWidth = IntWidth; 12818 BestPromotionType 12819 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12820 ? Context.UnsignedIntTy : Context.IntTy; 12821 } else if (NumPositiveBits <= 12822 (BestWidth = Context.getTargetInfo().getLongWidth())) { 12823 BestType = Context.UnsignedLongTy; 12824 BestPromotionType 12825 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12826 ? Context.UnsignedLongTy : Context.LongTy; 12827 } else { 12828 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12829 assert(NumPositiveBits <= BestWidth && 12830 "How could an initializer get larger than ULL?"); 12831 BestType = Context.UnsignedLongLongTy; 12832 BestPromotionType 12833 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12834 ? Context.UnsignedLongLongTy : Context.LongLongTy; 12835 } 12836 } 12837 12838 // Loop over all of the enumerator constants, changing their types to match 12839 // the type of the enum if needed. 12840 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12841 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12842 if (!ECD) continue; // Already issued a diagnostic. 12843 12844 // Standard C says the enumerators have int type, but we allow, as an 12845 // extension, the enumerators to be larger than int size. If each 12846 // enumerator value fits in an int, type it as an int, otherwise type it the 12847 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 12848 // that X has type 'int', not 'unsigned'. 12849 12850 // Determine whether the value fits into an int. 12851 llvm::APSInt InitVal = ECD->getInitVal(); 12852 12853 // If it fits into an integer type, force it. Otherwise force it to match 12854 // the enum decl type. 12855 QualType NewTy; 12856 unsigned NewWidth; 12857 bool NewSign; 12858 if (!getLangOpts().CPlusPlus && 12859 !Enum->isFixed() && 12860 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 12861 NewTy = Context.IntTy; 12862 NewWidth = IntWidth; 12863 NewSign = true; 12864 } else if (ECD->getType() == BestType) { 12865 // Already the right type! 12866 if (getLangOpts().CPlusPlus) 12867 // C++ [dcl.enum]p4: Following the closing brace of an 12868 // enum-specifier, each enumerator has the type of its 12869 // enumeration. 12870 ECD->setType(EnumType); 12871 continue; 12872 } else { 12873 NewTy = BestType; 12874 NewWidth = BestWidth; 12875 NewSign = BestType->isSignedIntegerOrEnumerationType(); 12876 } 12877 12878 // Adjust the APSInt value. 12879 InitVal = InitVal.extOrTrunc(NewWidth); 12880 InitVal.setIsSigned(NewSign); 12881 ECD->setInitVal(InitVal); 12882 12883 // Adjust the Expr initializer and type. 12884 if (ECD->getInitExpr() && 12885 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 12886 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 12887 CK_IntegralCast, 12888 ECD->getInitExpr(), 12889 /*base paths*/ 0, 12890 VK_RValue)); 12891 if (getLangOpts().CPlusPlus) 12892 // C++ [dcl.enum]p4: Following the closing brace of an 12893 // enum-specifier, each enumerator has the type of its 12894 // enumeration. 12895 ECD->setType(EnumType); 12896 else 12897 ECD->setType(NewTy); 12898 } 12899 12900 Enum->completeDefinition(BestType, BestPromotionType, 12901 NumPositiveBits, NumNegativeBits); 12902 12903 // If we're declaring a function, ensure this decl isn't forgotten about - 12904 // it needs to go into the function scope. 12905 if (InFunctionDeclarator) 12906 DeclsInPrototypeScope.push_back(Enum); 12907 12908 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 12909 12910 // Now that the enum type is defined, ensure it's not been underaligned. 12911 if (Enum->hasAttrs()) 12912 CheckAlignasUnderalignment(Enum); 12913 } 12914 12915 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 12916 SourceLocation StartLoc, 12917 SourceLocation EndLoc) { 12918 StringLiteral *AsmString = cast<StringLiteral>(expr); 12919 12920 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 12921 AsmString, StartLoc, 12922 EndLoc); 12923 CurContext->addDecl(New); 12924 return New; 12925 } 12926 12927 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 12928 SourceLocation ImportLoc, 12929 ModuleIdPath Path) { 12930 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 12931 Module::AllVisible, 12932 /*IsIncludeDirective=*/false); 12933 if (!Mod) 12934 return true; 12935 12936 SmallVector<SourceLocation, 2> IdentifierLocs; 12937 Module *ModCheck = Mod; 12938 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 12939 // If we've run out of module parents, just drop the remaining identifiers. 12940 // We need the length to be consistent. 12941 if (!ModCheck) 12942 break; 12943 ModCheck = ModCheck->Parent; 12944 12945 IdentifierLocs.push_back(Path[I].second); 12946 } 12947 12948 ImportDecl *Import = ImportDecl::Create(Context, 12949 Context.getTranslationUnitDecl(), 12950 AtLoc.isValid()? AtLoc : ImportLoc, 12951 Mod, IdentifierLocs); 12952 Context.getTranslationUnitDecl()->addDecl(Import); 12953 return Import; 12954 } 12955 12956 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 12957 // FIXME: Should we synthesize an ImportDecl here? 12958 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 12959 /*Complain=*/true); 12960 } 12961 12962 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 12963 // Create the implicit import declaration. 12964 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 12965 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 12966 Loc, Mod, Loc); 12967 TU->addDecl(ImportD); 12968 Consumer.HandleImplicitImportDecl(ImportD); 12969 12970 // Make the module visible. 12971 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 12972 /*Complain=*/false); 12973 } 12974 12975 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 12976 IdentifierInfo* AliasName, 12977 SourceLocation PragmaLoc, 12978 SourceLocation NameLoc, 12979 SourceLocation AliasNameLoc) { 12980 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 12981 LookupOrdinaryName); 12982 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 12983 AliasName->getName(), 0); 12984 12985 if (PrevDecl) 12986 PrevDecl->addAttr(Attr); 12987 else 12988 (void)ExtnameUndeclaredIdentifiers.insert( 12989 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 12990 } 12991 12992 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 12993 SourceLocation PragmaLoc, 12994 SourceLocation NameLoc) { 12995 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 12996 12997 if (PrevDecl) { 12998 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 12999 } else { 13000 (void)WeakUndeclaredIdentifiers.insert( 13001 std::pair<IdentifierInfo*,WeakInfo> 13002 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 13003 } 13004 } 13005 13006 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13007 IdentifierInfo* AliasName, 13008 SourceLocation PragmaLoc, 13009 SourceLocation NameLoc, 13010 SourceLocation AliasNameLoc) { 13011 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13012 LookupOrdinaryName); 13013 WeakInfo W = WeakInfo(Name, NameLoc); 13014 13015 if (PrevDecl) { 13016 if (!PrevDecl->hasAttr<AliasAttr>()) 13017 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13018 DeclApplyPragmaWeak(TUScope, ND, W); 13019 } else { 13020 (void)WeakUndeclaredIdentifiers.insert( 13021 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13022 } 13023 } 13024 13025 Decl *Sema::getObjCDeclContext() const { 13026 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13027 } 13028 13029 AvailabilityResult Sema::getCurContextAvailability() const { 13030 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13031 // If we are within an Objective-C method, we should consult 13032 // both the availability of the method as well as the 13033 // enclosing class. If the class is (say) deprecated, 13034 // the entire method is considered deprecated from the 13035 // purpose of checking if the current context is deprecated. 13036 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13037 AvailabilityResult R = MD->getAvailability(); 13038 if (R != AR_Available) 13039 return R; 13040 D = MD->getClassInterface(); 13041 } 13042 // If we are within an Objective-c @implementation, it 13043 // gets the same availability context as the @interface. 13044 else if (const ObjCImplementationDecl *ID = 13045 dyn_cast<ObjCImplementationDecl>(D)) { 13046 D = ID->getClassInterface(); 13047 } 13048 return D->getAvailability(); 13049 } 13050