1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex 32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex 33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex 34 #include "clang/Parse/ParseDiagnostic.h" 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/Template.h" 44 #include "llvm/ADT/SmallString.h" 45 #include "llvm/ADT/Triple.h" 46 #include <algorithm> 47 #include <cstring> 48 #include <functional> 49 using namespace clang; 50 using namespace sema; 51 52 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 53 if (OwnedType) { 54 Decl *Group[2] = { OwnedType, Ptr }; 55 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 56 } 57 58 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 59 } 60 61 namespace { 62 63 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 64 public: 65 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false) 66 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) { 67 WantExpressionKeywords = false; 68 WantCXXNamedCasts = false; 69 WantRemainingKeywords = false; 70 } 71 72 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 73 if (NamedDecl *ND = candidate.getCorrectionDecl()) 74 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 75 (AllowInvalidDecl || !ND->isInvalidDecl()); 76 else 77 return !WantClassName && candidate.isKeyword(); 78 } 79 80 private: 81 bool AllowInvalidDecl; 82 bool WantClassName; 83 }; 84 85 } 86 87 /// \brief Determine whether the token kind starts a simple-type-specifier. 88 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 89 switch (Kind) { 90 // FIXME: Take into account the current language when deciding whether a 91 // token kind is a valid type specifier 92 case tok::kw_short: 93 case tok::kw_long: 94 case tok::kw___int64: 95 case tok::kw___int128: 96 case tok::kw_signed: 97 case tok::kw_unsigned: 98 case tok::kw_void: 99 case tok::kw_char: 100 case tok::kw_int: 101 case tok::kw_half: 102 case tok::kw_float: 103 case tok::kw_double: 104 case tok::kw_wchar_t: 105 case tok::kw_bool: 106 case tok::kw___underlying_type: 107 return true; 108 109 case tok::annot_typename: 110 case tok::kw_char16_t: 111 case tok::kw_char32_t: 112 case tok::kw_typeof: 113 case tok::annot_decltype: 114 case tok::kw_decltype: 115 return getLangOpts().CPlusPlus; 116 117 default: 118 break; 119 } 120 121 return false; 122 } 123 124 /// \brief If the identifier refers to a type name within this scope, 125 /// return the declaration of that type. 126 /// 127 /// This routine performs ordinary name lookup of the identifier II 128 /// within the given scope, with optional C++ scope specifier SS, to 129 /// determine whether the name refers to a type. If so, returns an 130 /// opaque pointer (actually a QualType) corresponding to that 131 /// type. Otherwise, returns NULL. 132 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 133 Scope *S, CXXScopeSpec *SS, 134 bool isClassName, bool HasTrailingDot, 135 ParsedType ObjectTypePtr, 136 bool IsCtorOrDtorName, 137 bool WantNontrivialTypeSourceInfo, 138 IdentifierInfo **CorrectedII) { 139 // Determine where we will perform name lookup. 140 DeclContext *LookupCtx = 0; 141 if (ObjectTypePtr) { 142 QualType ObjectType = ObjectTypePtr.get(); 143 if (ObjectType->isRecordType()) 144 LookupCtx = computeDeclContext(ObjectType); 145 } else if (SS && SS->isNotEmpty()) { 146 LookupCtx = computeDeclContext(*SS, false); 147 148 if (!LookupCtx) { 149 if (isDependentScopeSpecifier(*SS)) { 150 // C++ [temp.res]p3: 151 // A qualified-id that refers to a type and in which the 152 // nested-name-specifier depends on a template-parameter (14.6.2) 153 // shall be prefixed by the keyword typename to indicate that the 154 // qualified-id denotes a type, forming an 155 // elaborated-type-specifier (7.1.5.3). 156 // 157 // We therefore do not perform any name lookup if the result would 158 // refer to a member of an unknown specialization. 159 if (!isClassName && !IsCtorOrDtorName) 160 return ParsedType(); 161 162 // We know from the grammar that this name refers to a type, 163 // so build a dependent node to describe the type. 164 if (WantNontrivialTypeSourceInfo) 165 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 166 167 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 168 QualType T = 169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 170 II, NameLoc); 171 172 return ParsedType::make(T); 173 } 174 175 return ParsedType(); 176 } 177 178 if (!LookupCtx->isDependentContext() && 179 RequireCompleteDeclContext(*SS, LookupCtx)) 180 return ParsedType(); 181 } 182 183 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 184 // lookup for class-names. 185 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 186 LookupOrdinaryName; 187 LookupResult Result(*this, &II, NameLoc, Kind); 188 if (LookupCtx) { 189 // Perform "qualified" name lookup into the declaration context we 190 // computed, which is either the type of the base of a member access 191 // expression or the declaration context associated with a prior 192 // nested-name-specifier. 193 LookupQualifiedName(Result, LookupCtx); 194 195 if (ObjectTypePtr && Result.empty()) { 196 // C++ [basic.lookup.classref]p3: 197 // If the unqualified-id is ~type-name, the type-name is looked up 198 // in the context of the entire postfix-expression. If the type T of 199 // the object expression is of a class type C, the type-name is also 200 // looked up in the scope of class C. At least one of the lookups shall 201 // find a name that refers to (possibly cv-qualified) T. 202 LookupName(Result, S); 203 } 204 } else { 205 // Perform unqualified name lookup. 206 LookupName(Result, S); 207 } 208 209 NamedDecl *IIDecl = 0; 210 switch (Result.getResultKind()) { 211 case LookupResult::NotFound: 212 case LookupResult::NotFoundInCurrentInstantiation: 213 if (CorrectedII) { 214 TypeNameValidatorCCC Validator(true, isClassName); 215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 216 Kind, S, SS, Validator); 217 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 218 TemplateTy Template; 219 bool MemberOfUnknownSpecialization; 220 UnqualifiedId TemplateName; 221 TemplateName.setIdentifier(NewII, NameLoc); 222 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 223 CXXScopeSpec NewSS, *NewSSPtr = SS; 224 if (SS && NNS) { 225 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 226 NewSSPtr = &NewSS; 227 } 228 if (Correction && (NNS || NewII != &II) && 229 // Ignore a correction to a template type as the to-be-corrected 230 // identifier is not a template (typo correction for template names 231 // is handled elsewhere). 232 !(getLangOpts().CPlusPlus && NewSSPtr && 233 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 234 false, Template, MemberOfUnknownSpecialization))) { 235 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 236 isClassName, HasTrailingDot, ObjectTypePtr, 237 IsCtorOrDtorName, 238 WantNontrivialTypeSourceInfo); 239 if (Ty) { 240 diagnoseTypo(Correction, 241 PDiag(diag::err_unknown_type_or_class_name_suggest) 242 << Result.getLookupName() << isClassName); 243 if (SS && NNS) 244 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 245 *CorrectedII = NewII; 246 return Ty; 247 } 248 } 249 } 250 // If typo correction failed or was not performed, fall through 251 case LookupResult::FoundOverloaded: 252 case LookupResult::FoundUnresolvedValue: 253 Result.suppressDiagnostics(); 254 return ParsedType(); 255 256 case LookupResult::Ambiguous: 257 // Recover from type-hiding ambiguities by hiding the type. We'll 258 // do the lookup again when looking for an object, and we can 259 // diagnose the error then. If we don't do this, then the error 260 // about hiding the type will be immediately followed by an error 261 // that only makes sense if the identifier was treated like a type. 262 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 263 Result.suppressDiagnostics(); 264 return ParsedType(); 265 } 266 267 // Look to see if we have a type anywhere in the list of results. 268 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 269 Res != ResEnd; ++Res) { 270 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 271 if (!IIDecl || 272 (*Res)->getLocation().getRawEncoding() < 273 IIDecl->getLocation().getRawEncoding()) 274 IIDecl = *Res; 275 } 276 } 277 278 if (!IIDecl) { 279 // None of the entities we found is a type, so there is no way 280 // to even assume that the result is a type. In this case, don't 281 // complain about the ambiguity. The parser will either try to 282 // perform this lookup again (e.g., as an object name), which 283 // will produce the ambiguity, or will complain that it expected 284 // a type name. 285 Result.suppressDiagnostics(); 286 return ParsedType(); 287 } 288 289 // We found a type within the ambiguous lookup; diagnose the 290 // ambiguity and then return that type. This might be the right 291 // answer, or it might not be, but it suppresses any attempt to 292 // perform the name lookup again. 293 break; 294 295 case LookupResult::Found: 296 IIDecl = Result.getFoundDecl(); 297 break; 298 } 299 300 assert(IIDecl && "Didn't find decl"); 301 302 QualType T; 303 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 304 DiagnoseUseOfDecl(IIDecl, NameLoc); 305 306 if (T.isNull()) 307 T = Context.getTypeDeclType(TD); 308 309 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 310 // constructor or destructor name (in such a case, the scope specifier 311 // will be attached to the enclosing Expr or Decl node). 312 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 313 if (WantNontrivialTypeSourceInfo) { 314 // Construct a type with type-source information. 315 TypeLocBuilder Builder; 316 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 317 318 T = getElaboratedType(ETK_None, *SS, T); 319 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 320 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 321 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 322 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 323 } else { 324 T = getElaboratedType(ETK_None, *SS, T); 325 } 326 } 327 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 328 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 329 if (!HasTrailingDot) 330 T = Context.getObjCInterfaceType(IDecl); 331 } 332 333 if (T.isNull()) { 334 // If it's not plausibly a type, suppress diagnostics. 335 Result.suppressDiagnostics(); 336 return ParsedType(); 337 } 338 return ParsedType::make(T); 339 } 340 341 /// isTagName() - This method is called *for error recovery purposes only* 342 /// to determine if the specified name is a valid tag name ("struct foo"). If 343 /// so, this returns the TST for the tag corresponding to it (TST_enum, 344 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 345 /// cases in C where the user forgot to specify the tag. 346 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 347 // Do a tag name lookup in this scope. 348 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 349 LookupName(R, S, false); 350 R.suppressDiagnostics(); 351 if (R.getResultKind() == LookupResult::Found) 352 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 353 switch (TD->getTagKind()) { 354 case TTK_Struct: return DeclSpec::TST_struct; 355 case TTK_Interface: return DeclSpec::TST_interface; 356 case TTK_Union: return DeclSpec::TST_union; 357 case TTK_Class: return DeclSpec::TST_class; 358 case TTK_Enum: return DeclSpec::TST_enum; 359 } 360 } 361 362 return DeclSpec::TST_unspecified; 363 } 364 365 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 366 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 367 /// then downgrade the missing typename error to a warning. 368 /// This is needed for MSVC compatibility; Example: 369 /// @code 370 /// template<class T> class A { 371 /// public: 372 /// typedef int TYPE; 373 /// }; 374 /// template<class T> class B : public A<T> { 375 /// public: 376 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 377 /// }; 378 /// @endcode 379 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 380 if (CurContext->isRecord()) { 381 const Type *Ty = SS->getScopeRep()->getAsType(); 382 383 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 384 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 385 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 386 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 387 return true; 388 return S->isFunctionPrototypeScope(); 389 } 390 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 391 } 392 393 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 394 SourceLocation IILoc, 395 Scope *S, 396 CXXScopeSpec *SS, 397 ParsedType &SuggestedType) { 398 // We don't have anything to suggest (yet). 399 SuggestedType = ParsedType(); 400 401 // There may have been a typo in the name of the type. Look up typo 402 // results, in case we have something that we can suggest. 403 TypeNameValidatorCCC Validator(false); 404 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 405 LookupOrdinaryName, S, SS, 406 Validator)) { 407 if (Corrected.isKeyword()) { 408 // We corrected to a keyword. 409 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 410 II = Corrected.getCorrectionAsIdentifierInfo(); 411 } else { 412 // We found a similarly-named type or interface; suggest that. 413 if (!SS || !SS->isSet()) { 414 diagnoseTypo(Corrected, 415 PDiag(diag::err_unknown_typename_suggest) << II); 416 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 417 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 418 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 419 II->getName().equals(CorrectedStr); 420 diagnoseTypo(Corrected, 421 PDiag(diag::err_unknown_nested_typename_suggest) 422 << II << DC << DroppedSpecifier << SS->getRange()); 423 } else { 424 llvm_unreachable("could not have corrected a typo here"); 425 } 426 427 CXXScopeSpec tmpSS; 428 if (Corrected.getCorrectionSpecifier()) 429 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 430 SourceRange(IILoc)); 431 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 432 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 433 false, ParsedType(), 434 /*IsCtorOrDtorName=*/false, 435 /*NonTrivialTypeSourceInfo=*/true); 436 } 437 return true; 438 } 439 440 if (getLangOpts().CPlusPlus) { 441 // See if II is a class template that the user forgot to pass arguments to. 442 UnqualifiedId Name; 443 Name.setIdentifier(II, IILoc); 444 CXXScopeSpec EmptySS; 445 TemplateTy TemplateResult; 446 bool MemberOfUnknownSpecialization; 447 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 448 Name, ParsedType(), true, TemplateResult, 449 MemberOfUnknownSpecialization) == TNK_Type_template) { 450 TemplateName TplName = TemplateResult.get(); 451 Diag(IILoc, diag::err_template_missing_args) << TplName; 452 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 453 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 454 << TplDecl->getTemplateParameters()->getSourceRange(); 455 } 456 return true; 457 } 458 } 459 460 // FIXME: Should we move the logic that tries to recover from a missing tag 461 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 462 463 if (!SS || (!SS->isSet() && !SS->isInvalid())) 464 Diag(IILoc, diag::err_unknown_typename) << II; 465 else if (DeclContext *DC = computeDeclContext(*SS, false)) 466 Diag(IILoc, diag::err_typename_nested_not_found) 467 << II << DC << SS->getRange(); 468 else if (isDependentScopeSpecifier(*SS)) { 469 unsigned DiagID = diag::err_typename_missing; 470 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 471 DiagID = diag::warn_typename_missing; 472 473 Diag(SS->getRange().getBegin(), DiagID) 474 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName() 475 << SourceRange(SS->getRange().getBegin(), IILoc) 476 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 477 SuggestedType = ActOnTypenameType(S, SourceLocation(), 478 *SS, *II, IILoc).get(); 479 } else { 480 assert(SS && SS->isInvalid() && 481 "Invalid scope specifier has already been diagnosed"); 482 } 483 484 return true; 485 } 486 487 /// \brief Determine whether the given result set contains either a type name 488 /// or 489 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 490 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 491 NextToken.is(tok::less); 492 493 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 494 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 495 return true; 496 497 if (CheckTemplate && isa<TemplateDecl>(*I)) 498 return true; 499 } 500 501 return false; 502 } 503 504 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 505 Scope *S, CXXScopeSpec &SS, 506 IdentifierInfo *&Name, 507 SourceLocation NameLoc) { 508 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 509 SemaRef.LookupParsedName(R, S, &SS); 510 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 511 const char *TagName = 0; 512 const char *FixItTagName = 0; 513 switch (Tag->getTagKind()) { 514 case TTK_Class: 515 TagName = "class"; 516 FixItTagName = "class "; 517 break; 518 519 case TTK_Enum: 520 TagName = "enum"; 521 FixItTagName = "enum "; 522 break; 523 524 case TTK_Struct: 525 TagName = "struct"; 526 FixItTagName = "struct "; 527 break; 528 529 case TTK_Interface: 530 TagName = "__interface"; 531 FixItTagName = "__interface "; 532 break; 533 534 case TTK_Union: 535 TagName = "union"; 536 FixItTagName = "union "; 537 break; 538 } 539 540 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 541 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 542 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 543 544 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 545 I != IEnd; ++I) 546 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 547 << Name << TagName; 548 549 // Replace lookup results with just the tag decl. 550 Result.clear(Sema::LookupTagName); 551 SemaRef.LookupParsedName(Result, S, &SS); 552 return true; 553 } 554 555 return false; 556 } 557 558 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 559 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 560 QualType T, SourceLocation NameLoc) { 561 ASTContext &Context = S.Context; 562 563 TypeLocBuilder Builder; 564 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 565 566 T = S.getElaboratedType(ETK_None, SS, T); 567 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 568 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 569 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 570 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 571 } 572 573 Sema::NameClassification Sema::ClassifyName(Scope *S, 574 CXXScopeSpec &SS, 575 IdentifierInfo *&Name, 576 SourceLocation NameLoc, 577 const Token &NextToken, 578 bool IsAddressOfOperand, 579 CorrectionCandidateCallback *CCC) { 580 DeclarationNameInfo NameInfo(Name, NameLoc); 581 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 582 583 if (NextToken.is(tok::coloncolon)) { 584 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 585 QualType(), false, SS, 0, false); 586 587 } 588 589 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 590 LookupParsedName(Result, S, &SS, !CurMethod); 591 592 // Perform lookup for Objective-C instance variables (including automatically 593 // synthesized instance variables), if we're in an Objective-C method. 594 // FIXME: This lookup really, really needs to be folded in to the normal 595 // unqualified lookup mechanism. 596 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 597 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 598 if (E.get() || E.isInvalid()) 599 return E; 600 } 601 602 bool SecondTry = false; 603 bool IsFilteredTemplateName = false; 604 605 Corrected: 606 switch (Result.getResultKind()) { 607 case LookupResult::NotFound: 608 // If an unqualified-id is followed by a '(', then we have a function 609 // call. 610 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 611 // In C++, this is an ADL-only call. 612 // FIXME: Reference? 613 if (getLangOpts().CPlusPlus) 614 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 615 616 // C90 6.3.2.2: 617 // If the expression that precedes the parenthesized argument list in a 618 // function call consists solely of an identifier, and if no 619 // declaration is visible for this identifier, the identifier is 620 // implicitly declared exactly as if, in the innermost block containing 621 // the function call, the declaration 622 // 623 // extern int identifier (); 624 // 625 // appeared. 626 // 627 // We also allow this in C99 as an extension. 628 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 629 Result.addDecl(D); 630 Result.resolveKind(); 631 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 632 } 633 } 634 635 // In C, we first see whether there is a tag type by the same name, in 636 // which case it's likely that the user just forget to write "enum", 637 // "struct", or "union". 638 if (!getLangOpts().CPlusPlus && !SecondTry && 639 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 640 break; 641 } 642 643 // Perform typo correction to determine if there is another name that is 644 // close to this name. 645 if (!SecondTry && CCC) { 646 SecondTry = true; 647 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 648 Result.getLookupKind(), S, 649 &SS, *CCC)) { 650 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 651 unsigned QualifiedDiag = diag::err_no_member_suggest; 652 653 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 654 NamedDecl *UnderlyingFirstDecl 655 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 656 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 657 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 658 UnqualifiedDiag = diag::err_no_template_suggest; 659 QualifiedDiag = diag::err_no_member_template_suggest; 660 } else if (UnderlyingFirstDecl && 661 (isa<TypeDecl>(UnderlyingFirstDecl) || 662 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 663 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 664 UnqualifiedDiag = diag::err_unknown_typename_suggest; 665 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 666 } 667 668 if (SS.isEmpty()) { 669 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 670 } else {// FIXME: is this even reachable? Test it. 671 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 672 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 673 Name->getName().equals(CorrectedStr); 674 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 675 << Name << computeDeclContext(SS, false) 676 << DroppedSpecifier << SS.getRange()); 677 } 678 679 // Update the name, so that the caller has the new name. 680 Name = Corrected.getCorrectionAsIdentifierInfo(); 681 682 // Typo correction corrected to a keyword. 683 if (Corrected.isKeyword()) 684 return Name; 685 686 // Also update the LookupResult... 687 // FIXME: This should probably go away at some point 688 Result.clear(); 689 Result.setLookupName(Corrected.getCorrection()); 690 if (FirstDecl) 691 Result.addDecl(FirstDecl); 692 693 // If we found an Objective-C instance variable, let 694 // LookupInObjCMethod build the appropriate expression to 695 // reference the ivar. 696 // FIXME: This is a gross hack. 697 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 698 Result.clear(); 699 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 700 return E; 701 } 702 703 goto Corrected; 704 } 705 } 706 707 // We failed to correct; just fall through and let the parser deal with it. 708 Result.suppressDiagnostics(); 709 return NameClassification::Unknown(); 710 711 case LookupResult::NotFoundInCurrentInstantiation: { 712 // We performed name lookup into the current instantiation, and there were 713 // dependent bases, so we treat this result the same way as any other 714 // dependent nested-name-specifier. 715 716 // C++ [temp.res]p2: 717 // A name used in a template declaration or definition and that is 718 // dependent on a template-parameter is assumed not to name a type 719 // unless the applicable name lookup finds a type name or the name is 720 // qualified by the keyword typename. 721 // 722 // FIXME: If the next token is '<', we might want to ask the parser to 723 // perform some heroics to see if we actually have a 724 // template-argument-list, which would indicate a missing 'template' 725 // keyword here. 726 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 727 NameInfo, IsAddressOfOperand, 728 /*TemplateArgs=*/0); 729 } 730 731 case LookupResult::Found: 732 case LookupResult::FoundOverloaded: 733 case LookupResult::FoundUnresolvedValue: 734 break; 735 736 case LookupResult::Ambiguous: 737 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 738 hasAnyAcceptableTemplateNames(Result)) { 739 // C++ [temp.local]p3: 740 // A lookup that finds an injected-class-name (10.2) can result in an 741 // ambiguity in certain cases (for example, if it is found in more than 742 // one base class). If all of the injected-class-names that are found 743 // refer to specializations of the same class template, and if the name 744 // is followed by a template-argument-list, the reference refers to the 745 // class template itself and not a specialization thereof, and is not 746 // ambiguous. 747 // 748 // This filtering can make an ambiguous result into an unambiguous one, 749 // so try again after filtering out template names. 750 FilterAcceptableTemplateNames(Result); 751 if (!Result.isAmbiguous()) { 752 IsFilteredTemplateName = true; 753 break; 754 } 755 } 756 757 // Diagnose the ambiguity and return an error. 758 return NameClassification::Error(); 759 } 760 761 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 762 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 763 // C++ [temp.names]p3: 764 // After name lookup (3.4) finds that a name is a template-name or that 765 // an operator-function-id or a literal- operator-id refers to a set of 766 // overloaded functions any member of which is a function template if 767 // this is followed by a <, the < is always taken as the delimiter of a 768 // template-argument-list and never as the less-than operator. 769 if (!IsFilteredTemplateName) 770 FilterAcceptableTemplateNames(Result); 771 772 if (!Result.empty()) { 773 bool IsFunctionTemplate; 774 bool IsVarTemplate; 775 TemplateName Template; 776 if (Result.end() - Result.begin() > 1) { 777 IsFunctionTemplate = true; 778 Template = Context.getOverloadedTemplateName(Result.begin(), 779 Result.end()); 780 } else { 781 TemplateDecl *TD 782 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 783 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 784 IsVarTemplate = isa<VarTemplateDecl>(TD); 785 786 if (SS.isSet() && !SS.isInvalid()) 787 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 788 /*TemplateKeyword=*/false, 789 TD); 790 else 791 Template = TemplateName(TD); 792 } 793 794 if (IsFunctionTemplate) { 795 // Function templates always go through overload resolution, at which 796 // point we'll perform the various checks (e.g., accessibility) we need 797 // to based on which function we selected. 798 Result.suppressDiagnostics(); 799 800 return NameClassification::FunctionTemplate(Template); 801 } 802 803 return IsVarTemplate ? NameClassification::VarTemplate(Template) 804 : NameClassification::TypeTemplate(Template); 805 } 806 } 807 808 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 809 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 810 DiagnoseUseOfDecl(Type, NameLoc); 811 QualType T = Context.getTypeDeclType(Type); 812 if (SS.isNotEmpty()) 813 return buildNestedType(*this, SS, T, NameLoc); 814 return ParsedType::make(T); 815 } 816 817 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 818 if (!Class) { 819 // FIXME: It's unfortunate that we don't have a Type node for handling this. 820 if (ObjCCompatibleAliasDecl *Alias 821 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 822 Class = Alias->getClassInterface(); 823 } 824 825 if (Class) { 826 DiagnoseUseOfDecl(Class, NameLoc); 827 828 if (NextToken.is(tok::period)) { 829 // Interface. <something> is parsed as a property reference expression. 830 // Just return "unknown" as a fall-through for now. 831 Result.suppressDiagnostics(); 832 return NameClassification::Unknown(); 833 } 834 835 QualType T = Context.getObjCInterfaceType(Class); 836 return ParsedType::make(T); 837 } 838 839 // We can have a type template here if we're classifying a template argument. 840 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 841 return NameClassification::TypeTemplate( 842 TemplateName(cast<TemplateDecl>(FirstDecl))); 843 844 // Check for a tag type hidden by a non-type decl in a few cases where it 845 // seems likely a type is wanted instead of the non-type that was found. 846 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 847 if ((NextToken.is(tok::identifier) || 848 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 849 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 850 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 851 DiagnoseUseOfDecl(Type, NameLoc); 852 QualType T = Context.getTypeDeclType(Type); 853 if (SS.isNotEmpty()) 854 return buildNestedType(*this, SS, T, NameLoc); 855 return ParsedType::make(T); 856 } 857 858 if (FirstDecl->isCXXClassMember()) 859 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 860 861 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 862 return BuildDeclarationNameExpr(SS, Result, ADL); 863 } 864 865 // Determines the context to return to after temporarily entering a 866 // context. This depends in an unnecessarily complicated way on the 867 // exact ordering of callbacks from the parser. 868 DeclContext *Sema::getContainingDC(DeclContext *DC) { 869 870 // Functions defined inline within classes aren't parsed until we've 871 // finished parsing the top-level class, so the top-level class is 872 // the context we'll need to return to. 873 // A Lambda call operator whose parent is a class must not be treated 874 // as an inline member function. A Lambda can be used legally 875 // either as an in-class member initializer or a default argument. These 876 // are parsed once the class has been marked complete and so the containing 877 // context would be the nested class (when the lambda is defined in one); 878 // If the class is not complete, then the lambda is being used in an 879 // ill-formed fashion (such as to specify the width of a bit-field, or 880 // in an array-bound) - in which case we still want to return the 881 // lexically containing DC (which could be a nested class). 882 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 883 DC = DC->getLexicalParent(); 884 885 // A function not defined within a class will always return to its 886 // lexical context. 887 if (!isa<CXXRecordDecl>(DC)) 888 return DC; 889 890 // A C++ inline method/friend is parsed *after* the topmost class 891 // it was declared in is fully parsed ("complete"); the topmost 892 // class is the context we need to return to. 893 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 894 DC = RD; 895 896 // Return the declaration context of the topmost class the inline method is 897 // declared in. 898 return DC; 899 } 900 901 return DC->getLexicalParent(); 902 } 903 904 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 905 assert(getContainingDC(DC) == CurContext && 906 "The next DeclContext should be lexically contained in the current one."); 907 CurContext = DC; 908 S->setEntity(DC); 909 } 910 911 void Sema::PopDeclContext() { 912 assert(CurContext && "DeclContext imbalance!"); 913 914 CurContext = getContainingDC(CurContext); 915 assert(CurContext && "Popped translation unit!"); 916 } 917 918 /// EnterDeclaratorContext - Used when we must lookup names in the context 919 /// of a declarator's nested name specifier. 920 /// 921 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 922 // C++0x [basic.lookup.unqual]p13: 923 // A name used in the definition of a static data member of class 924 // X (after the qualified-id of the static member) is looked up as 925 // if the name was used in a member function of X. 926 // C++0x [basic.lookup.unqual]p14: 927 // If a variable member of a namespace is defined outside of the 928 // scope of its namespace then any name used in the definition of 929 // the variable member (after the declarator-id) is looked up as 930 // if the definition of the variable member occurred in its 931 // namespace. 932 // Both of these imply that we should push a scope whose context 933 // is the semantic context of the declaration. We can't use 934 // PushDeclContext here because that context is not necessarily 935 // lexically contained in the current context. Fortunately, 936 // the containing scope should have the appropriate information. 937 938 assert(!S->getEntity() && "scope already has entity"); 939 940 #ifndef NDEBUG 941 Scope *Ancestor = S->getParent(); 942 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 943 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 944 #endif 945 946 CurContext = DC; 947 S->setEntity(DC); 948 } 949 950 void Sema::ExitDeclaratorContext(Scope *S) { 951 assert(S->getEntity() == CurContext && "Context imbalance!"); 952 953 // Switch back to the lexical context. The safety of this is 954 // enforced by an assert in EnterDeclaratorContext. 955 Scope *Ancestor = S->getParent(); 956 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 957 CurContext = Ancestor->getEntity(); 958 959 // We don't need to do anything with the scope, which is going to 960 // disappear. 961 } 962 963 964 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 965 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 966 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 967 // We assume that the caller has already called 968 // ActOnReenterTemplateScope 969 FD = TFD->getTemplatedDecl(); 970 } 971 if (!FD) 972 return; 973 974 // Same implementation as PushDeclContext, but enters the context 975 // from the lexical parent, rather than the top-level class. 976 assert(CurContext == FD->getLexicalParent() && 977 "The next DeclContext should be lexically contained in the current one."); 978 CurContext = FD; 979 S->setEntity(CurContext); 980 981 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 982 ParmVarDecl *Param = FD->getParamDecl(P); 983 // If the parameter has an identifier, then add it to the scope 984 if (Param->getIdentifier()) { 985 S->AddDecl(Param); 986 IdResolver.AddDecl(Param); 987 } 988 } 989 } 990 991 992 void Sema::ActOnExitFunctionContext() { 993 // Same implementation as PopDeclContext, but returns to the lexical parent, 994 // rather than the top-level class. 995 assert(CurContext && "DeclContext imbalance!"); 996 CurContext = CurContext->getLexicalParent(); 997 assert(CurContext && "Popped translation unit!"); 998 } 999 1000 1001 /// \brief Determine whether we allow overloading of the function 1002 /// PrevDecl with another declaration. 1003 /// 1004 /// This routine determines whether overloading is possible, not 1005 /// whether some new function is actually an overload. It will return 1006 /// true in C++ (where we can always provide overloads) or, as an 1007 /// extension, in C when the previous function is already an 1008 /// overloaded function declaration or has the "overloadable" 1009 /// attribute. 1010 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1011 ASTContext &Context) { 1012 if (Context.getLangOpts().CPlusPlus) 1013 return true; 1014 1015 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1016 return true; 1017 1018 return (Previous.getResultKind() == LookupResult::Found 1019 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1020 } 1021 1022 /// Add this decl to the scope shadowed decl chains. 1023 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1024 // Move up the scope chain until we find the nearest enclosing 1025 // non-transparent context. The declaration will be introduced into this 1026 // scope. 1027 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1028 S = S->getParent(); 1029 1030 // Add scoped declarations into their context, so that they can be 1031 // found later. Declarations without a context won't be inserted 1032 // into any context. 1033 if (AddToContext) 1034 CurContext->addDecl(D); 1035 1036 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1037 // are function-local declarations. 1038 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1039 !D->getDeclContext()->getRedeclContext()->Equals( 1040 D->getLexicalDeclContext()->getRedeclContext()) && 1041 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1042 return; 1043 1044 // Template instantiations should also not be pushed into scope. 1045 if (isa<FunctionDecl>(D) && 1046 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1047 return; 1048 1049 // If this replaces anything in the current scope, 1050 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1051 IEnd = IdResolver.end(); 1052 for (; I != IEnd; ++I) { 1053 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1054 S->RemoveDecl(*I); 1055 IdResolver.RemoveDecl(*I); 1056 1057 // Should only need to replace one decl. 1058 break; 1059 } 1060 } 1061 1062 S->AddDecl(D); 1063 1064 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1065 // Implicitly-generated labels may end up getting generated in an order that 1066 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1067 // the label at the appropriate place in the identifier chain. 1068 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1069 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1070 if (IDC == CurContext) { 1071 if (!S->isDeclScope(*I)) 1072 continue; 1073 } else if (IDC->Encloses(CurContext)) 1074 break; 1075 } 1076 1077 IdResolver.InsertDeclAfter(I, D); 1078 } else { 1079 IdResolver.AddDecl(D); 1080 } 1081 } 1082 1083 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1084 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1085 TUScope->AddDecl(D); 1086 } 1087 1088 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1089 bool AllowInlineNamespace) { 1090 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1091 } 1092 1093 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1094 DeclContext *TargetDC = DC->getPrimaryContext(); 1095 do { 1096 if (DeclContext *ScopeDC = S->getEntity()) 1097 if (ScopeDC->getPrimaryContext() == TargetDC) 1098 return S; 1099 } while ((S = S->getParent())); 1100 1101 return 0; 1102 } 1103 1104 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1105 DeclContext*, 1106 ASTContext&); 1107 1108 /// Filters out lookup results that don't fall within the given scope 1109 /// as determined by isDeclInScope. 1110 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1111 bool ConsiderLinkage, 1112 bool AllowInlineNamespace) { 1113 LookupResult::Filter F = R.makeFilter(); 1114 while (F.hasNext()) { 1115 NamedDecl *D = F.next(); 1116 1117 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1118 continue; 1119 1120 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1121 continue; 1122 1123 F.erase(); 1124 } 1125 1126 F.done(); 1127 } 1128 1129 static bool isUsingDecl(NamedDecl *D) { 1130 return isa<UsingShadowDecl>(D) || 1131 isa<UnresolvedUsingTypenameDecl>(D) || 1132 isa<UnresolvedUsingValueDecl>(D); 1133 } 1134 1135 /// Removes using shadow declarations from the lookup results. 1136 static void RemoveUsingDecls(LookupResult &R) { 1137 LookupResult::Filter F = R.makeFilter(); 1138 while (F.hasNext()) 1139 if (isUsingDecl(F.next())) 1140 F.erase(); 1141 1142 F.done(); 1143 } 1144 1145 /// \brief Check for this common pattern: 1146 /// @code 1147 /// class S { 1148 /// S(const S&); // DO NOT IMPLEMENT 1149 /// void operator=(const S&); // DO NOT IMPLEMENT 1150 /// }; 1151 /// @endcode 1152 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1153 // FIXME: Should check for private access too but access is set after we get 1154 // the decl here. 1155 if (D->doesThisDeclarationHaveABody()) 1156 return false; 1157 1158 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1159 return CD->isCopyConstructor(); 1160 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1161 return Method->isCopyAssignmentOperator(); 1162 return false; 1163 } 1164 1165 // We need this to handle 1166 // 1167 // typedef struct { 1168 // void *foo() { return 0; } 1169 // } A; 1170 // 1171 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1172 // for example. If 'A', foo will have external linkage. If we have '*A', 1173 // foo will have no linkage. Since we can't know until we get to the end 1174 // of the typedef, this function finds out if D might have non-external linkage. 1175 // Callers should verify at the end of the TU if it D has external linkage or 1176 // not. 1177 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1178 const DeclContext *DC = D->getDeclContext(); 1179 while (!DC->isTranslationUnit()) { 1180 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1181 if (!RD->hasNameForLinkage()) 1182 return true; 1183 } 1184 DC = DC->getParent(); 1185 } 1186 1187 return !D->isExternallyVisible(); 1188 } 1189 1190 // FIXME: This needs to be refactored; some other isInMainFile users want 1191 // these semantics. 1192 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1193 if (S.TUKind != TU_Complete) 1194 return false; 1195 return S.SourceMgr.isInMainFile(Loc); 1196 } 1197 1198 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1199 assert(D); 1200 1201 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1202 return false; 1203 1204 // Ignore class templates. 1205 if (D->getDeclContext()->isDependentContext() || 1206 D->getLexicalDeclContext()->isDependentContext()) 1207 return false; 1208 1209 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1210 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1211 return false; 1212 1213 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1214 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1215 return false; 1216 } else { 1217 // 'static inline' functions are defined in headers; don't warn. 1218 if (FD->isInlineSpecified() && 1219 !isMainFileLoc(*this, FD->getLocation())) 1220 return false; 1221 } 1222 1223 if (FD->doesThisDeclarationHaveABody() && 1224 Context.DeclMustBeEmitted(FD)) 1225 return false; 1226 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1227 // Constants and utility variables are defined in headers with internal 1228 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1229 // like "inline".) 1230 if (!isMainFileLoc(*this, VD->getLocation())) 1231 return false; 1232 1233 if (Context.DeclMustBeEmitted(VD)) 1234 return false; 1235 1236 if (VD->isStaticDataMember() && 1237 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1238 return false; 1239 } else { 1240 return false; 1241 } 1242 1243 // Only warn for unused decls internal to the translation unit. 1244 return mightHaveNonExternalLinkage(D); 1245 } 1246 1247 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1248 if (!D) 1249 return; 1250 1251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1252 const FunctionDecl *First = FD->getFirstDecl(); 1253 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1254 return; // First should already be in the vector. 1255 } 1256 1257 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1258 const VarDecl *First = VD->getFirstDecl(); 1259 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1260 return; // First should already be in the vector. 1261 } 1262 1263 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1264 UnusedFileScopedDecls.push_back(D); 1265 } 1266 1267 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1268 if (D->isInvalidDecl()) 1269 return false; 1270 1271 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1272 return false; 1273 1274 if (isa<LabelDecl>(D)) 1275 return true; 1276 1277 // White-list anything that isn't a local variable. 1278 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1279 !D->getDeclContext()->isFunctionOrMethod()) 1280 return false; 1281 1282 // Types of valid local variables should be complete, so this should succeed. 1283 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1284 1285 // White-list anything with an __attribute__((unused)) type. 1286 QualType Ty = VD->getType(); 1287 1288 // Only look at the outermost level of typedef. 1289 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1290 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1291 return false; 1292 } 1293 1294 // If we failed to complete the type for some reason, or if the type is 1295 // dependent, don't diagnose the variable. 1296 if (Ty->isIncompleteType() || Ty->isDependentType()) 1297 return false; 1298 1299 if (const TagType *TT = Ty->getAs<TagType>()) { 1300 const TagDecl *Tag = TT->getDecl(); 1301 if (Tag->hasAttr<UnusedAttr>()) 1302 return false; 1303 1304 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1305 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1306 return false; 1307 1308 if (const Expr *Init = VD->getInit()) { 1309 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1310 Init = Cleanups->getSubExpr(); 1311 const CXXConstructExpr *Construct = 1312 dyn_cast<CXXConstructExpr>(Init); 1313 if (Construct && !Construct->isElidable()) { 1314 CXXConstructorDecl *CD = Construct->getConstructor(); 1315 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1316 return false; 1317 } 1318 } 1319 } 1320 } 1321 1322 // TODO: __attribute__((unused)) templates? 1323 } 1324 1325 return true; 1326 } 1327 1328 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1329 FixItHint &Hint) { 1330 if (isa<LabelDecl>(D)) { 1331 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1332 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1333 if (AfterColon.isInvalid()) 1334 return; 1335 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1336 getCharRange(D->getLocStart(), AfterColon)); 1337 } 1338 return; 1339 } 1340 1341 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1342 /// unless they are marked attr(unused). 1343 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1344 FixItHint Hint; 1345 if (!ShouldDiagnoseUnusedDecl(D)) 1346 return; 1347 1348 GenerateFixForUnusedDecl(D, Context, Hint); 1349 1350 unsigned DiagID; 1351 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1352 DiagID = diag::warn_unused_exception_param; 1353 else if (isa<LabelDecl>(D)) 1354 DiagID = diag::warn_unused_label; 1355 else 1356 DiagID = diag::warn_unused_variable; 1357 1358 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1359 } 1360 1361 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1362 // Verify that we have no forward references left. If so, there was a goto 1363 // or address of a label taken, but no definition of it. Label fwd 1364 // definitions are indicated with a null substmt. 1365 if (L->getStmt() == 0) 1366 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1367 } 1368 1369 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1370 if (S->decl_empty()) return; 1371 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1372 "Scope shouldn't contain decls!"); 1373 1374 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1375 I != E; ++I) { 1376 Decl *TmpD = (*I); 1377 assert(TmpD && "This decl didn't get pushed??"); 1378 1379 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1380 NamedDecl *D = cast<NamedDecl>(TmpD); 1381 1382 if (!D->getDeclName()) continue; 1383 1384 // Diagnose unused variables in this scope. 1385 if (!S->hasUnrecoverableErrorOccurred()) 1386 DiagnoseUnusedDecl(D); 1387 1388 // If this was a forward reference to a label, verify it was defined. 1389 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1390 CheckPoppedLabel(LD, *this); 1391 1392 // Remove this name from our lexical scope. 1393 IdResolver.RemoveDecl(D); 1394 } 1395 DiagnoseUnusedBackingIvarInAccessor(S); 1396 } 1397 1398 void Sema::ActOnStartFunctionDeclarator() { 1399 ++InFunctionDeclarator; 1400 } 1401 1402 void Sema::ActOnEndFunctionDeclarator() { 1403 assert(InFunctionDeclarator); 1404 --InFunctionDeclarator; 1405 } 1406 1407 /// \brief Look for an Objective-C class in the translation unit. 1408 /// 1409 /// \param Id The name of the Objective-C class we're looking for. If 1410 /// typo-correction fixes this name, the Id will be updated 1411 /// to the fixed name. 1412 /// 1413 /// \param IdLoc The location of the name in the translation unit. 1414 /// 1415 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1416 /// if there is no class with the given name. 1417 /// 1418 /// \returns The declaration of the named Objective-C class, or NULL if the 1419 /// class could not be found. 1420 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1421 SourceLocation IdLoc, 1422 bool DoTypoCorrection) { 1423 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1424 // creation from this context. 1425 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1426 1427 if (!IDecl && DoTypoCorrection) { 1428 // Perform typo correction at the given location, but only if we 1429 // find an Objective-C class name. 1430 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1431 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1432 LookupOrdinaryName, TUScope, NULL, 1433 Validator)) { 1434 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1435 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1436 Id = IDecl->getIdentifier(); 1437 } 1438 } 1439 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1440 // This routine must always return a class definition, if any. 1441 if (Def && Def->getDefinition()) 1442 Def = Def->getDefinition(); 1443 return Def; 1444 } 1445 1446 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1447 /// from S, where a non-field would be declared. This routine copes 1448 /// with the difference between C and C++ scoping rules in structs and 1449 /// unions. For example, the following code is well-formed in C but 1450 /// ill-formed in C++: 1451 /// @code 1452 /// struct S6 { 1453 /// enum { BAR } e; 1454 /// }; 1455 /// 1456 /// void test_S6() { 1457 /// struct S6 a; 1458 /// a.e = BAR; 1459 /// } 1460 /// @endcode 1461 /// For the declaration of BAR, this routine will return a different 1462 /// scope. The scope S will be the scope of the unnamed enumeration 1463 /// within S6. In C++, this routine will return the scope associated 1464 /// with S6, because the enumeration's scope is a transparent 1465 /// context but structures can contain non-field names. In C, this 1466 /// routine will return the translation unit scope, since the 1467 /// enumeration's scope is a transparent context and structures cannot 1468 /// contain non-field names. 1469 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1470 while (((S->getFlags() & Scope::DeclScope) == 0) || 1471 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1472 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1473 S = S->getParent(); 1474 return S; 1475 } 1476 1477 /// \brief Looks up the declaration of "struct objc_super" and 1478 /// saves it for later use in building builtin declaration of 1479 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1480 /// pre-existing declaration exists no action takes place. 1481 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1482 IdentifierInfo *II) { 1483 if (!II->isStr("objc_msgSendSuper")) 1484 return; 1485 ASTContext &Context = ThisSema.Context; 1486 1487 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1488 SourceLocation(), Sema::LookupTagName); 1489 ThisSema.LookupName(Result, S); 1490 if (Result.getResultKind() == LookupResult::Found) 1491 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1492 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1493 } 1494 1495 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1496 /// file scope. lazily create a decl for it. ForRedeclaration is true 1497 /// if we're creating this built-in in anticipation of redeclaring the 1498 /// built-in. 1499 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1500 Scope *S, bool ForRedeclaration, 1501 SourceLocation Loc) { 1502 LookupPredefedObjCSuperType(*this, S, II); 1503 1504 Builtin::ID BID = (Builtin::ID)bid; 1505 1506 ASTContext::GetBuiltinTypeError Error; 1507 QualType R = Context.GetBuiltinType(BID, Error); 1508 switch (Error) { 1509 case ASTContext::GE_None: 1510 // Okay 1511 break; 1512 1513 case ASTContext::GE_Missing_stdio: 1514 if (ForRedeclaration) 1515 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1516 << Context.BuiltinInfo.GetName(BID); 1517 return 0; 1518 1519 case ASTContext::GE_Missing_setjmp: 1520 if (ForRedeclaration) 1521 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1522 << Context.BuiltinInfo.GetName(BID); 1523 return 0; 1524 1525 case ASTContext::GE_Missing_ucontext: 1526 if (ForRedeclaration) 1527 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1528 << Context.BuiltinInfo.GetName(BID); 1529 return 0; 1530 } 1531 1532 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1533 Diag(Loc, diag::ext_implicit_lib_function_decl) 1534 << Context.BuiltinInfo.GetName(BID) 1535 << R; 1536 if (Context.BuiltinInfo.getHeaderName(BID) && 1537 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1538 != DiagnosticsEngine::Ignored) 1539 Diag(Loc, diag::note_please_include_header) 1540 << Context.BuiltinInfo.getHeaderName(BID) 1541 << Context.BuiltinInfo.GetName(BID); 1542 } 1543 1544 DeclContext *Parent = Context.getTranslationUnitDecl(); 1545 if (getLangOpts().CPlusPlus) { 1546 LinkageSpecDecl *CLinkageDecl = 1547 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1548 LinkageSpecDecl::lang_c, false); 1549 CLinkageDecl->setImplicit(); 1550 Parent->addDecl(CLinkageDecl); 1551 Parent = CLinkageDecl; 1552 } 1553 1554 FunctionDecl *New = FunctionDecl::Create(Context, 1555 Parent, 1556 Loc, Loc, II, R, /*TInfo=*/0, 1557 SC_Extern, 1558 false, 1559 /*hasPrototype=*/true); 1560 New->setImplicit(); 1561 1562 // Create Decl objects for each parameter, adding them to the 1563 // FunctionDecl. 1564 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1565 SmallVector<ParmVarDecl*, 16> Params; 1566 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1567 ParmVarDecl *parm = 1568 ParmVarDecl::Create(Context, New, SourceLocation(), 1569 SourceLocation(), 0, 1570 FT->getArgType(i), /*TInfo=*/0, 1571 SC_None, 0); 1572 parm->setScopeInfo(0, i); 1573 Params.push_back(parm); 1574 } 1575 New->setParams(Params); 1576 } 1577 1578 AddKnownFunctionAttributes(New); 1579 RegisterLocallyScopedExternCDecl(New, S); 1580 1581 // TUScope is the translation-unit scope to insert this function into. 1582 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1583 // relate Scopes to DeclContexts, and probably eliminate CurContext 1584 // entirely, but we're not there yet. 1585 DeclContext *SavedContext = CurContext; 1586 CurContext = Parent; 1587 PushOnScopeChains(New, TUScope); 1588 CurContext = SavedContext; 1589 return New; 1590 } 1591 1592 /// \brief Filter out any previous declarations that the given declaration 1593 /// should not consider because they are not permitted to conflict, e.g., 1594 /// because they come from hidden sub-modules and do not refer to the same 1595 /// entity. 1596 static void filterNonConflictingPreviousDecls(ASTContext &context, 1597 NamedDecl *decl, 1598 LookupResult &previous){ 1599 // This is only interesting when modules are enabled. 1600 if (!context.getLangOpts().Modules) 1601 return; 1602 1603 // Empty sets are uninteresting. 1604 if (previous.empty()) 1605 return; 1606 1607 LookupResult::Filter filter = previous.makeFilter(); 1608 while (filter.hasNext()) { 1609 NamedDecl *old = filter.next(); 1610 1611 // Non-hidden declarations are never ignored. 1612 if (!old->isHidden()) 1613 continue; 1614 1615 if (!old->isExternallyVisible()) 1616 filter.erase(); 1617 } 1618 1619 filter.done(); 1620 } 1621 1622 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1623 QualType OldType; 1624 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1625 OldType = OldTypedef->getUnderlyingType(); 1626 else 1627 OldType = Context.getTypeDeclType(Old); 1628 QualType NewType = New->getUnderlyingType(); 1629 1630 if (NewType->isVariablyModifiedType()) { 1631 // Must not redefine a typedef with a variably-modified type. 1632 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1633 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1634 << Kind << NewType; 1635 if (Old->getLocation().isValid()) 1636 Diag(Old->getLocation(), diag::note_previous_definition); 1637 New->setInvalidDecl(); 1638 return true; 1639 } 1640 1641 if (OldType != NewType && 1642 !OldType->isDependentType() && 1643 !NewType->isDependentType() && 1644 !Context.hasSameType(OldType, NewType)) { 1645 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1646 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1647 << Kind << NewType << OldType; 1648 if (Old->getLocation().isValid()) 1649 Diag(Old->getLocation(), diag::note_previous_definition); 1650 New->setInvalidDecl(); 1651 return true; 1652 } 1653 return false; 1654 } 1655 1656 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1657 /// same name and scope as a previous declaration 'Old'. Figure out 1658 /// how to resolve this situation, merging decls or emitting 1659 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1660 /// 1661 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1662 // If the new decl is known invalid already, don't bother doing any 1663 // merging checks. 1664 if (New->isInvalidDecl()) return; 1665 1666 // Allow multiple definitions for ObjC built-in typedefs. 1667 // FIXME: Verify the underlying types are equivalent! 1668 if (getLangOpts().ObjC1) { 1669 const IdentifierInfo *TypeID = New->getIdentifier(); 1670 switch (TypeID->getLength()) { 1671 default: break; 1672 case 2: 1673 { 1674 if (!TypeID->isStr("id")) 1675 break; 1676 QualType T = New->getUnderlyingType(); 1677 if (!T->isPointerType()) 1678 break; 1679 if (!T->isVoidPointerType()) { 1680 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1681 if (!PT->isStructureType()) 1682 break; 1683 } 1684 Context.setObjCIdRedefinitionType(T); 1685 // Install the built-in type for 'id', ignoring the current definition. 1686 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1687 return; 1688 } 1689 case 5: 1690 if (!TypeID->isStr("Class")) 1691 break; 1692 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1693 // Install the built-in type for 'Class', ignoring the current definition. 1694 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1695 return; 1696 case 3: 1697 if (!TypeID->isStr("SEL")) 1698 break; 1699 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1700 // Install the built-in type for 'SEL', ignoring the current definition. 1701 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1702 return; 1703 } 1704 // Fall through - the typedef name was not a builtin type. 1705 } 1706 1707 // Verify the old decl was also a type. 1708 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1709 if (!Old) { 1710 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1711 << New->getDeclName(); 1712 1713 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1714 if (OldD->getLocation().isValid()) 1715 Diag(OldD->getLocation(), diag::note_previous_definition); 1716 1717 return New->setInvalidDecl(); 1718 } 1719 1720 // If the old declaration is invalid, just give up here. 1721 if (Old->isInvalidDecl()) 1722 return New->setInvalidDecl(); 1723 1724 // If the typedef types are not identical, reject them in all languages and 1725 // with any extensions enabled. 1726 if (isIncompatibleTypedef(Old, New)) 1727 return; 1728 1729 // The types match. Link up the redeclaration chain and merge attributes if 1730 // the old declaration was a typedef. 1731 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1732 New->setPreviousDecl(Typedef); 1733 mergeDeclAttributes(New, Old); 1734 } 1735 1736 if (getLangOpts().MicrosoftExt) 1737 return; 1738 1739 if (getLangOpts().CPlusPlus) { 1740 // C++ [dcl.typedef]p2: 1741 // In a given non-class scope, a typedef specifier can be used to 1742 // redefine the name of any type declared in that scope to refer 1743 // to the type to which it already refers. 1744 if (!isa<CXXRecordDecl>(CurContext)) 1745 return; 1746 1747 // C++0x [dcl.typedef]p4: 1748 // In a given class scope, a typedef specifier can be used to redefine 1749 // any class-name declared in that scope that is not also a typedef-name 1750 // to refer to the type to which it already refers. 1751 // 1752 // This wording came in via DR424, which was a correction to the 1753 // wording in DR56, which accidentally banned code like: 1754 // 1755 // struct S { 1756 // typedef struct A { } A; 1757 // }; 1758 // 1759 // in the C++03 standard. We implement the C++0x semantics, which 1760 // allow the above but disallow 1761 // 1762 // struct S { 1763 // typedef int I; 1764 // typedef int I; 1765 // }; 1766 // 1767 // since that was the intent of DR56. 1768 if (!isa<TypedefNameDecl>(Old)) 1769 return; 1770 1771 Diag(New->getLocation(), diag::err_redefinition) 1772 << New->getDeclName(); 1773 Diag(Old->getLocation(), diag::note_previous_definition); 1774 return New->setInvalidDecl(); 1775 } 1776 1777 // Modules always permit redefinition of typedefs, as does C11. 1778 if (getLangOpts().Modules || getLangOpts().C11) 1779 return; 1780 1781 // If we have a redefinition of a typedef in C, emit a warning. This warning 1782 // is normally mapped to an error, but can be controlled with 1783 // -Wtypedef-redefinition. If either the original or the redefinition is 1784 // in a system header, don't emit this for compatibility with GCC. 1785 if (getDiagnostics().getSuppressSystemWarnings() && 1786 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1787 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1788 return; 1789 1790 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1791 << New->getDeclName(); 1792 Diag(Old->getLocation(), diag::note_previous_definition); 1793 return; 1794 } 1795 1796 /// DeclhasAttr - returns true if decl Declaration already has the target 1797 /// attribute. 1798 static bool 1799 DeclHasAttr(const Decl *D, const Attr *A) { 1800 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1801 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1802 // responsible for making sure they are consistent. 1803 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1804 if (AA) 1805 return false; 1806 1807 // The following thread safety attributes can also be duplicated. 1808 switch (A->getKind()) { 1809 case attr::ExclusiveLocksRequired: 1810 case attr::SharedLocksRequired: 1811 case attr::LocksExcluded: 1812 case attr::ExclusiveLockFunction: 1813 case attr::SharedLockFunction: 1814 case attr::UnlockFunction: 1815 case attr::ExclusiveTrylockFunction: 1816 case attr::SharedTrylockFunction: 1817 case attr::GuardedBy: 1818 case attr::PtGuardedBy: 1819 case attr::AcquiredBefore: 1820 case attr::AcquiredAfter: 1821 return false; 1822 default: 1823 ; 1824 } 1825 1826 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1827 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1828 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1829 if ((*i)->getKind() == A->getKind()) { 1830 if (Ann) { 1831 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1832 return true; 1833 continue; 1834 } 1835 // FIXME: Don't hardcode this check 1836 if (OA && isa<OwnershipAttr>(*i)) 1837 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1838 return true; 1839 } 1840 1841 return false; 1842 } 1843 1844 static bool isAttributeTargetADefinition(Decl *D) { 1845 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1846 return VD->isThisDeclarationADefinition(); 1847 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1848 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1849 return true; 1850 } 1851 1852 /// Merge alignment attributes from \p Old to \p New, taking into account the 1853 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1854 /// 1855 /// \return \c true if any attributes were added to \p New. 1856 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1857 // Look for alignas attributes on Old, and pick out whichever attribute 1858 // specifies the strictest alignment requirement. 1859 AlignedAttr *OldAlignasAttr = 0; 1860 AlignedAttr *OldStrictestAlignAttr = 0; 1861 unsigned OldAlign = 0; 1862 for (specific_attr_iterator<AlignedAttr> 1863 I = Old->specific_attr_begin<AlignedAttr>(), 1864 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1865 // FIXME: We have no way of representing inherited dependent alignments 1866 // in a case like: 1867 // template<int A, int B> struct alignas(A) X; 1868 // template<int A, int B> struct alignas(B) X {}; 1869 // For now, we just ignore any alignas attributes which are not on the 1870 // definition in such a case. 1871 if (I->isAlignmentDependent()) 1872 return false; 1873 1874 if (I->isAlignas()) 1875 OldAlignasAttr = *I; 1876 1877 unsigned Align = I->getAlignment(S.Context); 1878 if (Align > OldAlign) { 1879 OldAlign = Align; 1880 OldStrictestAlignAttr = *I; 1881 } 1882 } 1883 1884 // Look for alignas attributes on New. 1885 AlignedAttr *NewAlignasAttr = 0; 1886 unsigned NewAlign = 0; 1887 for (specific_attr_iterator<AlignedAttr> 1888 I = New->specific_attr_begin<AlignedAttr>(), 1889 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1890 if (I->isAlignmentDependent()) 1891 return false; 1892 1893 if (I->isAlignas()) 1894 NewAlignasAttr = *I; 1895 1896 unsigned Align = I->getAlignment(S.Context); 1897 if (Align > NewAlign) 1898 NewAlign = Align; 1899 } 1900 1901 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1902 // Both declarations have 'alignas' attributes. We require them to match. 1903 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1904 // fall short. (If two declarations both have alignas, they must both match 1905 // every definition, and so must match each other if there is a definition.) 1906 1907 // If either declaration only contains 'alignas(0)' specifiers, then it 1908 // specifies the natural alignment for the type. 1909 if (OldAlign == 0 || NewAlign == 0) { 1910 QualType Ty; 1911 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1912 Ty = VD->getType(); 1913 else 1914 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1915 1916 if (OldAlign == 0) 1917 OldAlign = S.Context.getTypeAlign(Ty); 1918 if (NewAlign == 0) 1919 NewAlign = S.Context.getTypeAlign(Ty); 1920 } 1921 1922 if (OldAlign != NewAlign) { 1923 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1924 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1925 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1926 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1927 } 1928 } 1929 1930 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1931 // C++11 [dcl.align]p6: 1932 // if any declaration of an entity has an alignment-specifier, 1933 // every defining declaration of that entity shall specify an 1934 // equivalent alignment. 1935 // C11 6.7.5/7: 1936 // If the definition of an object does not have an alignment 1937 // specifier, any other declaration of that object shall also 1938 // have no alignment specifier. 1939 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1940 << OldAlignasAttr->isC11(); 1941 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1942 << OldAlignasAttr->isC11(); 1943 } 1944 1945 bool AnyAdded = false; 1946 1947 // Ensure we have an attribute representing the strictest alignment. 1948 if (OldAlign > NewAlign) { 1949 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1950 Clone->setInherited(true); 1951 New->addAttr(Clone); 1952 AnyAdded = true; 1953 } 1954 1955 // Ensure we have an alignas attribute if the old declaration had one. 1956 if (OldAlignasAttr && !NewAlignasAttr && 1957 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1958 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1959 Clone->setInherited(true); 1960 New->addAttr(Clone); 1961 AnyAdded = true; 1962 } 1963 1964 return AnyAdded; 1965 } 1966 1967 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1968 bool Override) { 1969 InheritableAttr *NewAttr = NULL; 1970 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1971 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1972 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1973 AA->getIntroduced(), AA->getDeprecated(), 1974 AA->getObsoleted(), AA->getUnavailable(), 1975 AA->getMessage(), Override, 1976 AttrSpellingListIndex); 1977 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1978 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1979 AttrSpellingListIndex); 1980 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1981 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1982 AttrSpellingListIndex); 1983 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1984 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1985 AttrSpellingListIndex); 1986 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1987 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1988 AttrSpellingListIndex); 1989 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1990 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1991 FA->getFormatIdx(), FA->getFirstArg(), 1992 AttrSpellingListIndex); 1993 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1994 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1995 AttrSpellingListIndex); 1996 else if (isa<AlignedAttr>(Attr)) 1997 // AlignedAttrs are handled separately, because we need to handle all 1998 // such attributes on a declaration at the same time. 1999 NewAttr = 0; 2000 else if (!DeclHasAttr(D, Attr)) 2001 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2002 2003 if (NewAttr) { 2004 NewAttr->setInherited(true); 2005 D->addAttr(NewAttr); 2006 return true; 2007 } 2008 2009 return false; 2010 } 2011 2012 static const Decl *getDefinition(const Decl *D) { 2013 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2014 return TD->getDefinition(); 2015 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2016 const VarDecl *Def = VD->getDefinition(); 2017 if (Def) 2018 return Def; 2019 return VD->getActingDefinition(); 2020 } 2021 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2022 const FunctionDecl* Def; 2023 if (FD->isDefined(Def)) 2024 return Def; 2025 } 2026 return NULL; 2027 } 2028 2029 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2030 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2031 I != E; ++I) { 2032 Attr *Attribute = *I; 2033 if (Attribute->getKind() == Kind) 2034 return true; 2035 } 2036 return false; 2037 } 2038 2039 /// checkNewAttributesAfterDef - If we already have a definition, check that 2040 /// there are no new attributes in this declaration. 2041 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2042 if (!New->hasAttrs()) 2043 return; 2044 2045 const Decl *Def = getDefinition(Old); 2046 if (!Def || Def == New) 2047 return; 2048 2049 AttrVec &NewAttributes = New->getAttrs(); 2050 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2051 const Attr *NewAttribute = NewAttributes[I]; 2052 2053 if (isa<AliasAttr>(NewAttribute)) { 2054 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2055 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2056 else { 2057 VarDecl *VD = cast<VarDecl>(New); 2058 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2059 VarDecl::TentativeDefinition 2060 ? diag::err_alias_after_tentative 2061 : diag::err_redefinition; 2062 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2063 S.Diag(Def->getLocation(), diag::note_previous_definition); 2064 VD->setInvalidDecl(); 2065 } 2066 ++I; 2067 continue; 2068 } 2069 2070 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2071 // Tentative definitions are only interesting for the alias check above. 2072 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2073 ++I; 2074 continue; 2075 } 2076 } 2077 2078 if (hasAttribute(Def, NewAttribute->getKind())) { 2079 ++I; 2080 continue; // regular attr merging will take care of validating this. 2081 } 2082 2083 if (isa<C11NoReturnAttr>(NewAttribute)) { 2084 // C's _Noreturn is allowed to be added to a function after it is defined. 2085 ++I; 2086 continue; 2087 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2088 if (AA->isAlignas()) { 2089 // C++11 [dcl.align]p6: 2090 // if any declaration of an entity has an alignment-specifier, 2091 // every defining declaration of that entity shall specify an 2092 // equivalent alignment. 2093 // C11 6.7.5/7: 2094 // If the definition of an object does not have an alignment 2095 // specifier, any other declaration of that object shall also 2096 // have no alignment specifier. 2097 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2098 << AA->isC11(); 2099 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2100 << AA->isC11(); 2101 NewAttributes.erase(NewAttributes.begin() + I); 2102 --E; 2103 continue; 2104 } 2105 } 2106 2107 S.Diag(NewAttribute->getLocation(), 2108 diag::warn_attribute_precede_definition); 2109 S.Diag(Def->getLocation(), diag::note_previous_definition); 2110 NewAttributes.erase(NewAttributes.begin() + I); 2111 --E; 2112 } 2113 } 2114 2115 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2116 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2117 AvailabilityMergeKind AMK) { 2118 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2119 UsedAttr *NewAttr = OldAttr->clone(Context); 2120 NewAttr->setInherited(true); 2121 New->addAttr(NewAttr); 2122 } 2123 2124 if (!Old->hasAttrs() && !New->hasAttrs()) 2125 return; 2126 2127 // attributes declared post-definition are currently ignored 2128 checkNewAttributesAfterDef(*this, New, Old); 2129 2130 if (!Old->hasAttrs()) 2131 return; 2132 2133 bool foundAny = New->hasAttrs(); 2134 2135 // Ensure that any moving of objects within the allocated map is done before 2136 // we process them. 2137 if (!foundAny) New->setAttrs(AttrVec()); 2138 2139 for (specific_attr_iterator<InheritableAttr> 2140 i = Old->specific_attr_begin<InheritableAttr>(), 2141 e = Old->specific_attr_end<InheritableAttr>(); 2142 i != e; ++i) { 2143 bool Override = false; 2144 // Ignore deprecated/unavailable/availability attributes if requested. 2145 if (isa<DeprecatedAttr>(*i) || 2146 isa<UnavailableAttr>(*i) || 2147 isa<AvailabilityAttr>(*i)) { 2148 switch (AMK) { 2149 case AMK_None: 2150 continue; 2151 2152 case AMK_Redeclaration: 2153 break; 2154 2155 case AMK_Override: 2156 Override = true; 2157 break; 2158 } 2159 } 2160 2161 // Already handled. 2162 if (isa<UsedAttr>(*i)) 2163 continue; 2164 2165 if (mergeDeclAttribute(*this, New, *i, Override)) 2166 foundAny = true; 2167 } 2168 2169 if (mergeAlignedAttrs(*this, New, Old)) 2170 foundAny = true; 2171 2172 if (!foundAny) New->dropAttrs(); 2173 } 2174 2175 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2176 /// to the new one. 2177 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2178 const ParmVarDecl *oldDecl, 2179 Sema &S) { 2180 // C++11 [dcl.attr.depend]p2: 2181 // The first declaration of a function shall specify the 2182 // carries_dependency attribute for its declarator-id if any declaration 2183 // of the function specifies the carries_dependency attribute. 2184 if (newDecl->hasAttr<CarriesDependencyAttr>() && 2185 !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2186 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(), 2187 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2188 // Find the first declaration of the parameter. 2189 // FIXME: Should we build redeclaration chains for function parameters? 2190 const FunctionDecl *FirstFD = 2191 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2192 const ParmVarDecl *FirstVD = 2193 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2194 S.Diag(FirstVD->getLocation(), 2195 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2196 } 2197 2198 if (!oldDecl->hasAttrs()) 2199 return; 2200 2201 bool foundAny = newDecl->hasAttrs(); 2202 2203 // Ensure that any moving of objects within the allocated map is 2204 // done before we process them. 2205 if (!foundAny) newDecl->setAttrs(AttrVec()); 2206 2207 for (specific_attr_iterator<InheritableParamAttr> 2208 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2209 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2210 if (!DeclHasAttr(newDecl, *i)) { 2211 InheritableAttr *newAttr = 2212 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2213 newAttr->setInherited(true); 2214 newDecl->addAttr(newAttr); 2215 foundAny = true; 2216 } 2217 } 2218 2219 if (!foundAny) newDecl->dropAttrs(); 2220 } 2221 2222 namespace { 2223 2224 /// Used in MergeFunctionDecl to keep track of function parameters in 2225 /// C. 2226 struct GNUCompatibleParamWarning { 2227 ParmVarDecl *OldParm; 2228 ParmVarDecl *NewParm; 2229 QualType PromotedType; 2230 }; 2231 2232 } 2233 2234 /// getSpecialMember - get the special member enum for a method. 2235 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2236 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2237 if (Ctor->isDefaultConstructor()) 2238 return Sema::CXXDefaultConstructor; 2239 2240 if (Ctor->isCopyConstructor()) 2241 return Sema::CXXCopyConstructor; 2242 2243 if (Ctor->isMoveConstructor()) 2244 return Sema::CXXMoveConstructor; 2245 } else if (isa<CXXDestructorDecl>(MD)) { 2246 return Sema::CXXDestructor; 2247 } else if (MD->isCopyAssignmentOperator()) { 2248 return Sema::CXXCopyAssignment; 2249 } else if (MD->isMoveAssignmentOperator()) { 2250 return Sema::CXXMoveAssignment; 2251 } 2252 2253 return Sema::CXXInvalid; 2254 } 2255 2256 /// canRedefineFunction - checks if a function can be redefined. Currently, 2257 /// only extern inline functions can be redefined, and even then only in 2258 /// GNU89 mode. 2259 static bool canRedefineFunction(const FunctionDecl *FD, 2260 const LangOptions& LangOpts) { 2261 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2262 !LangOpts.CPlusPlus && 2263 FD->isInlineSpecified() && 2264 FD->getStorageClass() == SC_Extern); 2265 } 2266 2267 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2268 const AttributedType *AT = T->getAs<AttributedType>(); 2269 while (AT && !AT->isCallingConv()) 2270 AT = AT->getModifiedType()->getAs<AttributedType>(); 2271 return AT; 2272 } 2273 2274 template <typename T> 2275 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2276 const DeclContext *DC = Old->getDeclContext(); 2277 if (DC->isRecord()) 2278 return false; 2279 2280 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2281 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2282 return true; 2283 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2284 return true; 2285 return false; 2286 } 2287 2288 /// MergeFunctionDecl - We just parsed a function 'New' from 2289 /// declarator D which has the same name and scope as a previous 2290 /// declaration 'Old'. Figure out how to resolve this situation, 2291 /// merging decls or emitting diagnostics as appropriate. 2292 /// 2293 /// In C++, New and Old must be declarations that are not 2294 /// overloaded. Use IsOverload to determine whether New and Old are 2295 /// overloaded, and to select the Old declaration that New should be 2296 /// merged with. 2297 /// 2298 /// Returns true if there was an error, false otherwise. 2299 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S, 2300 bool MergeTypeWithOld) { 2301 // Verify the old decl was also a function. 2302 FunctionDecl *Old = 0; 2303 if (FunctionTemplateDecl *OldFunctionTemplate 2304 = dyn_cast<FunctionTemplateDecl>(OldD)) 2305 Old = OldFunctionTemplate->getTemplatedDecl(); 2306 else 2307 Old = dyn_cast<FunctionDecl>(OldD); 2308 if (!Old) { 2309 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2310 if (New->getFriendObjectKind()) { 2311 Diag(New->getLocation(), diag::err_using_decl_friend); 2312 Diag(Shadow->getTargetDecl()->getLocation(), 2313 diag::note_using_decl_target); 2314 Diag(Shadow->getUsingDecl()->getLocation(), 2315 diag::note_using_decl) << 0; 2316 return true; 2317 } 2318 2319 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2320 Diag(Shadow->getTargetDecl()->getLocation(), 2321 diag::note_using_decl_target); 2322 Diag(Shadow->getUsingDecl()->getLocation(), 2323 diag::note_using_decl) << 0; 2324 return true; 2325 } 2326 2327 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2328 << New->getDeclName(); 2329 Diag(OldD->getLocation(), diag::note_previous_definition); 2330 return true; 2331 } 2332 2333 // If the old declaration is invalid, just give up here. 2334 if (Old->isInvalidDecl()) 2335 return true; 2336 2337 // Determine whether the previous declaration was a definition, 2338 // implicit declaration, or a declaration. 2339 diag::kind PrevDiag; 2340 if (Old->isThisDeclarationADefinition()) 2341 PrevDiag = diag::note_previous_definition; 2342 else if (Old->isImplicit()) 2343 PrevDiag = diag::note_previous_implicit_declaration; 2344 else 2345 PrevDiag = diag::note_previous_declaration; 2346 2347 // Don't complain about this if we're in GNU89 mode and the old function 2348 // is an extern inline function. 2349 // Don't complain about specializations. They are not supposed to have 2350 // storage classes. 2351 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2352 New->getStorageClass() == SC_Static && 2353 Old->hasExternalFormalLinkage() && 2354 !New->getTemplateSpecializationInfo() && 2355 !canRedefineFunction(Old, getLangOpts())) { 2356 if (getLangOpts().MicrosoftExt) { 2357 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2358 Diag(Old->getLocation(), PrevDiag); 2359 } else { 2360 Diag(New->getLocation(), diag::err_static_non_static) << New; 2361 Diag(Old->getLocation(), PrevDiag); 2362 return true; 2363 } 2364 } 2365 2366 2367 // If a function is first declared with a calling convention, but is later 2368 // declared or defined without one, all following decls assume the calling 2369 // convention of the first. 2370 // 2371 // It's OK if a function is first declared without a calling convention, 2372 // but is later declared or defined with the default calling convention. 2373 // 2374 // To test if either decl has an explicit calling convention, we look for 2375 // AttributedType sugar nodes on the type as written. If they are missing or 2376 // were canonicalized away, we assume the calling convention was implicit. 2377 // 2378 // Note also that we DO NOT return at this point, because we still have 2379 // other tests to run. 2380 QualType OldQType = Context.getCanonicalType(Old->getType()); 2381 QualType NewQType = Context.getCanonicalType(New->getType()); 2382 const FunctionType *OldType = cast<FunctionType>(OldQType); 2383 const FunctionType *NewType = cast<FunctionType>(NewQType); 2384 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2385 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2386 bool RequiresAdjustment = false; 2387 2388 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2389 FunctionDecl *First = Old->getFirstDecl(); 2390 const FunctionType *FT = 2391 First->getType().getCanonicalType()->castAs<FunctionType>(); 2392 FunctionType::ExtInfo FI = FT->getExtInfo(); 2393 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2394 if (!NewCCExplicit) { 2395 // Inherit the CC from the previous declaration if it was specified 2396 // there but not here. 2397 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2398 RequiresAdjustment = true; 2399 } else { 2400 // Calling conventions aren't compatible, so complain. 2401 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2402 Diag(New->getLocation(), diag::err_cconv_change) 2403 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2404 << !FirstCCExplicit 2405 << (!FirstCCExplicit ? "" : 2406 FunctionType::getNameForCallConv(FI.getCC())); 2407 2408 // Put the note on the first decl, since it is the one that matters. 2409 Diag(First->getLocation(), diag::note_previous_declaration); 2410 return true; 2411 } 2412 } 2413 2414 // FIXME: diagnose the other way around? 2415 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2416 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2417 RequiresAdjustment = true; 2418 } 2419 2420 // Merge regparm attribute. 2421 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2422 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2423 if (NewTypeInfo.getHasRegParm()) { 2424 Diag(New->getLocation(), diag::err_regparm_mismatch) 2425 << NewType->getRegParmType() 2426 << OldType->getRegParmType(); 2427 Diag(Old->getLocation(), diag::note_previous_declaration); 2428 return true; 2429 } 2430 2431 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2432 RequiresAdjustment = true; 2433 } 2434 2435 // Merge ns_returns_retained attribute. 2436 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2437 if (NewTypeInfo.getProducesResult()) { 2438 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2439 Diag(Old->getLocation(), diag::note_previous_declaration); 2440 return true; 2441 } 2442 2443 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2444 RequiresAdjustment = true; 2445 } 2446 2447 if (RequiresAdjustment) { 2448 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2449 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2450 New->setType(QualType(AdjustedType, 0)); 2451 NewQType = Context.getCanonicalType(New->getType()); 2452 NewType = cast<FunctionType>(NewQType); 2453 } 2454 2455 // If this redeclaration makes the function inline, we may need to add it to 2456 // UndefinedButUsed. 2457 if (!Old->isInlined() && New->isInlined() && 2458 !New->hasAttr<GNUInlineAttr>() && 2459 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2460 Old->isUsed(false) && 2461 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2462 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2463 SourceLocation())); 2464 2465 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2466 // about it. 2467 if (New->hasAttr<GNUInlineAttr>() && 2468 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2469 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2470 } 2471 2472 if (getLangOpts().CPlusPlus) { 2473 // (C++98 13.1p2): 2474 // Certain function declarations cannot be overloaded: 2475 // -- Function declarations that differ only in the return type 2476 // cannot be overloaded. 2477 2478 // Go back to the type source info to compare the declared return types, 2479 // per C++1y [dcl.type.auto]p13: 2480 // Redeclarations or specializations of a function or function template 2481 // with a declared return type that uses a placeholder type shall also 2482 // use that placeholder, not a deduced type. 2483 QualType OldDeclaredReturnType = (Old->getTypeSourceInfo() 2484 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2485 : OldType)->getResultType(); 2486 QualType NewDeclaredReturnType = (New->getTypeSourceInfo() 2487 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2488 : NewType)->getResultType(); 2489 QualType ResQT; 2490 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2491 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2492 New->isLocalExternDecl())) { 2493 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2494 OldDeclaredReturnType->isObjCObjectPointerType()) 2495 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2496 if (ResQT.isNull()) { 2497 if (New->isCXXClassMember() && New->isOutOfLine()) 2498 Diag(New->getLocation(), 2499 diag::err_member_def_does_not_match_ret_type) << New; 2500 else 2501 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2502 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2503 return true; 2504 } 2505 else 2506 NewQType = ResQT; 2507 } 2508 2509 QualType OldReturnType = OldType->getResultType(); 2510 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2511 if (OldReturnType != NewReturnType) { 2512 // If this function has a deduced return type and has already been 2513 // defined, copy the deduced value from the old declaration. 2514 AutoType *OldAT = Old->getResultType()->getContainedAutoType(); 2515 if (OldAT && OldAT->isDeduced()) { 2516 New->setType( 2517 SubstAutoType(New->getType(), 2518 OldAT->isDependentType() ? Context.DependentTy 2519 : OldAT->getDeducedType())); 2520 NewQType = Context.getCanonicalType( 2521 SubstAutoType(NewQType, 2522 OldAT->isDependentType() ? Context.DependentTy 2523 : OldAT->getDeducedType())); 2524 } 2525 } 2526 2527 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2528 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2529 if (OldMethod && NewMethod) { 2530 // Preserve triviality. 2531 NewMethod->setTrivial(OldMethod->isTrivial()); 2532 2533 // MSVC allows explicit template specialization at class scope: 2534 // 2 CXMethodDecls referring to the same function will be injected. 2535 // We don't want a redeclartion error. 2536 bool IsClassScopeExplicitSpecialization = 2537 OldMethod->isFunctionTemplateSpecialization() && 2538 NewMethod->isFunctionTemplateSpecialization(); 2539 bool isFriend = NewMethod->getFriendObjectKind(); 2540 2541 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2542 !IsClassScopeExplicitSpecialization) { 2543 // -- Member function declarations with the same name and the 2544 // same parameter types cannot be overloaded if any of them 2545 // is a static member function declaration. 2546 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2547 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2548 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2549 return true; 2550 } 2551 2552 // C++ [class.mem]p1: 2553 // [...] A member shall not be declared twice in the 2554 // member-specification, except that a nested class or member 2555 // class template can be declared and then later defined. 2556 if (ActiveTemplateInstantiations.empty()) { 2557 unsigned NewDiag; 2558 if (isa<CXXConstructorDecl>(OldMethod)) 2559 NewDiag = diag::err_constructor_redeclared; 2560 else if (isa<CXXDestructorDecl>(NewMethod)) 2561 NewDiag = diag::err_destructor_redeclared; 2562 else if (isa<CXXConversionDecl>(NewMethod)) 2563 NewDiag = diag::err_conv_function_redeclared; 2564 else 2565 NewDiag = diag::err_member_redeclared; 2566 2567 Diag(New->getLocation(), NewDiag); 2568 } else { 2569 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2570 << New << New->getType(); 2571 } 2572 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2573 2574 // Complain if this is an explicit declaration of a special 2575 // member that was initially declared implicitly. 2576 // 2577 // As an exception, it's okay to befriend such methods in order 2578 // to permit the implicit constructor/destructor/operator calls. 2579 } else if (OldMethod->isImplicit()) { 2580 if (isFriend) { 2581 NewMethod->setImplicit(); 2582 } else { 2583 Diag(NewMethod->getLocation(), 2584 diag::err_definition_of_implicitly_declared_member) 2585 << New << getSpecialMember(OldMethod); 2586 return true; 2587 } 2588 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2589 Diag(NewMethod->getLocation(), 2590 diag::err_definition_of_explicitly_defaulted_member) 2591 << getSpecialMember(OldMethod); 2592 return true; 2593 } 2594 } 2595 2596 // C++11 [dcl.attr.noreturn]p1: 2597 // The first declaration of a function shall specify the noreturn 2598 // attribute if any declaration of that function specifies the noreturn 2599 // attribute. 2600 if (New->hasAttr<CXX11NoReturnAttr>() && 2601 !Old->hasAttr<CXX11NoReturnAttr>()) { 2602 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(), 2603 diag::err_noreturn_missing_on_first_decl); 2604 Diag(Old->getFirstDecl()->getLocation(), 2605 diag::note_noreturn_missing_first_decl); 2606 } 2607 2608 // C++11 [dcl.attr.depend]p2: 2609 // The first declaration of a function shall specify the 2610 // carries_dependency attribute for its declarator-id if any declaration 2611 // of the function specifies the carries_dependency attribute. 2612 if (New->hasAttr<CarriesDependencyAttr>() && 2613 !Old->hasAttr<CarriesDependencyAttr>()) { 2614 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(), 2615 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2616 Diag(Old->getFirstDecl()->getLocation(), 2617 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2618 } 2619 2620 // (C++98 8.3.5p3): 2621 // All declarations for a function shall agree exactly in both the 2622 // return type and the parameter-type-list. 2623 // We also want to respect all the extended bits except noreturn. 2624 2625 // noreturn should now match unless the old type info didn't have it. 2626 QualType OldQTypeForComparison = OldQType; 2627 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2628 assert(OldQType == QualType(OldType, 0)); 2629 const FunctionType *OldTypeForComparison 2630 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2631 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2632 assert(OldQTypeForComparison.isCanonical()); 2633 } 2634 2635 if (haveIncompatibleLanguageLinkages(Old, New)) { 2636 // As a special case, retain the language linkage from previous 2637 // declarations of a friend function as an extension. 2638 // 2639 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2640 // and is useful because there's otherwise no way to specify language 2641 // linkage within class scope. 2642 // 2643 // Check cautiously as the friend object kind isn't yet complete. 2644 if (New->getFriendObjectKind() != Decl::FOK_None) { 2645 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2646 Diag(Old->getLocation(), PrevDiag); 2647 } else { 2648 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2649 Diag(Old->getLocation(), PrevDiag); 2650 return true; 2651 } 2652 } 2653 2654 if (OldQTypeForComparison == NewQType) 2655 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2656 2657 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2658 New->isLocalExternDecl()) { 2659 // It's OK if we couldn't merge types for a local function declaraton 2660 // if either the old or new type is dependent. We'll merge the types 2661 // when we instantiate the function. 2662 return false; 2663 } 2664 2665 // Fall through for conflicting redeclarations and redefinitions. 2666 } 2667 2668 // C: Function types need to be compatible, not identical. This handles 2669 // duplicate function decls like "void f(int); void f(enum X);" properly. 2670 if (!getLangOpts().CPlusPlus && 2671 Context.typesAreCompatible(OldQType, NewQType)) { 2672 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2673 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2674 const FunctionProtoType *OldProto = 0; 2675 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2676 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2677 // The old declaration provided a function prototype, but the 2678 // new declaration does not. Merge in the prototype. 2679 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2680 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2681 OldProto->arg_type_end()); 2682 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2683 ParamTypes, 2684 OldProto->getExtProtoInfo()); 2685 New->setType(NewQType); 2686 New->setHasInheritedPrototype(); 2687 2688 // Synthesize a parameter for each argument type. 2689 SmallVector<ParmVarDecl*, 16> Params; 2690 for (FunctionProtoType::arg_type_iterator 2691 ParamType = OldProto->arg_type_begin(), 2692 ParamEnd = OldProto->arg_type_end(); 2693 ParamType != ParamEnd; ++ParamType) { 2694 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2695 SourceLocation(), 2696 SourceLocation(), 0, 2697 *ParamType, /*TInfo=*/0, 2698 SC_None, 2699 0); 2700 Param->setScopeInfo(0, Params.size()); 2701 Param->setImplicit(); 2702 Params.push_back(Param); 2703 } 2704 2705 New->setParams(Params); 2706 } 2707 2708 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2709 } 2710 2711 // GNU C permits a K&R definition to follow a prototype declaration 2712 // if the declared types of the parameters in the K&R definition 2713 // match the types in the prototype declaration, even when the 2714 // promoted types of the parameters from the K&R definition differ 2715 // from the types in the prototype. GCC then keeps the types from 2716 // the prototype. 2717 // 2718 // If a variadic prototype is followed by a non-variadic K&R definition, 2719 // the K&R definition becomes variadic. This is sort of an edge case, but 2720 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2721 // C99 6.9.1p8. 2722 if (!getLangOpts().CPlusPlus && 2723 Old->hasPrototype() && !New->hasPrototype() && 2724 New->getType()->getAs<FunctionProtoType>() && 2725 Old->getNumParams() == New->getNumParams()) { 2726 SmallVector<QualType, 16> ArgTypes; 2727 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2728 const FunctionProtoType *OldProto 2729 = Old->getType()->getAs<FunctionProtoType>(); 2730 const FunctionProtoType *NewProto 2731 = New->getType()->getAs<FunctionProtoType>(); 2732 2733 // Determine whether this is the GNU C extension. 2734 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2735 NewProto->getResultType()); 2736 bool LooseCompatible = !MergedReturn.isNull(); 2737 for (unsigned Idx = 0, End = Old->getNumParams(); 2738 LooseCompatible && Idx != End; ++Idx) { 2739 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2740 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2741 if (Context.typesAreCompatible(OldParm->getType(), 2742 NewProto->getArgType(Idx))) { 2743 ArgTypes.push_back(NewParm->getType()); 2744 } else if (Context.typesAreCompatible(OldParm->getType(), 2745 NewParm->getType(), 2746 /*CompareUnqualified=*/true)) { 2747 GNUCompatibleParamWarning Warn 2748 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2749 Warnings.push_back(Warn); 2750 ArgTypes.push_back(NewParm->getType()); 2751 } else 2752 LooseCompatible = false; 2753 } 2754 2755 if (LooseCompatible) { 2756 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2757 Diag(Warnings[Warn].NewParm->getLocation(), 2758 diag::ext_param_promoted_not_compatible_with_prototype) 2759 << Warnings[Warn].PromotedType 2760 << Warnings[Warn].OldParm->getType(); 2761 if (Warnings[Warn].OldParm->getLocation().isValid()) 2762 Diag(Warnings[Warn].OldParm->getLocation(), 2763 diag::note_previous_declaration); 2764 } 2765 2766 if (MergeTypeWithOld) 2767 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2768 OldProto->getExtProtoInfo())); 2769 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2770 } 2771 2772 // Fall through to diagnose conflicting types. 2773 } 2774 2775 // A function that has already been declared has been redeclared or 2776 // defined with a different type; show an appropriate diagnostic. 2777 2778 // If the previous declaration was an implicitly-generated builtin 2779 // declaration, then at the very least we should use a specialized note. 2780 unsigned BuiltinID; 2781 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2782 // If it's actually a library-defined builtin function like 'malloc' 2783 // or 'printf', just warn about the incompatible redeclaration. 2784 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2785 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2786 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2787 << Old << Old->getType(); 2788 2789 // If this is a global redeclaration, just forget hereafter 2790 // about the "builtin-ness" of the function. 2791 // 2792 // Doing this for local extern declarations is problematic. If 2793 // the builtin declaration remains visible, a second invalid 2794 // local declaration will produce a hard error; if it doesn't 2795 // remain visible, a single bogus local redeclaration (which is 2796 // actually only a warning) could break all the downstream code. 2797 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2798 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2799 2800 return false; 2801 } 2802 2803 PrevDiag = diag::note_previous_builtin_declaration; 2804 } 2805 2806 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2807 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2808 return true; 2809 } 2810 2811 /// \brief Completes the merge of two function declarations that are 2812 /// known to be compatible. 2813 /// 2814 /// This routine handles the merging of attributes and other 2815 /// properties of function declarations from the old declaration to 2816 /// the new declaration, once we know that New is in fact a 2817 /// redeclaration of Old. 2818 /// 2819 /// \returns false 2820 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2821 Scope *S, bool MergeTypeWithOld) { 2822 // Merge the attributes 2823 mergeDeclAttributes(New, Old); 2824 2825 // Merge "pure" flag. 2826 if (Old->isPure()) 2827 New->setPure(); 2828 2829 // Merge "used" flag. 2830 if (Old->getMostRecentDecl()->isUsed(false)) 2831 New->setIsUsed(); 2832 2833 // Merge attributes from the parameters. These can mismatch with K&R 2834 // declarations. 2835 if (New->getNumParams() == Old->getNumParams()) 2836 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2837 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2838 *this); 2839 2840 if (getLangOpts().CPlusPlus) 2841 return MergeCXXFunctionDecl(New, Old, S); 2842 2843 // Merge the function types so the we get the composite types for the return 2844 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2845 // was visible. 2846 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2847 if (!Merged.isNull() && MergeTypeWithOld) 2848 New->setType(Merged); 2849 2850 return false; 2851 } 2852 2853 2854 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2855 ObjCMethodDecl *oldMethod) { 2856 2857 // Merge the attributes, including deprecated/unavailable 2858 AvailabilityMergeKind MergeKind = 2859 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2860 : AMK_Override; 2861 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2862 2863 // Merge attributes from the parameters. 2864 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2865 oe = oldMethod->param_end(); 2866 for (ObjCMethodDecl::param_iterator 2867 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2868 ni != ne && oi != oe; ++ni, ++oi) 2869 mergeParamDeclAttributes(*ni, *oi, *this); 2870 2871 CheckObjCMethodOverride(newMethod, oldMethod); 2872 } 2873 2874 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2875 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2876 /// emitting diagnostics as appropriate. 2877 /// 2878 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2879 /// to here in AddInitializerToDecl. We can't check them before the initializer 2880 /// is attached. 2881 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2882 bool MergeTypeWithOld) { 2883 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2884 return; 2885 2886 QualType MergedT; 2887 if (getLangOpts().CPlusPlus) { 2888 if (New->getType()->isUndeducedType()) { 2889 // We don't know what the new type is until the initializer is attached. 2890 return; 2891 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2892 // These could still be something that needs exception specs checked. 2893 return MergeVarDeclExceptionSpecs(New, Old); 2894 } 2895 // C++ [basic.link]p10: 2896 // [...] the types specified by all declarations referring to a given 2897 // object or function shall be identical, except that declarations for an 2898 // array object can specify array types that differ by the presence or 2899 // absence of a major array bound (8.3.4). 2900 else if (Old->getType()->isIncompleteArrayType() && 2901 New->getType()->isArrayType()) { 2902 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2903 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2904 if (Context.hasSameType(OldArray->getElementType(), 2905 NewArray->getElementType())) 2906 MergedT = New->getType(); 2907 } else if (Old->getType()->isArrayType() && 2908 New->getType()->isIncompleteArrayType()) { 2909 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2910 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2911 if (Context.hasSameType(OldArray->getElementType(), 2912 NewArray->getElementType())) 2913 MergedT = Old->getType(); 2914 } else if (New->getType()->isObjCObjectPointerType() && 2915 Old->getType()->isObjCObjectPointerType()) { 2916 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2917 Old->getType()); 2918 } 2919 } else { 2920 // C 6.2.7p2: 2921 // All declarations that refer to the same object or function shall have 2922 // compatible type. 2923 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2924 } 2925 if (MergedT.isNull()) { 2926 // It's OK if we couldn't merge types if either type is dependent, for a 2927 // block-scope variable. In other cases (static data members of class 2928 // templates, variable templates, ...), we require the types to be 2929 // equivalent. 2930 // FIXME: The C++ standard doesn't say anything about this. 2931 if ((New->getType()->isDependentType() || 2932 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2933 // If the old type was dependent, we can't merge with it, so the new type 2934 // becomes dependent for now. We'll reproduce the original type when we 2935 // instantiate the TypeSourceInfo for the variable. 2936 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2937 New->setType(Context.DependentTy); 2938 return; 2939 } 2940 2941 // FIXME: Even if this merging succeeds, some other non-visible declaration 2942 // of this variable might have an incompatible type. For instance: 2943 // 2944 // extern int arr[]; 2945 // void f() { extern int arr[2]; } 2946 // void g() { extern int arr[3]; } 2947 // 2948 // Neither C nor C++ requires a diagnostic for this, but we should still try 2949 // to diagnose it. 2950 Diag(New->getLocation(), diag::err_redefinition_different_type) 2951 << New->getDeclName() << New->getType() << Old->getType(); 2952 Diag(Old->getLocation(), diag::note_previous_definition); 2953 return New->setInvalidDecl(); 2954 } 2955 2956 // Don't actually update the type on the new declaration if the old 2957 // declaration was an extern declaration in a different scope. 2958 if (MergeTypeWithOld) 2959 New->setType(MergedT); 2960 } 2961 2962 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2963 LookupResult &Previous) { 2964 // C11 6.2.7p4: 2965 // For an identifier with internal or external linkage declared 2966 // in a scope in which a prior declaration of that identifier is 2967 // visible, if the prior declaration specifies internal or 2968 // external linkage, the type of the identifier at the later 2969 // declaration becomes the composite type. 2970 // 2971 // If the variable isn't visible, we do not merge with its type. 2972 if (Previous.isShadowed()) 2973 return false; 2974 2975 if (S.getLangOpts().CPlusPlus) { 2976 // C++11 [dcl.array]p3: 2977 // If there is a preceding declaration of the entity in the same 2978 // scope in which the bound was specified, an omitted array bound 2979 // is taken to be the same as in that earlier declaration. 2980 return NewVD->isPreviousDeclInSameBlockScope() || 2981 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2982 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2983 } else { 2984 // If the old declaration was function-local, don't merge with its 2985 // type unless we're in the same function. 2986 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2987 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2988 } 2989 } 2990 2991 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2992 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2993 /// situation, merging decls or emitting diagnostics as appropriate. 2994 /// 2995 /// Tentative definition rules (C99 6.9.2p2) are checked by 2996 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2997 /// definitions here, since the initializer hasn't been attached. 2998 /// 2999 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3000 // If the new decl is already invalid, don't do any other checking. 3001 if (New->isInvalidDecl()) 3002 return; 3003 3004 // Verify the old decl was also a variable or variable template. 3005 VarDecl *Old = 0; 3006 if (Previous.isSingleResult() && 3007 (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 3008 if (New->getDescribedVarTemplate()) 3009 Old = Old->getDescribedVarTemplate() ? Old : 0; 3010 else 3011 Old = Old->getDescribedVarTemplate() ? 0 : Old; 3012 } 3013 if (!Old) { 3014 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3015 << New->getDeclName(); 3016 Diag(Previous.getRepresentativeDecl()->getLocation(), 3017 diag::note_previous_definition); 3018 return New->setInvalidDecl(); 3019 } 3020 3021 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3022 return; 3023 3024 // C++ [class.mem]p1: 3025 // A member shall not be declared twice in the member-specification [...] 3026 // 3027 // Here, we need only consider static data members. 3028 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3029 Diag(New->getLocation(), diag::err_duplicate_member) 3030 << New->getIdentifier(); 3031 Diag(Old->getLocation(), diag::note_previous_declaration); 3032 New->setInvalidDecl(); 3033 } 3034 3035 mergeDeclAttributes(New, Old); 3036 // Warn if an already-declared variable is made a weak_import in a subsequent 3037 // declaration 3038 if (New->getAttr<WeakImportAttr>() && 3039 Old->getStorageClass() == SC_None && 3040 !Old->getAttr<WeakImportAttr>()) { 3041 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3042 Diag(Old->getLocation(), diag::note_previous_definition); 3043 // Remove weak_import attribute on new declaration. 3044 New->dropAttr<WeakImportAttr>(); 3045 } 3046 3047 // Merge the types. 3048 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3049 3050 if (New->isInvalidDecl()) 3051 return; 3052 3053 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3054 if (New->getStorageClass() == SC_Static && 3055 !New->isStaticDataMember() && 3056 Old->hasExternalFormalLinkage()) { 3057 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3058 Diag(Old->getLocation(), diag::note_previous_definition); 3059 return New->setInvalidDecl(); 3060 } 3061 // C99 6.2.2p4: 3062 // For an identifier declared with the storage-class specifier 3063 // extern in a scope in which a prior declaration of that 3064 // identifier is visible,23) if the prior declaration specifies 3065 // internal or external linkage, the linkage of the identifier at 3066 // the later declaration is the same as the linkage specified at 3067 // the prior declaration. If no prior declaration is visible, or 3068 // if the prior declaration specifies no linkage, then the 3069 // identifier has external linkage. 3070 if (New->hasExternalStorage() && Old->hasLinkage()) 3071 /* Okay */; 3072 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3073 !New->isStaticDataMember() && 3074 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3075 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3076 Diag(Old->getLocation(), diag::note_previous_definition); 3077 return New->setInvalidDecl(); 3078 } 3079 3080 // Check if extern is followed by non-extern and vice-versa. 3081 if (New->hasExternalStorage() && 3082 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3083 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3084 Diag(Old->getLocation(), diag::note_previous_definition); 3085 return New->setInvalidDecl(); 3086 } 3087 if (Old->hasLinkage() && New->isLocalVarDecl() && 3088 !New->hasExternalStorage()) { 3089 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3090 Diag(Old->getLocation(), diag::note_previous_definition); 3091 return New->setInvalidDecl(); 3092 } 3093 3094 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3095 3096 // FIXME: The test for external storage here seems wrong? We still 3097 // need to check for mismatches. 3098 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3099 // Don't complain about out-of-line definitions of static members. 3100 !(Old->getLexicalDeclContext()->isRecord() && 3101 !New->getLexicalDeclContext()->isRecord())) { 3102 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3103 Diag(Old->getLocation(), diag::note_previous_definition); 3104 return New->setInvalidDecl(); 3105 } 3106 3107 if (New->getTLSKind() != Old->getTLSKind()) { 3108 if (!Old->getTLSKind()) { 3109 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3110 Diag(Old->getLocation(), diag::note_previous_declaration); 3111 } else if (!New->getTLSKind()) { 3112 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3113 Diag(Old->getLocation(), diag::note_previous_declaration); 3114 } else { 3115 // Do not allow redeclaration to change the variable between requiring 3116 // static and dynamic initialization. 3117 // FIXME: GCC allows this, but uses the TLS keyword on the first 3118 // declaration to determine the kind. Do we need to be compatible here? 3119 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3120 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3121 Diag(Old->getLocation(), diag::note_previous_declaration); 3122 } 3123 } 3124 3125 // C++ doesn't have tentative definitions, so go right ahead and check here. 3126 const VarDecl *Def; 3127 if (getLangOpts().CPlusPlus && 3128 New->isThisDeclarationADefinition() == VarDecl::Definition && 3129 (Def = Old->getDefinition())) { 3130 Diag(New->getLocation(), diag::err_redefinition) << New; 3131 Diag(Def->getLocation(), diag::note_previous_definition); 3132 New->setInvalidDecl(); 3133 return; 3134 } 3135 3136 if (haveIncompatibleLanguageLinkages(Old, New)) { 3137 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3138 Diag(Old->getLocation(), diag::note_previous_definition); 3139 New->setInvalidDecl(); 3140 return; 3141 } 3142 3143 // Merge "used" flag. 3144 if (Old->getMostRecentDecl()->isUsed(false)) 3145 New->setIsUsed(); 3146 3147 // Keep a chain of previous declarations. 3148 New->setPreviousDecl(Old); 3149 3150 // Inherit access appropriately. 3151 New->setAccess(Old->getAccess()); 3152 3153 if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) { 3154 if (New->isStaticDataMember() && New->isOutOfLine()) 3155 VTD->setAccess(New->getAccess()); 3156 } 3157 } 3158 3159 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3160 /// no declarator (e.g. "struct foo;") is parsed. 3161 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3162 DeclSpec &DS) { 3163 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3164 } 3165 3166 static void HandleTagNumbering(Sema &S, const TagDecl *Tag) { 3167 if (!S.Context.getLangOpts().CPlusPlus) 3168 return; 3169 3170 if (isa<CXXRecordDecl>(Tag->getParent())) { 3171 // If this tag is the direct child of a class, number it if 3172 // it is anonymous. 3173 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3174 return; 3175 MangleNumberingContext &MCtx = 3176 S.Context.getManglingNumberContext(Tag->getParent()); 3177 S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag)); 3178 return; 3179 } 3180 3181 // If this tag isn't a direct child of a class, number it if it is local. 3182 Decl *ManglingContextDecl; 3183 if (MangleNumberingContext *MCtx = 3184 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3185 ManglingContextDecl)) { 3186 S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag)); 3187 } 3188 } 3189 3190 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3191 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3192 /// parameters to cope with template friend declarations. 3193 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3194 DeclSpec &DS, 3195 MultiTemplateParamsArg TemplateParams, 3196 bool IsExplicitInstantiation) { 3197 Decl *TagD = 0; 3198 TagDecl *Tag = 0; 3199 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3200 DS.getTypeSpecType() == DeclSpec::TST_struct || 3201 DS.getTypeSpecType() == DeclSpec::TST_interface || 3202 DS.getTypeSpecType() == DeclSpec::TST_union || 3203 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3204 TagD = DS.getRepAsDecl(); 3205 3206 if (!TagD) // We probably had an error 3207 return 0; 3208 3209 // Note that the above type specs guarantee that the 3210 // type rep is a Decl, whereas in many of the others 3211 // it's a Type. 3212 if (isa<TagDecl>(TagD)) 3213 Tag = cast<TagDecl>(TagD); 3214 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3215 Tag = CTD->getTemplatedDecl(); 3216 } 3217 3218 if (Tag) { 3219 HandleTagNumbering(*this, Tag); 3220 Tag->setFreeStanding(); 3221 if (Tag->isInvalidDecl()) 3222 return Tag; 3223 } 3224 3225 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3226 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3227 // or incomplete types shall not be restrict-qualified." 3228 if (TypeQuals & DeclSpec::TQ_restrict) 3229 Diag(DS.getRestrictSpecLoc(), 3230 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3231 << DS.getSourceRange(); 3232 } 3233 3234 if (DS.isConstexprSpecified()) { 3235 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3236 // and definitions of functions and variables. 3237 if (Tag) 3238 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3239 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3240 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3241 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3242 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3243 else 3244 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3245 // Don't emit warnings after this error. 3246 return TagD; 3247 } 3248 3249 DiagnoseFunctionSpecifiers(DS); 3250 3251 if (DS.isFriendSpecified()) { 3252 // If we're dealing with a decl but not a TagDecl, assume that 3253 // whatever routines created it handled the friendship aspect. 3254 if (TagD && !Tag) 3255 return 0; 3256 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3257 } 3258 3259 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3260 bool IsExplicitSpecialization = 3261 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3262 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3263 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3264 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3265 // nested-name-specifier unless it is an explicit instantiation 3266 // or an explicit specialization. 3267 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3268 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3269 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3270 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3271 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3272 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3273 << SS.getRange(); 3274 return 0; 3275 } 3276 3277 // Track whether this decl-specifier declares anything. 3278 bool DeclaresAnything = true; 3279 3280 // Handle anonymous struct definitions. 3281 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3282 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3283 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3284 if (getLangOpts().CPlusPlus || 3285 Record->getDeclContext()->isRecord()) 3286 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 3287 3288 DeclaresAnything = false; 3289 } 3290 } 3291 3292 // Check for Microsoft C extension: anonymous struct member. 3293 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3294 CurContext->isRecord() && 3295 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3296 // Handle 2 kinds of anonymous struct: 3297 // struct STRUCT; 3298 // and 3299 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3300 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3301 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3302 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3303 DS.getRepAsType().get()->isStructureType())) { 3304 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3305 << DS.getSourceRange(); 3306 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3307 } 3308 } 3309 3310 // Skip all the checks below if we have a type error. 3311 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3312 (TagD && TagD->isInvalidDecl())) 3313 return TagD; 3314 3315 if (getLangOpts().CPlusPlus && 3316 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3317 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3318 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3319 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3320 DeclaresAnything = false; 3321 3322 if (!DS.isMissingDeclaratorOk()) { 3323 // Customize diagnostic for a typedef missing a name. 3324 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3325 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3326 << DS.getSourceRange(); 3327 else 3328 DeclaresAnything = false; 3329 } 3330 3331 if (DS.isModulePrivateSpecified() && 3332 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3333 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3334 << Tag->getTagKind() 3335 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3336 3337 ActOnDocumentableDecl(TagD); 3338 3339 // C 6.7/2: 3340 // A declaration [...] shall declare at least a declarator [...], a tag, 3341 // or the members of an enumeration. 3342 // C++ [dcl.dcl]p3: 3343 // [If there are no declarators], and except for the declaration of an 3344 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3345 // names into the program, or shall redeclare a name introduced by a 3346 // previous declaration. 3347 if (!DeclaresAnything) { 3348 // In C, we allow this as a (popular) extension / bug. Don't bother 3349 // producing further diagnostics for redundant qualifiers after this. 3350 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3351 return TagD; 3352 } 3353 3354 // C++ [dcl.stc]p1: 3355 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3356 // init-declarator-list of the declaration shall not be empty. 3357 // C++ [dcl.fct.spec]p1: 3358 // If a cv-qualifier appears in a decl-specifier-seq, the 3359 // init-declarator-list of the declaration shall not be empty. 3360 // 3361 // Spurious qualifiers here appear to be valid in C. 3362 unsigned DiagID = diag::warn_standalone_specifier; 3363 if (getLangOpts().CPlusPlus) 3364 DiagID = diag::ext_standalone_specifier; 3365 3366 // Note that a linkage-specification sets a storage class, but 3367 // 'extern "C" struct foo;' is actually valid and not theoretically 3368 // useless. 3369 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3370 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3371 Diag(DS.getStorageClassSpecLoc(), DiagID) 3372 << DeclSpec::getSpecifierName(SCS); 3373 3374 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3375 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3376 << DeclSpec::getSpecifierName(TSCS); 3377 if (DS.getTypeQualifiers()) { 3378 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3379 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3380 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3381 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3382 // Restrict is covered above. 3383 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3384 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3385 } 3386 3387 // Warn about ignored type attributes, for example: 3388 // __attribute__((aligned)) struct A; 3389 // Attributes should be placed after tag to apply to type declaration. 3390 if (!DS.getAttributes().empty()) { 3391 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3392 if (TypeSpecType == DeclSpec::TST_class || 3393 TypeSpecType == DeclSpec::TST_struct || 3394 TypeSpecType == DeclSpec::TST_interface || 3395 TypeSpecType == DeclSpec::TST_union || 3396 TypeSpecType == DeclSpec::TST_enum) { 3397 AttributeList* attrs = DS.getAttributes().getList(); 3398 while (attrs) { 3399 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3400 << attrs->getName() 3401 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3402 TypeSpecType == DeclSpec::TST_struct ? 1 : 3403 TypeSpecType == DeclSpec::TST_union ? 2 : 3404 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3405 attrs = attrs->getNext(); 3406 } 3407 } 3408 } 3409 3410 return TagD; 3411 } 3412 3413 /// We are trying to inject an anonymous member into the given scope; 3414 /// check if there's an existing declaration that can't be overloaded. 3415 /// 3416 /// \return true if this is a forbidden redeclaration 3417 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3418 Scope *S, 3419 DeclContext *Owner, 3420 DeclarationName Name, 3421 SourceLocation NameLoc, 3422 unsigned diagnostic) { 3423 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3424 Sema::ForRedeclaration); 3425 if (!SemaRef.LookupName(R, S)) return false; 3426 3427 if (R.getAsSingle<TagDecl>()) 3428 return false; 3429 3430 // Pick a representative declaration. 3431 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3432 assert(PrevDecl && "Expected a non-null Decl"); 3433 3434 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3435 return false; 3436 3437 SemaRef.Diag(NameLoc, diagnostic) << Name; 3438 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3439 3440 return true; 3441 } 3442 3443 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3444 /// anonymous struct or union AnonRecord into the owning context Owner 3445 /// and scope S. This routine will be invoked just after we realize 3446 /// that an unnamed union or struct is actually an anonymous union or 3447 /// struct, e.g., 3448 /// 3449 /// @code 3450 /// union { 3451 /// int i; 3452 /// float f; 3453 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3454 /// // f into the surrounding scope.x 3455 /// @endcode 3456 /// 3457 /// This routine is recursive, injecting the names of nested anonymous 3458 /// structs/unions into the owning context and scope as well. 3459 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3460 DeclContext *Owner, 3461 RecordDecl *AnonRecord, 3462 AccessSpecifier AS, 3463 SmallVectorImpl<NamedDecl *> &Chaining, 3464 bool MSAnonStruct) { 3465 unsigned diagKind 3466 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3467 : diag::err_anonymous_struct_member_redecl; 3468 3469 bool Invalid = false; 3470 3471 // Look every FieldDecl and IndirectFieldDecl with a name. 3472 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3473 DEnd = AnonRecord->decls_end(); 3474 D != DEnd; ++D) { 3475 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3476 cast<NamedDecl>(*D)->getDeclName()) { 3477 ValueDecl *VD = cast<ValueDecl>(*D); 3478 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3479 VD->getLocation(), diagKind)) { 3480 // C++ [class.union]p2: 3481 // The names of the members of an anonymous union shall be 3482 // distinct from the names of any other entity in the 3483 // scope in which the anonymous union is declared. 3484 Invalid = true; 3485 } else { 3486 // C++ [class.union]p2: 3487 // For the purpose of name lookup, after the anonymous union 3488 // definition, the members of the anonymous union are 3489 // considered to have been defined in the scope in which the 3490 // anonymous union is declared. 3491 unsigned OldChainingSize = Chaining.size(); 3492 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3493 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3494 PE = IF->chain_end(); PI != PE; ++PI) 3495 Chaining.push_back(*PI); 3496 else 3497 Chaining.push_back(VD); 3498 3499 assert(Chaining.size() >= 2); 3500 NamedDecl **NamedChain = 3501 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3502 for (unsigned i = 0; i < Chaining.size(); i++) 3503 NamedChain[i] = Chaining[i]; 3504 3505 IndirectFieldDecl* IndirectField = 3506 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3507 VD->getIdentifier(), VD->getType(), 3508 NamedChain, Chaining.size()); 3509 3510 IndirectField->setAccess(AS); 3511 IndirectField->setImplicit(); 3512 SemaRef.PushOnScopeChains(IndirectField, S); 3513 3514 // That includes picking up the appropriate access specifier. 3515 if (AS != AS_none) IndirectField->setAccess(AS); 3516 3517 Chaining.resize(OldChainingSize); 3518 } 3519 } 3520 } 3521 3522 return Invalid; 3523 } 3524 3525 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3526 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3527 /// illegal input values are mapped to SC_None. 3528 static StorageClass 3529 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3530 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3531 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3532 "Parser allowed 'typedef' as storage class VarDecl."); 3533 switch (StorageClassSpec) { 3534 case DeclSpec::SCS_unspecified: return SC_None; 3535 case DeclSpec::SCS_extern: 3536 if (DS.isExternInLinkageSpec()) 3537 return SC_None; 3538 return SC_Extern; 3539 case DeclSpec::SCS_static: return SC_Static; 3540 case DeclSpec::SCS_auto: return SC_Auto; 3541 case DeclSpec::SCS_register: return SC_Register; 3542 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3543 // Illegal SCSs map to None: error reporting is up to the caller. 3544 case DeclSpec::SCS_mutable: // Fall through. 3545 case DeclSpec::SCS_typedef: return SC_None; 3546 } 3547 llvm_unreachable("unknown storage class specifier"); 3548 } 3549 3550 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3551 /// anonymous structure or union. Anonymous unions are a C++ feature 3552 /// (C++ [class.union]) and a C11 feature; anonymous structures 3553 /// are a C11 feature and GNU C++ extension. 3554 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3555 AccessSpecifier AS, 3556 RecordDecl *Record) { 3557 DeclContext *Owner = Record->getDeclContext(); 3558 3559 // Diagnose whether this anonymous struct/union is an extension. 3560 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3561 Diag(Record->getLocation(), diag::ext_anonymous_union); 3562 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3563 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3564 else if (!Record->isUnion() && !getLangOpts().C11) 3565 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3566 3567 // C and C++ require different kinds of checks for anonymous 3568 // structs/unions. 3569 bool Invalid = false; 3570 if (getLangOpts().CPlusPlus) { 3571 const char* PrevSpec = 0; 3572 unsigned DiagID; 3573 if (Record->isUnion()) { 3574 // C++ [class.union]p6: 3575 // Anonymous unions declared in a named namespace or in the 3576 // global namespace shall be declared static. 3577 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3578 (isa<TranslationUnitDecl>(Owner) || 3579 (isa<NamespaceDecl>(Owner) && 3580 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3581 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3582 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3583 3584 // Recover by adding 'static'. 3585 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3586 PrevSpec, DiagID); 3587 } 3588 // C++ [class.union]p6: 3589 // A storage class is not allowed in a declaration of an 3590 // anonymous union in a class scope. 3591 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3592 isa<RecordDecl>(Owner)) { 3593 Diag(DS.getStorageClassSpecLoc(), 3594 diag::err_anonymous_union_with_storage_spec) 3595 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3596 3597 // Recover by removing the storage specifier. 3598 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3599 SourceLocation(), 3600 PrevSpec, DiagID); 3601 } 3602 } 3603 3604 // Ignore const/volatile/restrict qualifiers. 3605 if (DS.getTypeQualifiers()) { 3606 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3607 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3608 << Record->isUnion() << "const" 3609 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3610 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3611 Diag(DS.getVolatileSpecLoc(), 3612 diag::ext_anonymous_struct_union_qualified) 3613 << Record->isUnion() << "volatile" 3614 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3615 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3616 Diag(DS.getRestrictSpecLoc(), 3617 diag::ext_anonymous_struct_union_qualified) 3618 << Record->isUnion() << "restrict" 3619 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3620 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3621 Diag(DS.getAtomicSpecLoc(), 3622 diag::ext_anonymous_struct_union_qualified) 3623 << Record->isUnion() << "_Atomic" 3624 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3625 3626 DS.ClearTypeQualifiers(); 3627 } 3628 3629 // C++ [class.union]p2: 3630 // The member-specification of an anonymous union shall only 3631 // define non-static data members. [Note: nested types and 3632 // functions cannot be declared within an anonymous union. ] 3633 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3634 MemEnd = Record->decls_end(); 3635 Mem != MemEnd; ++Mem) { 3636 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3637 // C++ [class.union]p3: 3638 // An anonymous union shall not have private or protected 3639 // members (clause 11). 3640 assert(FD->getAccess() != AS_none); 3641 if (FD->getAccess() != AS_public) { 3642 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3643 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3644 Invalid = true; 3645 } 3646 3647 // C++ [class.union]p1 3648 // An object of a class with a non-trivial constructor, a non-trivial 3649 // copy constructor, a non-trivial destructor, or a non-trivial copy 3650 // assignment operator cannot be a member of a union, nor can an 3651 // array of such objects. 3652 if (CheckNontrivialField(FD)) 3653 Invalid = true; 3654 } else if ((*Mem)->isImplicit()) { 3655 // Any implicit members are fine. 3656 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3657 // This is a type that showed up in an 3658 // elaborated-type-specifier inside the anonymous struct or 3659 // union, but which actually declares a type outside of the 3660 // anonymous struct or union. It's okay. 3661 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3662 if (!MemRecord->isAnonymousStructOrUnion() && 3663 MemRecord->getDeclName()) { 3664 // Visual C++ allows type definition in anonymous struct or union. 3665 if (getLangOpts().MicrosoftExt) 3666 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3667 << (int)Record->isUnion(); 3668 else { 3669 // This is a nested type declaration. 3670 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3671 << (int)Record->isUnion(); 3672 Invalid = true; 3673 } 3674 } else { 3675 // This is an anonymous type definition within another anonymous type. 3676 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3677 // not part of standard C++. 3678 Diag(MemRecord->getLocation(), 3679 diag::ext_anonymous_record_with_anonymous_type) 3680 << (int)Record->isUnion(); 3681 } 3682 } else if (isa<AccessSpecDecl>(*Mem)) { 3683 // Any access specifier is fine. 3684 } else { 3685 // We have something that isn't a non-static data 3686 // member. Complain about it. 3687 unsigned DK = diag::err_anonymous_record_bad_member; 3688 if (isa<TypeDecl>(*Mem)) 3689 DK = diag::err_anonymous_record_with_type; 3690 else if (isa<FunctionDecl>(*Mem)) 3691 DK = diag::err_anonymous_record_with_function; 3692 else if (isa<VarDecl>(*Mem)) 3693 DK = diag::err_anonymous_record_with_static; 3694 3695 // Visual C++ allows type definition in anonymous struct or union. 3696 if (getLangOpts().MicrosoftExt && 3697 DK == diag::err_anonymous_record_with_type) 3698 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3699 << (int)Record->isUnion(); 3700 else { 3701 Diag((*Mem)->getLocation(), DK) 3702 << (int)Record->isUnion(); 3703 Invalid = true; 3704 } 3705 } 3706 } 3707 } 3708 3709 if (!Record->isUnion() && !Owner->isRecord()) { 3710 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3711 << (int)getLangOpts().CPlusPlus; 3712 Invalid = true; 3713 } 3714 3715 // Mock up a declarator. 3716 Declarator Dc(DS, Declarator::MemberContext); 3717 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3718 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3719 3720 // Create a declaration for this anonymous struct/union. 3721 NamedDecl *Anon = 0; 3722 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3723 Anon = FieldDecl::Create(Context, OwningClass, 3724 DS.getLocStart(), 3725 Record->getLocation(), 3726 /*IdentifierInfo=*/0, 3727 Context.getTypeDeclType(Record), 3728 TInfo, 3729 /*BitWidth=*/0, /*Mutable=*/false, 3730 /*InitStyle=*/ICIS_NoInit); 3731 Anon->setAccess(AS); 3732 if (getLangOpts().CPlusPlus) 3733 FieldCollector->Add(cast<FieldDecl>(Anon)); 3734 } else { 3735 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3736 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3737 if (SCSpec == DeclSpec::SCS_mutable) { 3738 // mutable can only appear on non-static class members, so it's always 3739 // an error here 3740 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3741 Invalid = true; 3742 SC = SC_None; 3743 } 3744 3745 Anon = VarDecl::Create(Context, Owner, 3746 DS.getLocStart(), 3747 Record->getLocation(), /*IdentifierInfo=*/0, 3748 Context.getTypeDeclType(Record), 3749 TInfo, SC); 3750 3751 // Default-initialize the implicit variable. This initialization will be 3752 // trivial in almost all cases, except if a union member has an in-class 3753 // initializer: 3754 // union { int n = 0; }; 3755 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3756 } 3757 Anon->setImplicit(); 3758 3759 // Add the anonymous struct/union object to the current 3760 // context. We'll be referencing this object when we refer to one of 3761 // its members. 3762 Owner->addDecl(Anon); 3763 3764 // Inject the members of the anonymous struct/union into the owning 3765 // context and into the identifier resolver chain for name lookup 3766 // purposes. 3767 SmallVector<NamedDecl*, 2> Chain; 3768 Chain.push_back(Anon); 3769 3770 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3771 Chain, false)) 3772 Invalid = true; 3773 3774 // Mark this as an anonymous struct/union type. Note that we do not 3775 // do this until after we have already checked and injected the 3776 // members of this anonymous struct/union type, because otherwise 3777 // the members could be injected twice: once by DeclContext when it 3778 // builds its lookup table, and once by 3779 // InjectAnonymousStructOrUnionMembers. 3780 Record->setAnonymousStructOrUnion(true); 3781 3782 if (Invalid) 3783 Anon->setInvalidDecl(); 3784 3785 return Anon; 3786 } 3787 3788 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3789 /// Microsoft C anonymous structure. 3790 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3791 /// Example: 3792 /// 3793 /// struct A { int a; }; 3794 /// struct B { struct A; int b; }; 3795 /// 3796 /// void foo() { 3797 /// B var; 3798 /// var.a = 3; 3799 /// } 3800 /// 3801 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3802 RecordDecl *Record) { 3803 3804 // If there is no Record, get the record via the typedef. 3805 if (!Record) 3806 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3807 3808 // Mock up a declarator. 3809 Declarator Dc(DS, Declarator::TypeNameContext); 3810 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3811 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3812 3813 // Create a declaration for this anonymous struct. 3814 NamedDecl* Anon = FieldDecl::Create(Context, 3815 cast<RecordDecl>(CurContext), 3816 DS.getLocStart(), 3817 DS.getLocStart(), 3818 /*IdentifierInfo=*/0, 3819 Context.getTypeDeclType(Record), 3820 TInfo, 3821 /*BitWidth=*/0, /*Mutable=*/false, 3822 /*InitStyle=*/ICIS_NoInit); 3823 Anon->setImplicit(); 3824 3825 // Add the anonymous struct object to the current context. 3826 CurContext->addDecl(Anon); 3827 3828 // Inject the members of the anonymous struct into the current 3829 // context and into the identifier resolver chain for name lookup 3830 // purposes. 3831 SmallVector<NamedDecl*, 2> Chain; 3832 Chain.push_back(Anon); 3833 3834 RecordDecl *RecordDef = Record->getDefinition(); 3835 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3836 RecordDef, AS_none, 3837 Chain, true)) 3838 Anon->setInvalidDecl(); 3839 3840 return Anon; 3841 } 3842 3843 /// GetNameForDeclarator - Determine the full declaration name for the 3844 /// given Declarator. 3845 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3846 return GetNameFromUnqualifiedId(D.getName()); 3847 } 3848 3849 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3850 DeclarationNameInfo 3851 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3852 DeclarationNameInfo NameInfo; 3853 NameInfo.setLoc(Name.StartLocation); 3854 3855 switch (Name.getKind()) { 3856 3857 case UnqualifiedId::IK_ImplicitSelfParam: 3858 case UnqualifiedId::IK_Identifier: 3859 NameInfo.setName(Name.Identifier); 3860 NameInfo.setLoc(Name.StartLocation); 3861 return NameInfo; 3862 3863 case UnqualifiedId::IK_OperatorFunctionId: 3864 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3865 Name.OperatorFunctionId.Operator)); 3866 NameInfo.setLoc(Name.StartLocation); 3867 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3868 = Name.OperatorFunctionId.SymbolLocations[0]; 3869 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3870 = Name.EndLocation.getRawEncoding(); 3871 return NameInfo; 3872 3873 case UnqualifiedId::IK_LiteralOperatorId: 3874 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3875 Name.Identifier)); 3876 NameInfo.setLoc(Name.StartLocation); 3877 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3878 return NameInfo; 3879 3880 case UnqualifiedId::IK_ConversionFunctionId: { 3881 TypeSourceInfo *TInfo; 3882 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3883 if (Ty.isNull()) 3884 return DeclarationNameInfo(); 3885 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3886 Context.getCanonicalType(Ty))); 3887 NameInfo.setLoc(Name.StartLocation); 3888 NameInfo.setNamedTypeInfo(TInfo); 3889 return NameInfo; 3890 } 3891 3892 case UnqualifiedId::IK_ConstructorName: { 3893 TypeSourceInfo *TInfo; 3894 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3895 if (Ty.isNull()) 3896 return DeclarationNameInfo(); 3897 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3898 Context.getCanonicalType(Ty))); 3899 NameInfo.setLoc(Name.StartLocation); 3900 NameInfo.setNamedTypeInfo(TInfo); 3901 return NameInfo; 3902 } 3903 3904 case UnqualifiedId::IK_ConstructorTemplateId: { 3905 // In well-formed code, we can only have a constructor 3906 // template-id that refers to the current context, so go there 3907 // to find the actual type being constructed. 3908 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3909 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3910 return DeclarationNameInfo(); 3911 3912 // Determine the type of the class being constructed. 3913 QualType CurClassType = Context.getTypeDeclType(CurClass); 3914 3915 // FIXME: Check two things: that the template-id names the same type as 3916 // CurClassType, and that the template-id does not occur when the name 3917 // was qualified. 3918 3919 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3920 Context.getCanonicalType(CurClassType))); 3921 NameInfo.setLoc(Name.StartLocation); 3922 // FIXME: should we retrieve TypeSourceInfo? 3923 NameInfo.setNamedTypeInfo(0); 3924 return NameInfo; 3925 } 3926 3927 case UnqualifiedId::IK_DestructorName: { 3928 TypeSourceInfo *TInfo; 3929 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3930 if (Ty.isNull()) 3931 return DeclarationNameInfo(); 3932 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3933 Context.getCanonicalType(Ty))); 3934 NameInfo.setLoc(Name.StartLocation); 3935 NameInfo.setNamedTypeInfo(TInfo); 3936 return NameInfo; 3937 } 3938 3939 case UnqualifiedId::IK_TemplateId: { 3940 TemplateName TName = Name.TemplateId->Template.get(); 3941 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3942 return Context.getNameForTemplate(TName, TNameLoc); 3943 } 3944 3945 } // switch (Name.getKind()) 3946 3947 llvm_unreachable("Unknown name kind"); 3948 } 3949 3950 static QualType getCoreType(QualType Ty) { 3951 do { 3952 if (Ty->isPointerType() || Ty->isReferenceType()) 3953 Ty = Ty->getPointeeType(); 3954 else if (Ty->isArrayType()) 3955 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3956 else 3957 return Ty.withoutLocalFastQualifiers(); 3958 } while (true); 3959 } 3960 3961 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3962 /// and Definition have "nearly" matching parameters. This heuristic is 3963 /// used to improve diagnostics in the case where an out-of-line function 3964 /// definition doesn't match any declaration within the class or namespace. 3965 /// Also sets Params to the list of indices to the parameters that differ 3966 /// between the declaration and the definition. If hasSimilarParameters 3967 /// returns true and Params is empty, then all of the parameters match. 3968 static bool hasSimilarParameters(ASTContext &Context, 3969 FunctionDecl *Declaration, 3970 FunctionDecl *Definition, 3971 SmallVectorImpl<unsigned> &Params) { 3972 Params.clear(); 3973 if (Declaration->param_size() != Definition->param_size()) 3974 return false; 3975 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3976 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3977 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3978 3979 // The parameter types are identical 3980 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3981 continue; 3982 3983 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3984 QualType DefParamBaseTy = getCoreType(DefParamTy); 3985 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3986 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3987 3988 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3989 (DeclTyName && DeclTyName == DefTyName)) 3990 Params.push_back(Idx); 3991 else // The two parameters aren't even close 3992 return false; 3993 } 3994 3995 return true; 3996 } 3997 3998 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3999 /// declarator needs to be rebuilt in the current instantiation. 4000 /// Any bits of declarator which appear before the name are valid for 4001 /// consideration here. That's specifically the type in the decl spec 4002 /// and the base type in any member-pointer chunks. 4003 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4004 DeclarationName Name) { 4005 // The types we specifically need to rebuild are: 4006 // - typenames, typeofs, and decltypes 4007 // - types which will become injected class names 4008 // Of course, we also need to rebuild any type referencing such a 4009 // type. It's safest to just say "dependent", but we call out a 4010 // few cases here. 4011 4012 DeclSpec &DS = D.getMutableDeclSpec(); 4013 switch (DS.getTypeSpecType()) { 4014 case DeclSpec::TST_typename: 4015 case DeclSpec::TST_typeofType: 4016 case DeclSpec::TST_underlyingType: 4017 case DeclSpec::TST_atomic: { 4018 // Grab the type from the parser. 4019 TypeSourceInfo *TSI = 0; 4020 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4021 if (T.isNull() || !T->isDependentType()) break; 4022 4023 // Make sure there's a type source info. This isn't really much 4024 // of a waste; most dependent types should have type source info 4025 // attached already. 4026 if (!TSI) 4027 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4028 4029 // Rebuild the type in the current instantiation. 4030 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4031 if (!TSI) return true; 4032 4033 // Store the new type back in the decl spec. 4034 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4035 DS.UpdateTypeRep(LocType); 4036 break; 4037 } 4038 4039 case DeclSpec::TST_decltype: 4040 case DeclSpec::TST_typeofExpr: { 4041 Expr *E = DS.getRepAsExpr(); 4042 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4043 if (Result.isInvalid()) return true; 4044 DS.UpdateExprRep(Result.get()); 4045 break; 4046 } 4047 4048 default: 4049 // Nothing to do for these decl specs. 4050 break; 4051 } 4052 4053 // It doesn't matter what order we do this in. 4054 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4055 DeclaratorChunk &Chunk = D.getTypeObject(I); 4056 4057 // The only type information in the declarator which can come 4058 // before the declaration name is the base type of a member 4059 // pointer. 4060 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4061 continue; 4062 4063 // Rebuild the scope specifier in-place. 4064 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4065 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4066 return true; 4067 } 4068 4069 return false; 4070 } 4071 4072 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4073 D.setFunctionDefinitionKind(FDK_Declaration); 4074 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4075 4076 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4077 Dcl && Dcl->getDeclContext()->isFileContext()) 4078 Dcl->setTopLevelDeclInObjCContainer(); 4079 4080 return Dcl; 4081 } 4082 4083 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4084 /// If T is the name of a class, then each of the following shall have a 4085 /// name different from T: 4086 /// - every static data member of class T; 4087 /// - every member function of class T 4088 /// - every member of class T that is itself a type; 4089 /// \returns true if the declaration name violates these rules. 4090 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4091 DeclarationNameInfo NameInfo) { 4092 DeclarationName Name = NameInfo.getName(); 4093 4094 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4095 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4096 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4097 return true; 4098 } 4099 4100 return false; 4101 } 4102 4103 /// \brief Diagnose a declaration whose declarator-id has the given 4104 /// nested-name-specifier. 4105 /// 4106 /// \param SS The nested-name-specifier of the declarator-id. 4107 /// 4108 /// \param DC The declaration context to which the nested-name-specifier 4109 /// resolves. 4110 /// 4111 /// \param Name The name of the entity being declared. 4112 /// 4113 /// \param Loc The location of the name of the entity being declared. 4114 /// 4115 /// \returns true if we cannot safely recover from this error, false otherwise. 4116 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4117 DeclarationName Name, 4118 SourceLocation Loc) { 4119 DeclContext *Cur = CurContext; 4120 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4121 Cur = Cur->getParent(); 4122 4123 // If the user provided a superfluous scope specifier that refers back to the 4124 // class in which the entity is already declared, diagnose and ignore it. 4125 // 4126 // class X { 4127 // void X::f(); 4128 // }; 4129 // 4130 // Note, it was once ill-formed to give redundant qualification in all 4131 // contexts, but that rule was removed by DR482. 4132 if (Cur->Equals(DC)) { 4133 if (Cur->isRecord()) { 4134 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4135 : diag::err_member_extra_qualification) 4136 << Name << FixItHint::CreateRemoval(SS.getRange()); 4137 SS.clear(); 4138 } else { 4139 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4140 } 4141 return false; 4142 } 4143 4144 // Check whether the qualifying scope encloses the scope of the original 4145 // declaration. 4146 if (!Cur->Encloses(DC)) { 4147 if (Cur->isRecord()) 4148 Diag(Loc, diag::err_member_qualification) 4149 << Name << SS.getRange(); 4150 else if (isa<TranslationUnitDecl>(DC)) 4151 Diag(Loc, diag::err_invalid_declarator_global_scope) 4152 << Name << SS.getRange(); 4153 else if (isa<FunctionDecl>(Cur)) 4154 Diag(Loc, diag::err_invalid_declarator_in_function) 4155 << Name << SS.getRange(); 4156 else if (isa<BlockDecl>(Cur)) 4157 Diag(Loc, diag::err_invalid_declarator_in_block) 4158 << Name << SS.getRange(); 4159 else 4160 Diag(Loc, diag::err_invalid_declarator_scope) 4161 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4162 4163 return true; 4164 } 4165 4166 if (Cur->isRecord()) { 4167 // Cannot qualify members within a class. 4168 Diag(Loc, diag::err_member_qualification) 4169 << Name << SS.getRange(); 4170 SS.clear(); 4171 4172 // C++ constructors and destructors with incorrect scopes can break 4173 // our AST invariants by having the wrong underlying types. If 4174 // that's the case, then drop this declaration entirely. 4175 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4176 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4177 !Context.hasSameType(Name.getCXXNameType(), 4178 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4179 return true; 4180 4181 return false; 4182 } 4183 4184 // C++11 [dcl.meaning]p1: 4185 // [...] "The nested-name-specifier of the qualified declarator-id shall 4186 // not begin with a decltype-specifer" 4187 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4188 while (SpecLoc.getPrefix()) 4189 SpecLoc = SpecLoc.getPrefix(); 4190 if (dyn_cast_or_null<DecltypeType>( 4191 SpecLoc.getNestedNameSpecifier()->getAsType())) 4192 Diag(Loc, diag::err_decltype_in_declarator) 4193 << SpecLoc.getTypeLoc().getSourceRange(); 4194 4195 return false; 4196 } 4197 4198 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4199 MultiTemplateParamsArg TemplateParamLists) { 4200 // TODO: consider using NameInfo for diagnostic. 4201 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4202 DeclarationName Name = NameInfo.getName(); 4203 4204 // All of these full declarators require an identifier. If it doesn't have 4205 // one, the ParsedFreeStandingDeclSpec action should be used. 4206 if (!Name) { 4207 if (!D.isInvalidType()) // Reject this if we think it is valid. 4208 Diag(D.getDeclSpec().getLocStart(), 4209 diag::err_declarator_need_ident) 4210 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4211 return 0; 4212 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4213 return 0; 4214 4215 // The scope passed in may not be a decl scope. Zip up the scope tree until 4216 // we find one that is. 4217 while ((S->getFlags() & Scope::DeclScope) == 0 || 4218 (S->getFlags() & Scope::TemplateParamScope) != 0) 4219 S = S->getParent(); 4220 4221 DeclContext *DC = CurContext; 4222 if (D.getCXXScopeSpec().isInvalid()) 4223 D.setInvalidType(); 4224 else if (D.getCXXScopeSpec().isSet()) { 4225 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4226 UPPC_DeclarationQualifier)) 4227 return 0; 4228 4229 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4230 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4231 if (!DC || isa<EnumDecl>(DC)) { 4232 // If we could not compute the declaration context, it's because the 4233 // declaration context is dependent but does not refer to a class, 4234 // class template, or class template partial specialization. Complain 4235 // and return early, to avoid the coming semantic disaster. 4236 Diag(D.getIdentifierLoc(), 4237 diag::err_template_qualified_declarator_no_match) 4238 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 4239 << D.getCXXScopeSpec().getRange(); 4240 return 0; 4241 } 4242 bool IsDependentContext = DC->isDependentContext(); 4243 4244 if (!IsDependentContext && 4245 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4246 return 0; 4247 4248 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4249 Diag(D.getIdentifierLoc(), 4250 diag::err_member_def_undefined_record) 4251 << Name << DC << D.getCXXScopeSpec().getRange(); 4252 D.setInvalidType(); 4253 } else if (!D.getDeclSpec().isFriendSpecified()) { 4254 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4255 Name, D.getIdentifierLoc())) { 4256 if (DC->isRecord()) 4257 return 0; 4258 4259 D.setInvalidType(); 4260 } 4261 } 4262 4263 // Check whether we need to rebuild the type of the given 4264 // declaration in the current instantiation. 4265 if (EnteringContext && IsDependentContext && 4266 TemplateParamLists.size() != 0) { 4267 ContextRAII SavedContext(*this, DC); 4268 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4269 D.setInvalidType(); 4270 } 4271 } 4272 4273 if (DiagnoseClassNameShadow(DC, NameInfo)) 4274 // If this is a typedef, we'll end up spewing multiple diagnostics. 4275 // Just return early; it's safer. 4276 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4277 return 0; 4278 4279 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4280 QualType R = TInfo->getType(); 4281 4282 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4283 UPPC_DeclarationType)) 4284 D.setInvalidType(); 4285 4286 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4287 ForRedeclaration); 4288 4289 // See if this is a redefinition of a variable in the same scope. 4290 if (!D.getCXXScopeSpec().isSet()) { 4291 bool IsLinkageLookup = false; 4292 bool CreateBuiltins = false; 4293 4294 // If the declaration we're planning to build will be a function 4295 // or object with linkage, then look for another declaration with 4296 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4297 // 4298 // If the declaration we're planning to build will be declared with 4299 // external linkage in the translation unit, create any builtin with 4300 // the same name. 4301 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4302 /* Do nothing*/; 4303 else if (CurContext->isFunctionOrMethod() && 4304 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4305 R->isFunctionType())) { 4306 IsLinkageLookup = true; 4307 CreateBuiltins = 4308 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4309 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4310 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4311 CreateBuiltins = true; 4312 4313 if (IsLinkageLookup) 4314 Previous.clear(LookupRedeclarationWithLinkage); 4315 4316 LookupName(Previous, S, CreateBuiltins); 4317 } else { // Something like "int foo::x;" 4318 LookupQualifiedName(Previous, DC); 4319 4320 // C++ [dcl.meaning]p1: 4321 // When the declarator-id is qualified, the declaration shall refer to a 4322 // previously declared member of the class or namespace to which the 4323 // qualifier refers (or, in the case of a namespace, of an element of the 4324 // inline namespace set of that namespace (7.3.1)) or to a specialization 4325 // thereof; [...] 4326 // 4327 // Note that we already checked the context above, and that we do not have 4328 // enough information to make sure that Previous contains the declaration 4329 // we want to match. For example, given: 4330 // 4331 // class X { 4332 // void f(); 4333 // void f(float); 4334 // }; 4335 // 4336 // void X::f(int) { } // ill-formed 4337 // 4338 // In this case, Previous will point to the overload set 4339 // containing the two f's declared in X, but neither of them 4340 // matches. 4341 4342 // C++ [dcl.meaning]p1: 4343 // [...] the member shall not merely have been introduced by a 4344 // using-declaration in the scope of the class or namespace nominated by 4345 // the nested-name-specifier of the declarator-id. 4346 RemoveUsingDecls(Previous); 4347 } 4348 4349 if (Previous.isSingleResult() && 4350 Previous.getFoundDecl()->isTemplateParameter()) { 4351 // Maybe we will complain about the shadowed template parameter. 4352 if (!D.isInvalidType()) 4353 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4354 Previous.getFoundDecl()); 4355 4356 // Just pretend that we didn't see the previous declaration. 4357 Previous.clear(); 4358 } 4359 4360 // In C++, the previous declaration we find might be a tag type 4361 // (class or enum). In this case, the new declaration will hide the 4362 // tag type. Note that this does does not apply if we're declaring a 4363 // typedef (C++ [dcl.typedef]p4). 4364 if (Previous.isSingleTagDecl() && 4365 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4366 Previous.clear(); 4367 4368 // Check that there are no default arguments other than in the parameters 4369 // of a function declaration (C++ only). 4370 if (getLangOpts().CPlusPlus) 4371 CheckExtraCXXDefaultArguments(D); 4372 4373 NamedDecl *New; 4374 4375 bool AddToScope = true; 4376 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4377 if (TemplateParamLists.size()) { 4378 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4379 return 0; 4380 } 4381 4382 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4383 } else if (R->isFunctionType()) { 4384 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4385 TemplateParamLists, 4386 AddToScope); 4387 } else { 4388 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4389 AddToScope); 4390 } 4391 4392 if (New == 0) 4393 return 0; 4394 4395 // If this has an identifier and is not an invalid redeclaration or 4396 // function template specialization, add it to the scope stack. 4397 if (New->getDeclName() && AddToScope && 4398 !(D.isRedeclaration() && New->isInvalidDecl())) { 4399 // Only make a locally-scoped extern declaration visible if it is the first 4400 // declaration of this entity. Qualified lookup for such an entity should 4401 // only find this declaration if there is no visible declaration of it. 4402 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4403 PushOnScopeChains(New, S, AddToContext); 4404 if (!AddToContext) 4405 CurContext->addHiddenDecl(New); 4406 } 4407 4408 return New; 4409 } 4410 4411 /// Helper method to turn variable array types into constant array 4412 /// types in certain situations which would otherwise be errors (for 4413 /// GCC compatibility). 4414 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4415 ASTContext &Context, 4416 bool &SizeIsNegative, 4417 llvm::APSInt &Oversized) { 4418 // This method tries to turn a variable array into a constant 4419 // array even when the size isn't an ICE. This is necessary 4420 // for compatibility with code that depends on gcc's buggy 4421 // constant expression folding, like struct {char x[(int)(char*)2];} 4422 SizeIsNegative = false; 4423 Oversized = 0; 4424 4425 if (T->isDependentType()) 4426 return QualType(); 4427 4428 QualifierCollector Qs; 4429 const Type *Ty = Qs.strip(T); 4430 4431 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4432 QualType Pointee = PTy->getPointeeType(); 4433 QualType FixedType = 4434 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4435 Oversized); 4436 if (FixedType.isNull()) return FixedType; 4437 FixedType = Context.getPointerType(FixedType); 4438 return Qs.apply(Context, FixedType); 4439 } 4440 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4441 QualType Inner = PTy->getInnerType(); 4442 QualType FixedType = 4443 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4444 Oversized); 4445 if (FixedType.isNull()) return FixedType; 4446 FixedType = Context.getParenType(FixedType); 4447 return Qs.apply(Context, FixedType); 4448 } 4449 4450 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4451 if (!VLATy) 4452 return QualType(); 4453 // FIXME: We should probably handle this case 4454 if (VLATy->getElementType()->isVariablyModifiedType()) 4455 return QualType(); 4456 4457 llvm::APSInt Res; 4458 if (!VLATy->getSizeExpr() || 4459 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4460 return QualType(); 4461 4462 // Check whether the array size is negative. 4463 if (Res.isSigned() && Res.isNegative()) { 4464 SizeIsNegative = true; 4465 return QualType(); 4466 } 4467 4468 // Check whether the array is too large to be addressed. 4469 unsigned ActiveSizeBits 4470 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4471 Res); 4472 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4473 Oversized = Res; 4474 return QualType(); 4475 } 4476 4477 return Context.getConstantArrayType(VLATy->getElementType(), 4478 Res, ArrayType::Normal, 0); 4479 } 4480 4481 static void 4482 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4483 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4484 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4485 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4486 DstPTL.getPointeeLoc()); 4487 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4488 return; 4489 } 4490 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4491 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4492 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4493 DstPTL.getInnerLoc()); 4494 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4495 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4496 return; 4497 } 4498 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4499 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4500 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4501 TypeLoc DstElemTL = DstATL.getElementLoc(); 4502 DstElemTL.initializeFullCopy(SrcElemTL); 4503 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4504 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4505 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4506 } 4507 4508 /// Helper method to turn variable array types into constant array 4509 /// types in certain situations which would otherwise be errors (for 4510 /// GCC compatibility). 4511 static TypeSourceInfo* 4512 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4513 ASTContext &Context, 4514 bool &SizeIsNegative, 4515 llvm::APSInt &Oversized) { 4516 QualType FixedTy 4517 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4518 SizeIsNegative, Oversized); 4519 if (FixedTy.isNull()) 4520 return 0; 4521 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4522 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4523 FixedTInfo->getTypeLoc()); 4524 return FixedTInfo; 4525 } 4526 4527 /// \brief Register the given locally-scoped extern "C" declaration so 4528 /// that it can be found later for redeclarations. We include any extern "C" 4529 /// declaration that is not visible in the translation unit here, not just 4530 /// function-scope declarations. 4531 void 4532 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4533 if (!getLangOpts().CPlusPlus && 4534 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4535 // Don't need to track declarations in the TU in C. 4536 return; 4537 4538 // Note that we have a locally-scoped external with this name. 4539 // FIXME: There can be multiple such declarations if they are functions marked 4540 // __attribute__((overloadable)) declared in function scope in C. 4541 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4542 } 4543 4544 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4545 if (ExternalSource) { 4546 // Load locally-scoped external decls from the external source. 4547 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4548 SmallVector<NamedDecl *, 4> Decls; 4549 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4550 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4551 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4552 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4553 if (Pos == LocallyScopedExternCDecls.end()) 4554 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4555 } 4556 } 4557 4558 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4559 return D ? D->getMostRecentDecl() : 0; 4560 } 4561 4562 /// \brief Diagnose function specifiers on a declaration of an identifier that 4563 /// does not identify a function. 4564 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4565 // FIXME: We should probably indicate the identifier in question to avoid 4566 // confusion for constructs like "inline int a(), b;" 4567 if (DS.isInlineSpecified()) 4568 Diag(DS.getInlineSpecLoc(), 4569 diag::err_inline_non_function); 4570 4571 if (DS.isVirtualSpecified()) 4572 Diag(DS.getVirtualSpecLoc(), 4573 diag::err_virtual_non_function); 4574 4575 if (DS.isExplicitSpecified()) 4576 Diag(DS.getExplicitSpecLoc(), 4577 diag::err_explicit_non_function); 4578 4579 if (DS.isNoreturnSpecified()) 4580 Diag(DS.getNoreturnSpecLoc(), 4581 diag::err_noreturn_non_function); 4582 } 4583 4584 NamedDecl* 4585 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4586 TypeSourceInfo *TInfo, LookupResult &Previous) { 4587 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4588 if (D.getCXXScopeSpec().isSet()) { 4589 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4590 << D.getCXXScopeSpec().getRange(); 4591 D.setInvalidType(); 4592 // Pretend we didn't see the scope specifier. 4593 DC = CurContext; 4594 Previous.clear(); 4595 } 4596 4597 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4598 4599 if (D.getDeclSpec().isConstexprSpecified()) 4600 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4601 << 1; 4602 4603 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4604 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4605 << D.getName().getSourceRange(); 4606 return 0; 4607 } 4608 4609 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4610 if (!NewTD) return 0; 4611 4612 // Handle attributes prior to checking for duplicates in MergeVarDecl 4613 ProcessDeclAttributes(S, NewTD, D); 4614 4615 CheckTypedefForVariablyModifiedType(S, NewTD); 4616 4617 bool Redeclaration = D.isRedeclaration(); 4618 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4619 D.setRedeclaration(Redeclaration); 4620 return ND; 4621 } 4622 4623 void 4624 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4625 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4626 // then it shall have block scope. 4627 // Note that variably modified types must be fixed before merging the decl so 4628 // that redeclarations will match. 4629 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4630 QualType T = TInfo->getType(); 4631 if (T->isVariablyModifiedType()) { 4632 getCurFunction()->setHasBranchProtectedScope(); 4633 4634 if (S->getFnParent() == 0) { 4635 bool SizeIsNegative; 4636 llvm::APSInt Oversized; 4637 TypeSourceInfo *FixedTInfo = 4638 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4639 SizeIsNegative, 4640 Oversized); 4641 if (FixedTInfo) { 4642 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4643 NewTD->setTypeSourceInfo(FixedTInfo); 4644 } else { 4645 if (SizeIsNegative) 4646 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4647 else if (T->isVariableArrayType()) 4648 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4649 else if (Oversized.getBoolValue()) 4650 Diag(NewTD->getLocation(), diag::err_array_too_large) 4651 << Oversized.toString(10); 4652 else 4653 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4654 NewTD->setInvalidDecl(); 4655 } 4656 } 4657 } 4658 } 4659 4660 4661 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4662 /// declares a typedef-name, either using the 'typedef' type specifier or via 4663 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4664 NamedDecl* 4665 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4666 LookupResult &Previous, bool &Redeclaration) { 4667 // Merge the decl with the existing one if appropriate. If the decl is 4668 // in an outer scope, it isn't the same thing. 4669 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4670 /*AllowInlineNamespace*/false); 4671 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4672 if (!Previous.empty()) { 4673 Redeclaration = true; 4674 MergeTypedefNameDecl(NewTD, Previous); 4675 } 4676 4677 // If this is the C FILE type, notify the AST context. 4678 if (IdentifierInfo *II = NewTD->getIdentifier()) 4679 if (!NewTD->isInvalidDecl() && 4680 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4681 if (II->isStr("FILE")) 4682 Context.setFILEDecl(NewTD); 4683 else if (II->isStr("jmp_buf")) 4684 Context.setjmp_bufDecl(NewTD); 4685 else if (II->isStr("sigjmp_buf")) 4686 Context.setsigjmp_bufDecl(NewTD); 4687 else if (II->isStr("ucontext_t")) 4688 Context.setucontext_tDecl(NewTD); 4689 } 4690 4691 return NewTD; 4692 } 4693 4694 /// \brief Determines whether the given declaration is an out-of-scope 4695 /// previous declaration. 4696 /// 4697 /// This routine should be invoked when name lookup has found a 4698 /// previous declaration (PrevDecl) that is not in the scope where a 4699 /// new declaration by the same name is being introduced. If the new 4700 /// declaration occurs in a local scope, previous declarations with 4701 /// linkage may still be considered previous declarations (C99 4702 /// 6.2.2p4-5, C++ [basic.link]p6). 4703 /// 4704 /// \param PrevDecl the previous declaration found by name 4705 /// lookup 4706 /// 4707 /// \param DC the context in which the new declaration is being 4708 /// declared. 4709 /// 4710 /// \returns true if PrevDecl is an out-of-scope previous declaration 4711 /// for a new delcaration with the same name. 4712 static bool 4713 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4714 ASTContext &Context) { 4715 if (!PrevDecl) 4716 return false; 4717 4718 if (!PrevDecl->hasLinkage()) 4719 return false; 4720 4721 if (Context.getLangOpts().CPlusPlus) { 4722 // C++ [basic.link]p6: 4723 // If there is a visible declaration of an entity with linkage 4724 // having the same name and type, ignoring entities declared 4725 // outside the innermost enclosing namespace scope, the block 4726 // scope declaration declares that same entity and receives the 4727 // linkage of the previous declaration. 4728 DeclContext *OuterContext = DC->getRedeclContext(); 4729 if (!OuterContext->isFunctionOrMethod()) 4730 // This rule only applies to block-scope declarations. 4731 return false; 4732 4733 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4734 if (PrevOuterContext->isRecord()) 4735 // We found a member function: ignore it. 4736 return false; 4737 4738 // Find the innermost enclosing namespace for the new and 4739 // previous declarations. 4740 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4741 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4742 4743 // The previous declaration is in a different namespace, so it 4744 // isn't the same function. 4745 if (!OuterContext->Equals(PrevOuterContext)) 4746 return false; 4747 } 4748 4749 return true; 4750 } 4751 4752 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4753 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4754 if (!SS.isSet()) return; 4755 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4756 } 4757 4758 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4759 QualType type = decl->getType(); 4760 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4761 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4762 // Various kinds of declaration aren't allowed to be __autoreleasing. 4763 unsigned kind = -1U; 4764 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4765 if (var->hasAttr<BlocksAttr>()) 4766 kind = 0; // __block 4767 else if (!var->hasLocalStorage()) 4768 kind = 1; // global 4769 } else if (isa<ObjCIvarDecl>(decl)) { 4770 kind = 3; // ivar 4771 } else if (isa<FieldDecl>(decl)) { 4772 kind = 2; // field 4773 } 4774 4775 if (kind != -1U) { 4776 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4777 << kind; 4778 } 4779 } else if (lifetime == Qualifiers::OCL_None) { 4780 // Try to infer lifetime. 4781 if (!type->isObjCLifetimeType()) 4782 return false; 4783 4784 lifetime = type->getObjCARCImplicitLifetime(); 4785 type = Context.getLifetimeQualifiedType(type, lifetime); 4786 decl->setType(type); 4787 } 4788 4789 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4790 // Thread-local variables cannot have lifetime. 4791 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4792 var->getTLSKind()) { 4793 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4794 << var->getType(); 4795 return true; 4796 } 4797 } 4798 4799 return false; 4800 } 4801 4802 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4803 // 'weak' only applies to declarations with external linkage. 4804 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4805 if (!ND.isExternallyVisible()) { 4806 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4807 ND.dropAttr<WeakAttr>(); 4808 } 4809 } 4810 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4811 if (ND.isExternallyVisible()) { 4812 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4813 ND.dropAttr<WeakRefAttr>(); 4814 } 4815 } 4816 4817 // 'selectany' only applies to externally visible varable declarations. 4818 // It does not apply to functions. 4819 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4820 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4821 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4822 ND.dropAttr<SelectAnyAttr>(); 4823 } 4824 } 4825 } 4826 4827 /// Given that we are within the definition of the given function, 4828 /// will that definition behave like C99's 'inline', where the 4829 /// definition is discarded except for optimization purposes? 4830 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4831 // Try to avoid calling GetGVALinkageForFunction. 4832 4833 // All cases of this require the 'inline' keyword. 4834 if (!FD->isInlined()) return false; 4835 4836 // This is only possible in C++ with the gnu_inline attribute. 4837 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4838 return false; 4839 4840 // Okay, go ahead and call the relatively-more-expensive function. 4841 4842 #ifndef NDEBUG 4843 // AST quite reasonably asserts that it's working on a function 4844 // definition. We don't really have a way to tell it that we're 4845 // currently defining the function, so just lie to it in +Asserts 4846 // builds. This is an awful hack. 4847 FD->setLazyBody(1); 4848 #endif 4849 4850 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4851 4852 #ifndef NDEBUG 4853 FD->setLazyBody(0); 4854 #endif 4855 4856 return isC99Inline; 4857 } 4858 4859 /// Determine whether a variable is extern "C" prior to attaching 4860 /// an initializer. We can't just call isExternC() here, because that 4861 /// will also compute and cache whether the declaration is externally 4862 /// visible, which might change when we attach the initializer. 4863 /// 4864 /// This can only be used if the declaration is known to not be a 4865 /// redeclaration of an internal linkage declaration. 4866 /// 4867 /// For instance: 4868 /// 4869 /// auto x = []{}; 4870 /// 4871 /// Attaching the initializer here makes this declaration not externally 4872 /// visible, because its type has internal linkage. 4873 /// 4874 /// FIXME: This is a hack. 4875 template<typename T> 4876 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4877 if (S.getLangOpts().CPlusPlus) { 4878 // In C++, the overloadable attribute negates the effects of extern "C". 4879 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4880 return false; 4881 } 4882 return D->isExternC(); 4883 } 4884 4885 static bool shouldConsiderLinkage(const VarDecl *VD) { 4886 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4887 if (DC->isFunctionOrMethod()) 4888 return VD->hasExternalStorage(); 4889 if (DC->isFileContext()) 4890 return true; 4891 if (DC->isRecord()) 4892 return false; 4893 llvm_unreachable("Unexpected context"); 4894 } 4895 4896 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4897 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4898 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4899 return true; 4900 if (DC->isRecord()) 4901 return false; 4902 llvm_unreachable("Unexpected context"); 4903 } 4904 4905 /// Adjust the \c DeclContext for a function or variable that might be a 4906 /// function-local external declaration. 4907 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 4908 if (!DC->isFunctionOrMethod()) 4909 return false; 4910 4911 // If this is a local extern function or variable declared within a function 4912 // template, don't add it into the enclosing namespace scope until it is 4913 // instantiated; it might have a dependent type right now. 4914 if (DC->isDependentContext()) 4915 return true; 4916 4917 // C++11 [basic.link]p7: 4918 // When a block scope declaration of an entity with linkage is not found to 4919 // refer to some other declaration, then that entity is a member of the 4920 // innermost enclosing namespace. 4921 // 4922 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 4923 // semantically-enclosing namespace, not a lexically-enclosing one. 4924 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 4925 DC = DC->getParent(); 4926 return true; 4927 } 4928 4929 NamedDecl * 4930 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4931 TypeSourceInfo *TInfo, LookupResult &Previous, 4932 MultiTemplateParamsArg TemplateParamLists, 4933 bool &AddToScope) { 4934 QualType R = TInfo->getType(); 4935 DeclarationName Name = GetNameForDeclarator(D).getName(); 4936 4937 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4938 VarDecl::StorageClass SC = 4939 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 4940 4941 DeclContext *OriginalDC = DC; 4942 bool IsLocalExternDecl = SC == SC_Extern && 4943 adjustContextForLocalExternDecl(DC); 4944 4945 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) { 4946 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4947 // half array type (unless the cl_khr_fp16 extension is enabled). 4948 if (Context.getBaseElementType(R)->isHalfType()) { 4949 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4950 D.setInvalidType(); 4951 } 4952 } 4953 4954 if (SCSpec == DeclSpec::SCS_mutable) { 4955 // mutable can only appear on non-static class members, so it's always 4956 // an error here 4957 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4958 D.setInvalidType(); 4959 SC = SC_None; 4960 } 4961 4962 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 4963 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 4964 D.getDeclSpec().getStorageClassSpecLoc())) { 4965 // In C++11, the 'register' storage class specifier is deprecated. 4966 // Suppress the warning in system macros, it's used in macros in some 4967 // popular C system headers, such as in glibc's htonl() macro. 4968 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4969 diag::warn_deprecated_register) 4970 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4971 } 4972 4973 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4974 if (!II) { 4975 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4976 << Name; 4977 return 0; 4978 } 4979 4980 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4981 4982 if (!DC->isRecord() && S->getFnParent() == 0) { 4983 // C99 6.9p2: The storage-class specifiers auto and register shall not 4984 // appear in the declaration specifiers in an external declaration. 4985 if (SC == SC_Auto || SC == SC_Register) { 4986 // If this is a register variable with an asm label specified, then this 4987 // is a GNU extension. 4988 if (SC == SC_Register && D.getAsmLabel()) 4989 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4990 else 4991 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4992 D.setInvalidType(); 4993 } 4994 } 4995 4996 if (getLangOpts().OpenCL) { 4997 // Set up the special work-group-local storage class for variables in the 4998 // OpenCL __local address space. 4999 if (R.getAddressSpace() == LangAS::opencl_local) { 5000 SC = SC_OpenCLWorkGroupLocal; 5001 } 5002 5003 // OpenCL v1.2 s6.9.b p4: 5004 // The sampler type cannot be used with the __local and __global address 5005 // space qualifiers. 5006 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5007 R.getAddressSpace() == LangAS::opencl_global)) { 5008 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5009 } 5010 5011 // OpenCL 1.2 spec, p6.9 r: 5012 // The event type cannot be used to declare a program scope variable. 5013 // The event type cannot be used with the __local, __constant and __global 5014 // address space qualifiers. 5015 if (R->isEventT()) { 5016 if (S->getParent() == 0) { 5017 Diag(D.getLocStart(), diag::err_event_t_global_var); 5018 D.setInvalidType(); 5019 } 5020 5021 if (R.getAddressSpace()) { 5022 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5023 D.setInvalidType(); 5024 } 5025 } 5026 } 5027 5028 bool IsExplicitSpecialization = false; 5029 bool IsVariableTemplateSpecialization = false; 5030 bool IsPartialSpecialization = false; 5031 bool IsVariableTemplate = false; 5032 VarTemplateDecl *PrevVarTemplate = 0; 5033 VarDecl *NewVD = 0; 5034 VarTemplateDecl *NewTemplate = 0; 5035 if (!getLangOpts().CPlusPlus) { 5036 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5037 D.getIdentifierLoc(), II, 5038 R, TInfo, SC); 5039 5040 if (D.isInvalidType()) 5041 NewVD->setInvalidDecl(); 5042 } else { 5043 bool Invalid = false; 5044 5045 if (DC->isRecord() && !CurContext->isRecord()) { 5046 // This is an out-of-line definition of a static data member. 5047 switch (SC) { 5048 case SC_None: 5049 break; 5050 case SC_Static: 5051 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5052 diag::err_static_out_of_line) 5053 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5054 break; 5055 case SC_Auto: 5056 case SC_Register: 5057 case SC_Extern: 5058 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5059 // to names of variables declared in a block or to function parameters. 5060 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5061 // of class members 5062 5063 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5064 diag::err_storage_class_for_static_member) 5065 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5066 break; 5067 case SC_PrivateExtern: 5068 llvm_unreachable("C storage class in c++!"); 5069 case SC_OpenCLWorkGroupLocal: 5070 llvm_unreachable("OpenCL storage class in c++!"); 5071 } 5072 } 5073 5074 if (SC == SC_Static && CurContext->isRecord()) { 5075 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5076 if (RD->isLocalClass()) 5077 Diag(D.getIdentifierLoc(), 5078 diag::err_static_data_member_not_allowed_in_local_class) 5079 << Name << RD->getDeclName(); 5080 5081 // C++98 [class.union]p1: If a union contains a static data member, 5082 // the program is ill-formed. C++11 drops this restriction. 5083 if (RD->isUnion()) 5084 Diag(D.getIdentifierLoc(), 5085 getLangOpts().CPlusPlus11 5086 ? diag::warn_cxx98_compat_static_data_member_in_union 5087 : diag::ext_static_data_member_in_union) << Name; 5088 // We conservatively disallow static data members in anonymous structs. 5089 else if (!RD->getDeclName()) 5090 Diag(D.getIdentifierLoc(), 5091 diag::err_static_data_member_not_allowed_in_anon_struct) 5092 << Name << RD->isUnion(); 5093 } 5094 } 5095 5096 NamedDecl *PrevDecl = 0; 5097 if (Previous.begin() != Previous.end()) 5098 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 5099 PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl); 5100 5101 // Match up the template parameter lists with the scope specifier, then 5102 // determine whether we have a template or a template specialization. 5103 TemplateParameterList *TemplateParams = 5104 MatchTemplateParametersToScopeSpecifier( 5105 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5106 D.getCXXScopeSpec(), TemplateParamLists, 5107 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5108 if (TemplateParams) { 5109 if (!TemplateParams->size() && 5110 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5111 // There is an extraneous 'template<>' for this variable. Complain 5112 // about it, but allow the declaration of the variable. 5113 Diag(TemplateParams->getTemplateLoc(), 5114 diag::err_template_variable_noparams) 5115 << II 5116 << SourceRange(TemplateParams->getTemplateLoc(), 5117 TemplateParams->getRAngleLoc()); 5118 } else { 5119 // Only C++1y supports variable templates (N3651). 5120 Diag(D.getIdentifierLoc(), 5121 getLangOpts().CPlusPlus1y 5122 ? diag::warn_cxx11_compat_variable_template 5123 : diag::ext_variable_template); 5124 5125 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5126 // This is an explicit specialization or a partial specialization. 5127 // Check that we can declare a specialization here 5128 5129 IsVariableTemplateSpecialization = true; 5130 IsPartialSpecialization = TemplateParams->size() > 0; 5131 5132 } else { // if (TemplateParams->size() > 0) 5133 // This is a template declaration. 5134 IsVariableTemplate = true; 5135 5136 // Check that we can declare a template here. 5137 if (CheckTemplateDeclScope(S, TemplateParams)) 5138 return 0; 5139 5140 // If there is a previous declaration with the same name, check 5141 // whether this is a valid redeclaration. 5142 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S)) 5143 PrevDecl = PrevVarTemplate = 0; 5144 5145 if (PrevVarTemplate) { 5146 // Ensure that the template parameter lists are compatible. 5147 if (!TemplateParameterListsAreEqual( 5148 TemplateParams, PrevVarTemplate->getTemplateParameters(), 5149 /*Complain=*/true, TPL_TemplateMatch)) 5150 return 0; 5151 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 5152 // Maybe we will complain about the shadowed template parameter. 5153 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5154 5155 // Just pretend that we didn't see the previous declaration. 5156 PrevDecl = 0; 5157 } else if (PrevDecl) { 5158 // C++ [temp]p5: 5159 // ... a template name declared in namespace scope or in class 5160 // scope shall be unique in that scope. 5161 Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind) 5162 << Name; 5163 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5164 return 0; 5165 } 5166 5167 // Check the template parameter list of this declaration, possibly 5168 // merging in the template parameter list from the previous variable 5169 // template declaration. 5170 if (CheckTemplateParameterList( 5171 TemplateParams, 5172 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5173 : 0, 5174 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5175 DC->isDependentContext()) 5176 ? TPC_ClassTemplateMember 5177 : TPC_VarTemplate)) 5178 Invalid = true; 5179 5180 if (D.getCXXScopeSpec().isSet()) { 5181 // If the name of the template was qualified, we must be defining 5182 // the template out-of-line. 5183 if (!D.getCXXScopeSpec().isInvalid() && !Invalid && 5184 !PrevVarTemplate) { 5185 Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match) 5186 << Name << DC << /*IsDefinition*/true 5187 << D.getCXXScopeSpec().getRange(); 5188 Invalid = true; 5189 } 5190 } 5191 } 5192 } 5193 } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5194 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5195 5196 // We have encountered something that the user meant to be a 5197 // specialization (because it has explicitly-specified template 5198 // arguments) but that was not introduced with a "template<>" (or had 5199 // too few of them). 5200 // FIXME: Differentiate between attempts for explicit instantiations 5201 // (starting with "template") and the rest. 5202 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5203 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5204 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5205 "template<> "); 5206 IsVariableTemplateSpecialization = true; 5207 } 5208 5209 if (IsVariableTemplateSpecialization) { 5210 if (!PrevVarTemplate) { 5211 Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) 5212 << IsPartialSpecialization; 5213 return 0; 5214 } 5215 5216 SourceLocation TemplateKWLoc = 5217 TemplateParamLists.size() > 0 5218 ? TemplateParamLists[0]->getTemplateLoc() 5219 : SourceLocation(); 5220 DeclResult Res = ActOnVarTemplateSpecialization( 5221 S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5222 IsPartialSpecialization); 5223 if (Res.isInvalid()) 5224 return 0; 5225 NewVD = cast<VarDecl>(Res.get()); 5226 AddToScope = false; 5227 } else 5228 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5229 D.getIdentifierLoc(), II, R, TInfo, SC); 5230 5231 // If this is supposed to be a variable template, create it as such. 5232 if (IsVariableTemplate) { 5233 NewTemplate = 5234 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5235 TemplateParams, NewVD, PrevVarTemplate); 5236 NewVD->setDescribedVarTemplate(NewTemplate); 5237 } 5238 5239 // If this decl has an auto type in need of deduction, make a note of the 5240 // Decl so we can diagnose uses of it in its own initializer. 5241 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5242 ParsingInitForAutoVars.insert(NewVD); 5243 5244 if (D.isInvalidType() || Invalid) { 5245 NewVD->setInvalidDecl(); 5246 if (NewTemplate) 5247 NewTemplate->setInvalidDecl(); 5248 } 5249 5250 SetNestedNameSpecifier(NewVD, D); 5251 5252 // FIXME: Do we need D.getCXXScopeSpec().isSet()? 5253 if (TemplateParams && TemplateParamLists.size() > 1 && 5254 (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) { 5255 NewVD->setTemplateParameterListsInfo( 5256 Context, TemplateParamLists.size() - 1, TemplateParamLists.data()); 5257 } else if (IsVariableTemplateSpecialization || 5258 (!TemplateParams && TemplateParamLists.size() > 0 && 5259 (D.getCXXScopeSpec().isSet()))) { 5260 NewVD->setTemplateParameterListsInfo(Context, 5261 TemplateParamLists.size(), 5262 TemplateParamLists.data()); 5263 } 5264 5265 if (D.getDeclSpec().isConstexprSpecified()) 5266 NewVD->setConstexpr(true); 5267 } 5268 5269 // Set the lexical context. If the declarator has a C++ scope specifier, the 5270 // lexical context will be different from the semantic context. 5271 NewVD->setLexicalDeclContext(CurContext); 5272 if (NewTemplate) 5273 NewTemplate->setLexicalDeclContext(CurContext); 5274 5275 if (IsLocalExternDecl) 5276 NewVD->setLocalExternDecl(); 5277 5278 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5279 if (NewVD->hasLocalStorage()) { 5280 // C++11 [dcl.stc]p4: 5281 // When thread_local is applied to a variable of block scope the 5282 // storage-class-specifier static is implied if it does not appear 5283 // explicitly. 5284 // Core issue: 'static' is not implied if the variable is declared 5285 // 'extern'. 5286 if (SCSpec == DeclSpec::SCS_unspecified && 5287 TSCS == DeclSpec::TSCS_thread_local && 5288 DC->isFunctionOrMethod()) 5289 NewVD->setTSCSpec(TSCS); 5290 else 5291 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5292 diag::err_thread_non_global) 5293 << DeclSpec::getSpecifierName(TSCS); 5294 } else if (!Context.getTargetInfo().isTLSSupported()) 5295 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5296 diag::err_thread_unsupported); 5297 else 5298 NewVD->setTSCSpec(TSCS); 5299 } 5300 5301 // C99 6.7.4p3 5302 // An inline definition of a function with external linkage shall 5303 // not contain a definition of a modifiable object with static or 5304 // thread storage duration... 5305 // We only apply this when the function is required to be defined 5306 // elsewhere, i.e. when the function is not 'extern inline'. Note 5307 // that a local variable with thread storage duration still has to 5308 // be marked 'static'. Also note that it's possible to get these 5309 // semantics in C++ using __attribute__((gnu_inline)). 5310 if (SC == SC_Static && S->getFnParent() != 0 && 5311 !NewVD->getType().isConstQualified()) { 5312 FunctionDecl *CurFD = getCurFunctionDecl(); 5313 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5314 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5315 diag::warn_static_local_in_extern_inline); 5316 MaybeSuggestAddingStaticToDecl(CurFD); 5317 } 5318 } 5319 5320 if (D.getDeclSpec().isModulePrivateSpecified()) { 5321 if (IsVariableTemplateSpecialization) 5322 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5323 << (IsPartialSpecialization ? 1 : 0) 5324 << FixItHint::CreateRemoval( 5325 D.getDeclSpec().getModulePrivateSpecLoc()); 5326 else if (IsExplicitSpecialization) 5327 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5328 << 2 5329 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5330 else if (NewVD->hasLocalStorage()) 5331 Diag(NewVD->getLocation(), diag::err_module_private_local) 5332 << 0 << NewVD->getDeclName() 5333 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5334 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5335 else { 5336 NewVD->setModulePrivate(); 5337 if (NewTemplate) 5338 NewTemplate->setModulePrivate(); 5339 } 5340 } 5341 5342 // Handle attributes prior to checking for duplicates in MergeVarDecl 5343 ProcessDeclAttributes(S, NewVD, D); 5344 5345 if (NewVD->hasAttrs()) 5346 CheckAlignasUnderalignment(NewVD); 5347 5348 if (getLangOpts().CUDA) { 5349 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5350 // storage [duration]." 5351 if (SC == SC_None && S->getFnParent() != 0 && 5352 (NewVD->hasAttr<CUDASharedAttr>() || 5353 NewVD->hasAttr<CUDAConstantAttr>())) { 5354 NewVD->setStorageClass(SC_Static); 5355 } 5356 } 5357 5358 // In auto-retain/release, infer strong retension for variables of 5359 // retainable type. 5360 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5361 NewVD->setInvalidDecl(); 5362 5363 // Handle GNU asm-label extension (encoded as an attribute). 5364 if (Expr *E = (Expr*)D.getAsmLabel()) { 5365 // The parser guarantees this is a string. 5366 StringLiteral *SE = cast<StringLiteral>(E); 5367 StringRef Label = SE->getString(); 5368 if (S->getFnParent() != 0) { 5369 switch (SC) { 5370 case SC_None: 5371 case SC_Auto: 5372 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5373 break; 5374 case SC_Register: 5375 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5376 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5377 break; 5378 case SC_Static: 5379 case SC_Extern: 5380 case SC_PrivateExtern: 5381 case SC_OpenCLWorkGroupLocal: 5382 break; 5383 } 5384 } 5385 5386 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5387 Context, Label)); 5388 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5389 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5390 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5391 if (I != ExtnameUndeclaredIdentifiers.end()) { 5392 NewVD->addAttr(I->second); 5393 ExtnameUndeclaredIdentifiers.erase(I); 5394 } 5395 } 5396 5397 // Diagnose shadowed variables before filtering for scope. 5398 if (D.getCXXScopeSpec().isEmpty()) 5399 CheckShadow(S, NewVD, Previous); 5400 5401 // Don't consider existing declarations that are in a different 5402 // scope and are out-of-semantic-context declarations (if the new 5403 // declaration has linkage). 5404 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5405 D.getCXXScopeSpec().isNotEmpty() || 5406 IsExplicitSpecialization || 5407 IsVariableTemplateSpecialization); 5408 5409 // Check whether the previous declaration is in the same block scope. This 5410 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5411 if (getLangOpts().CPlusPlus && 5412 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5413 NewVD->setPreviousDeclInSameBlockScope( 5414 Previous.isSingleResult() && !Previous.isShadowed() && 5415 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5416 5417 if (!getLangOpts().CPlusPlus) { 5418 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5419 } else { 5420 // Merge the decl with the existing one if appropriate. 5421 if (!Previous.empty()) { 5422 if (Previous.isSingleResult() && 5423 isa<FieldDecl>(Previous.getFoundDecl()) && 5424 D.getCXXScopeSpec().isSet()) { 5425 // The user tried to define a non-static data member 5426 // out-of-line (C++ [dcl.meaning]p1). 5427 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5428 << D.getCXXScopeSpec().getRange(); 5429 Previous.clear(); 5430 NewVD->setInvalidDecl(); 5431 } 5432 } else if (D.getCXXScopeSpec().isSet()) { 5433 // No previous declaration in the qualifying scope. 5434 Diag(D.getIdentifierLoc(), diag::err_no_member) 5435 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5436 << D.getCXXScopeSpec().getRange(); 5437 NewVD->setInvalidDecl(); 5438 } 5439 5440 if (!IsVariableTemplateSpecialization) { 5441 if (PrevVarTemplate) { 5442 LookupResult PrevDecl(*this, GetNameForDeclarator(D), 5443 LookupOrdinaryName, ForRedeclaration); 5444 PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl()); 5445 D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl)); 5446 } else 5447 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5448 } 5449 5450 // This is an explicit specialization of a static data member. Check it. 5451 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5452 CheckMemberSpecialization(NewVD, Previous)) 5453 NewVD->setInvalidDecl(); 5454 } 5455 5456 ProcessPragmaWeak(S, NewVD); 5457 checkAttributesAfterMerging(*this, *NewVD); 5458 5459 // If this is the first declaration of an extern C variable, update 5460 // the map of such variables. 5461 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5462 isIncompleteDeclExternC(*this, NewVD)) 5463 RegisterLocallyScopedExternCDecl(NewVD, S); 5464 5465 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5466 Decl *ManglingContextDecl; 5467 if (MangleNumberingContext *MCtx = 5468 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5469 ManglingContextDecl)) { 5470 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD)); 5471 } 5472 } 5473 5474 // If we are providing an explicit specialization of a static variable 5475 // template, make a note of that. 5476 if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5477 PrevVarTemplate->setMemberSpecialization(); 5478 5479 if (NewTemplate) { 5480 ActOnDocumentableDecl(NewTemplate); 5481 return NewTemplate; 5482 } 5483 5484 return NewVD; 5485 } 5486 5487 /// \brief Diagnose variable or built-in function shadowing. Implements 5488 /// -Wshadow. 5489 /// 5490 /// This method is called whenever a VarDecl is added to a "useful" 5491 /// scope. 5492 /// 5493 /// \param S the scope in which the shadowing name is being declared 5494 /// \param R the lookup of the name 5495 /// 5496 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5497 // Return if warning is ignored. 5498 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5499 DiagnosticsEngine::Ignored) 5500 return; 5501 5502 // Don't diagnose declarations at file scope. 5503 if (D->hasGlobalStorage()) 5504 return; 5505 5506 DeclContext *NewDC = D->getDeclContext(); 5507 5508 // Only diagnose if we're shadowing an unambiguous field or variable. 5509 if (R.getResultKind() != LookupResult::Found) 5510 return; 5511 5512 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5513 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5514 return; 5515 5516 // Fields are not shadowed by variables in C++ static methods. 5517 if (isa<FieldDecl>(ShadowedDecl)) 5518 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5519 if (MD->isStatic()) 5520 return; 5521 5522 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5523 if (shadowedVar->isExternC()) { 5524 // For shadowing external vars, make sure that we point to the global 5525 // declaration, not a locally scoped extern declaration. 5526 for (VarDecl::redecl_iterator 5527 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 5528 I != E; ++I) 5529 if (I->isFileVarDecl()) { 5530 ShadowedDecl = *I; 5531 break; 5532 } 5533 } 5534 5535 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5536 5537 // Only warn about certain kinds of shadowing for class members. 5538 if (NewDC && NewDC->isRecord()) { 5539 // In particular, don't warn about shadowing non-class members. 5540 if (!OldDC->isRecord()) 5541 return; 5542 5543 // TODO: should we warn about static data members shadowing 5544 // static data members from base classes? 5545 5546 // TODO: don't diagnose for inaccessible shadowed members. 5547 // This is hard to do perfectly because we might friend the 5548 // shadowing context, but that's just a false negative. 5549 } 5550 5551 // Determine what kind of declaration we're shadowing. 5552 unsigned Kind; 5553 if (isa<RecordDecl>(OldDC)) { 5554 if (isa<FieldDecl>(ShadowedDecl)) 5555 Kind = 3; // field 5556 else 5557 Kind = 2; // static data member 5558 } else if (OldDC->isFileContext()) 5559 Kind = 1; // global 5560 else 5561 Kind = 0; // local 5562 5563 DeclarationName Name = R.getLookupName(); 5564 5565 // Emit warning and note. 5566 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5567 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5568 } 5569 5570 /// \brief Check -Wshadow without the advantage of a previous lookup. 5571 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5572 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5573 DiagnosticsEngine::Ignored) 5574 return; 5575 5576 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5577 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5578 LookupName(R, S); 5579 CheckShadow(S, D, R); 5580 } 5581 5582 /// Check for conflict between this global or extern "C" declaration and 5583 /// previous global or extern "C" declarations. This is only used in C++. 5584 template<typename T> 5585 static bool checkGlobalOrExternCConflict( 5586 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5587 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5588 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5589 5590 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5591 // The common case: this global doesn't conflict with any extern "C" 5592 // declaration. 5593 return false; 5594 } 5595 5596 if (Prev) { 5597 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5598 // Both the old and new declarations have C language linkage. This is a 5599 // redeclaration. 5600 Previous.clear(); 5601 Previous.addDecl(Prev); 5602 return true; 5603 } 5604 5605 // This is a global, non-extern "C" declaration, and there is a previous 5606 // non-global extern "C" declaration. Diagnose if this is a variable 5607 // declaration. 5608 if (!isa<VarDecl>(ND)) 5609 return false; 5610 } else { 5611 // The declaration is extern "C". Check for any declaration in the 5612 // translation unit which might conflict. 5613 if (IsGlobal) { 5614 // We have already performed the lookup into the translation unit. 5615 IsGlobal = false; 5616 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5617 I != E; ++I) { 5618 if (isa<VarDecl>(*I)) { 5619 Prev = *I; 5620 break; 5621 } 5622 } 5623 } else { 5624 DeclContext::lookup_result R = 5625 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5626 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5627 I != E; ++I) { 5628 if (isa<VarDecl>(*I)) { 5629 Prev = *I; 5630 break; 5631 } 5632 // FIXME: If we have any other entity with this name in global scope, 5633 // the declaration is ill-formed, but that is a defect: it breaks the 5634 // 'stat' hack, for instance. Only variables can have mangled name 5635 // clashes with extern "C" declarations, so only they deserve a 5636 // diagnostic. 5637 } 5638 } 5639 5640 if (!Prev) 5641 return false; 5642 } 5643 5644 // Use the first declaration's location to ensure we point at something which 5645 // is lexically inside an extern "C" linkage-spec. 5646 assert(Prev && "should have found a previous declaration to diagnose"); 5647 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5648 Prev = FD->getFirstDecl(); 5649 else 5650 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5651 5652 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5653 << IsGlobal << ND; 5654 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5655 << IsGlobal; 5656 return false; 5657 } 5658 5659 /// Apply special rules for handling extern "C" declarations. Returns \c true 5660 /// if we have found that this is a redeclaration of some prior entity. 5661 /// 5662 /// Per C++ [dcl.link]p6: 5663 /// Two declarations [for a function or variable] with C language linkage 5664 /// with the same name that appear in different scopes refer to the same 5665 /// [entity]. An entity with C language linkage shall not be declared with 5666 /// the same name as an entity in global scope. 5667 template<typename T> 5668 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5669 LookupResult &Previous) { 5670 if (!S.getLangOpts().CPlusPlus) { 5671 // In C, when declaring a global variable, look for a corresponding 'extern' 5672 // variable declared in function scope. We don't need this in C++, because 5673 // we find local extern decls in the surrounding file-scope DeclContext. 5674 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5675 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5676 Previous.clear(); 5677 Previous.addDecl(Prev); 5678 return true; 5679 } 5680 } 5681 return false; 5682 } 5683 5684 // A declaration in the translation unit can conflict with an extern "C" 5685 // declaration. 5686 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5687 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5688 5689 // An extern "C" declaration can conflict with a declaration in the 5690 // translation unit or can be a redeclaration of an extern "C" declaration 5691 // in another scope. 5692 if (isIncompleteDeclExternC(S,ND)) 5693 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5694 5695 // Neither global nor extern "C": nothing to do. 5696 return false; 5697 } 5698 5699 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5700 // If the decl is already known invalid, don't check it. 5701 if (NewVD->isInvalidDecl()) 5702 return; 5703 5704 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5705 QualType T = TInfo->getType(); 5706 5707 // Defer checking an 'auto' type until its initializer is attached. 5708 if (T->isUndeducedType()) 5709 return; 5710 5711 if (T->isObjCObjectType()) { 5712 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5713 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5714 T = Context.getObjCObjectPointerType(T); 5715 NewVD->setType(T); 5716 } 5717 5718 // Emit an error if an address space was applied to decl with local storage. 5719 // This includes arrays of objects with address space qualifiers, but not 5720 // automatic variables that point to other address spaces. 5721 // ISO/IEC TR 18037 S5.1.2 5722 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5723 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5724 NewVD->setInvalidDecl(); 5725 return; 5726 } 5727 5728 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5729 // __constant address space. 5730 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5731 && T.getAddressSpace() != LangAS::opencl_constant 5732 && !T->isSamplerT()){ 5733 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5734 NewVD->setInvalidDecl(); 5735 return; 5736 } 5737 5738 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5739 // scope. 5740 if ((getLangOpts().OpenCLVersion >= 120) 5741 && NewVD->isStaticLocal()) { 5742 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5743 NewVD->setInvalidDecl(); 5744 return; 5745 } 5746 5747 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5748 && !NewVD->hasAttr<BlocksAttr>()) { 5749 if (getLangOpts().getGC() != LangOptions::NonGC) 5750 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5751 else { 5752 assert(!getLangOpts().ObjCAutoRefCount); 5753 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5754 } 5755 } 5756 5757 bool isVM = T->isVariablyModifiedType(); 5758 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5759 NewVD->hasAttr<BlocksAttr>()) 5760 getCurFunction()->setHasBranchProtectedScope(); 5761 5762 if ((isVM && NewVD->hasLinkage()) || 5763 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5764 bool SizeIsNegative; 5765 llvm::APSInt Oversized; 5766 TypeSourceInfo *FixedTInfo = 5767 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5768 SizeIsNegative, Oversized); 5769 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5770 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5771 // FIXME: This won't give the correct result for 5772 // int a[10][n]; 5773 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5774 5775 if (NewVD->isFileVarDecl()) 5776 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5777 << SizeRange; 5778 else if (NewVD->isStaticLocal()) 5779 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5780 << SizeRange; 5781 else 5782 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5783 << SizeRange; 5784 NewVD->setInvalidDecl(); 5785 return; 5786 } 5787 5788 if (FixedTInfo == 0) { 5789 if (NewVD->isFileVarDecl()) 5790 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5791 else 5792 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5793 NewVD->setInvalidDecl(); 5794 return; 5795 } 5796 5797 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5798 NewVD->setType(FixedTInfo->getType()); 5799 NewVD->setTypeSourceInfo(FixedTInfo); 5800 } 5801 5802 if (T->isVoidType()) { 5803 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5804 // of objects and functions. 5805 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5806 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5807 << T; 5808 NewVD->setInvalidDecl(); 5809 return; 5810 } 5811 } 5812 5813 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5814 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5815 NewVD->setInvalidDecl(); 5816 return; 5817 } 5818 5819 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5820 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5821 NewVD->setInvalidDecl(); 5822 return; 5823 } 5824 5825 if (NewVD->isConstexpr() && !T->isDependentType() && 5826 RequireLiteralType(NewVD->getLocation(), T, 5827 diag::err_constexpr_var_non_literal)) { 5828 // Can't perform this check until the type is deduced. 5829 NewVD->setInvalidDecl(); 5830 return; 5831 } 5832 } 5833 5834 /// \brief Perform semantic checking on a newly-created variable 5835 /// declaration. 5836 /// 5837 /// This routine performs all of the type-checking required for a 5838 /// variable declaration once it has been built. It is used both to 5839 /// check variables after they have been parsed and their declarators 5840 /// have been translated into a declaration, and to check variables 5841 /// that have been instantiated from a template. 5842 /// 5843 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5844 /// 5845 /// Returns true if the variable declaration is a redeclaration. 5846 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5847 CheckVariableDeclarationType(NewVD); 5848 5849 // If the decl is already known invalid, don't check it. 5850 if (NewVD->isInvalidDecl()) 5851 return false; 5852 5853 // If we did not find anything by this name, look for a non-visible 5854 // extern "C" declaration with the same name. 5855 if (Previous.empty() && 5856 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5857 Previous.setShadowed(); 5858 5859 // Filter out any non-conflicting previous declarations. 5860 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5861 5862 if (!Previous.empty()) { 5863 MergeVarDecl(NewVD, Previous); 5864 return true; 5865 } 5866 return false; 5867 } 5868 5869 /// \brief Data used with FindOverriddenMethod 5870 struct FindOverriddenMethodData { 5871 Sema *S; 5872 CXXMethodDecl *Method; 5873 }; 5874 5875 /// \brief Member lookup function that determines whether a given C++ 5876 /// method overrides a method in a base class, to be used with 5877 /// CXXRecordDecl::lookupInBases(). 5878 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5879 CXXBasePath &Path, 5880 void *UserData) { 5881 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5882 5883 FindOverriddenMethodData *Data 5884 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5885 5886 DeclarationName Name = Data->Method->getDeclName(); 5887 5888 // FIXME: Do we care about other names here too? 5889 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5890 // We really want to find the base class destructor here. 5891 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5892 CanQualType CT = Data->S->Context.getCanonicalType(T); 5893 5894 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5895 } 5896 5897 for (Path.Decls = BaseRecord->lookup(Name); 5898 !Path.Decls.empty(); 5899 Path.Decls = Path.Decls.slice(1)) { 5900 NamedDecl *D = Path.Decls.front(); 5901 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5902 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5903 return true; 5904 } 5905 } 5906 5907 return false; 5908 } 5909 5910 namespace { 5911 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5912 } 5913 /// \brief Report an error regarding overriding, along with any relevant 5914 /// overriden methods. 5915 /// 5916 /// \param DiagID the primary error to report. 5917 /// \param MD the overriding method. 5918 /// \param OEK which overrides to include as notes. 5919 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5920 OverrideErrorKind OEK = OEK_All) { 5921 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5922 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5923 E = MD->end_overridden_methods(); 5924 I != E; ++I) { 5925 // This check (& the OEK parameter) could be replaced by a predicate, but 5926 // without lambdas that would be overkill. This is still nicer than writing 5927 // out the diag loop 3 times. 5928 if ((OEK == OEK_All) || 5929 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5930 (OEK == OEK_Deleted && (*I)->isDeleted())) 5931 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5932 } 5933 } 5934 5935 /// AddOverriddenMethods - See if a method overrides any in the base classes, 5936 /// and if so, check that it's a valid override and remember it. 5937 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5938 // Look for virtual methods in base classes that this method might override. 5939 CXXBasePaths Paths; 5940 FindOverriddenMethodData Data; 5941 Data.Method = MD; 5942 Data.S = this; 5943 bool hasDeletedOverridenMethods = false; 5944 bool hasNonDeletedOverridenMethods = false; 5945 bool AddedAny = false; 5946 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5947 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5948 E = Paths.found_decls_end(); I != E; ++I) { 5949 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5950 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5951 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5952 !CheckOverridingFunctionAttributes(MD, OldMD) && 5953 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5954 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5955 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5956 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5957 AddedAny = true; 5958 } 5959 } 5960 } 5961 } 5962 5963 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5964 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5965 } 5966 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5967 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5968 } 5969 5970 return AddedAny; 5971 } 5972 5973 namespace { 5974 // Struct for holding all of the extra arguments needed by 5975 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5976 struct ActOnFDArgs { 5977 Scope *S; 5978 Declarator &D; 5979 MultiTemplateParamsArg TemplateParamLists; 5980 bool AddToScope; 5981 }; 5982 } 5983 5984 namespace { 5985 5986 // Callback to only accept typo corrections that have a non-zero edit distance. 5987 // Also only accept corrections that have the same parent decl. 5988 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5989 public: 5990 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5991 CXXRecordDecl *Parent) 5992 : Context(Context), OriginalFD(TypoFD), 5993 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5994 5995 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5996 if (candidate.getEditDistance() == 0) 5997 return false; 5998 5999 SmallVector<unsigned, 1> MismatchedParams; 6000 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6001 CDeclEnd = candidate.end(); 6002 CDecl != CDeclEnd; ++CDecl) { 6003 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6004 6005 if (FD && !FD->hasBody() && 6006 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6007 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6008 CXXRecordDecl *Parent = MD->getParent(); 6009 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6010 return true; 6011 } else if (!ExpectedParent) { 6012 return true; 6013 } 6014 } 6015 } 6016 6017 return false; 6018 } 6019 6020 private: 6021 ASTContext &Context; 6022 FunctionDecl *OriginalFD; 6023 CXXRecordDecl *ExpectedParent; 6024 }; 6025 6026 } 6027 6028 /// \brief Generate diagnostics for an invalid function redeclaration. 6029 /// 6030 /// This routine handles generating the diagnostic messages for an invalid 6031 /// function redeclaration, including finding possible similar declarations 6032 /// or performing typo correction if there are no previous declarations with 6033 /// the same name. 6034 /// 6035 /// Returns a NamedDecl iff typo correction was performed and substituting in 6036 /// the new declaration name does not cause new errors. 6037 static NamedDecl *DiagnoseInvalidRedeclaration( 6038 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6039 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6040 DeclarationName Name = NewFD->getDeclName(); 6041 DeclContext *NewDC = NewFD->getDeclContext(); 6042 SmallVector<unsigned, 1> MismatchedParams; 6043 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6044 TypoCorrection Correction; 6045 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6046 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6047 : diag::err_member_decl_does_not_match; 6048 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6049 IsLocalFriend ? Sema::LookupLocalFriendName 6050 : Sema::LookupOrdinaryName, 6051 Sema::ForRedeclaration); 6052 6053 NewFD->setInvalidDecl(); 6054 if (IsLocalFriend) 6055 SemaRef.LookupName(Prev, S); 6056 else 6057 SemaRef.LookupQualifiedName(Prev, NewDC); 6058 assert(!Prev.isAmbiguous() && 6059 "Cannot have an ambiguity in previous-declaration lookup"); 6060 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6061 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6062 MD ? MD->getParent() : 0); 6063 if (!Prev.empty()) { 6064 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6065 Func != FuncEnd; ++Func) { 6066 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6067 if (FD && 6068 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6069 // Add 1 to the index so that 0 can mean the mismatch didn't 6070 // involve a parameter 6071 unsigned ParamNum = 6072 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6073 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6074 } 6075 } 6076 // If the qualified name lookup yielded nothing, try typo correction 6077 } else if ((Correction = SemaRef.CorrectTypo( 6078 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6079 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6080 IsLocalFriend ? 0 : NewDC))) { 6081 // Set up everything for the call to ActOnFunctionDeclarator 6082 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6083 ExtraArgs.D.getIdentifierLoc()); 6084 Previous.clear(); 6085 Previous.setLookupName(Correction.getCorrection()); 6086 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6087 CDeclEnd = Correction.end(); 6088 CDecl != CDeclEnd; ++CDecl) { 6089 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6090 if (FD && !FD->hasBody() && 6091 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6092 Previous.addDecl(FD); 6093 } 6094 } 6095 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6096 6097 NamedDecl *Result; 6098 // Retry building the function declaration with the new previous 6099 // declarations, and with errors suppressed. 6100 { 6101 // Trap errors. 6102 Sema::SFINAETrap Trap(SemaRef); 6103 6104 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6105 // pieces need to verify the typo-corrected C++ declaration and hopefully 6106 // eliminate the need for the parameter pack ExtraArgs. 6107 Result = SemaRef.ActOnFunctionDeclarator( 6108 ExtraArgs.S, ExtraArgs.D, 6109 Correction.getCorrectionDecl()->getDeclContext(), 6110 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6111 ExtraArgs.AddToScope); 6112 6113 if (Trap.hasErrorOccurred()) 6114 Result = 0; 6115 } 6116 6117 if (Result) { 6118 // Determine which correction we picked. 6119 Decl *Canonical = Result->getCanonicalDecl(); 6120 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6121 I != E; ++I) 6122 if ((*I)->getCanonicalDecl() == Canonical) 6123 Correction.setCorrectionDecl(*I); 6124 6125 SemaRef.diagnoseTypo( 6126 Correction, 6127 SemaRef.PDiag(IsLocalFriend 6128 ? diag::err_no_matching_local_friend_suggest 6129 : diag::err_member_decl_does_not_match_suggest) 6130 << Name << NewDC << IsDefinition); 6131 return Result; 6132 } 6133 6134 // Pretend the typo correction never occurred 6135 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6136 ExtraArgs.D.getIdentifierLoc()); 6137 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6138 Previous.clear(); 6139 Previous.setLookupName(Name); 6140 } 6141 6142 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6143 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6144 6145 bool NewFDisConst = false; 6146 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6147 NewFDisConst = NewMD->isConst(); 6148 6149 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6150 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6151 NearMatch != NearMatchEnd; ++NearMatch) { 6152 FunctionDecl *FD = NearMatch->first; 6153 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6154 bool FDisConst = MD && MD->isConst(); 6155 bool IsMember = MD || !IsLocalFriend; 6156 6157 // FIXME: These notes are poorly worded for the local friend case. 6158 if (unsigned Idx = NearMatch->second) { 6159 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6160 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6161 if (Loc.isInvalid()) Loc = FD->getLocation(); 6162 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6163 : diag::note_local_decl_close_param_match) 6164 << Idx << FDParam->getType() 6165 << NewFD->getParamDecl(Idx - 1)->getType(); 6166 } else if (FDisConst != NewFDisConst) { 6167 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6168 << NewFDisConst << FD->getSourceRange().getEnd(); 6169 } else 6170 SemaRef.Diag(FD->getLocation(), 6171 IsMember ? diag::note_member_def_close_match 6172 : diag::note_local_decl_close_match); 6173 } 6174 return 0; 6175 } 6176 6177 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6178 Declarator &D) { 6179 switch (D.getDeclSpec().getStorageClassSpec()) { 6180 default: llvm_unreachable("Unknown storage class!"); 6181 case DeclSpec::SCS_auto: 6182 case DeclSpec::SCS_register: 6183 case DeclSpec::SCS_mutable: 6184 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6185 diag::err_typecheck_sclass_func); 6186 D.setInvalidType(); 6187 break; 6188 case DeclSpec::SCS_unspecified: break; 6189 case DeclSpec::SCS_extern: 6190 if (D.getDeclSpec().isExternInLinkageSpec()) 6191 return SC_None; 6192 return SC_Extern; 6193 case DeclSpec::SCS_static: { 6194 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6195 // C99 6.7.1p5: 6196 // The declaration of an identifier for a function that has 6197 // block scope shall have no explicit storage-class specifier 6198 // other than extern 6199 // See also (C++ [dcl.stc]p4). 6200 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6201 diag::err_static_block_func); 6202 break; 6203 } else 6204 return SC_Static; 6205 } 6206 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6207 } 6208 6209 // No explicit storage class has already been returned 6210 return SC_None; 6211 } 6212 6213 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6214 DeclContext *DC, QualType &R, 6215 TypeSourceInfo *TInfo, 6216 FunctionDecl::StorageClass SC, 6217 bool &IsVirtualOkay) { 6218 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6219 DeclarationName Name = NameInfo.getName(); 6220 6221 FunctionDecl *NewFD = 0; 6222 bool isInline = D.getDeclSpec().isInlineSpecified(); 6223 6224 if (!SemaRef.getLangOpts().CPlusPlus) { 6225 // Determine whether the function was written with a 6226 // prototype. This true when: 6227 // - there is a prototype in the declarator, or 6228 // - the type R of the function is some kind of typedef or other reference 6229 // to a type name (which eventually refers to a function type). 6230 bool HasPrototype = 6231 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6232 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6233 6234 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6235 D.getLocStart(), NameInfo, R, 6236 TInfo, SC, isInline, 6237 HasPrototype, false); 6238 if (D.isInvalidType()) 6239 NewFD->setInvalidDecl(); 6240 6241 // Set the lexical context. 6242 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6243 6244 return NewFD; 6245 } 6246 6247 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6248 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6249 6250 // Check that the return type is not an abstract class type. 6251 // For record types, this is done by the AbstractClassUsageDiagnoser once 6252 // the class has been completely parsed. 6253 if (!DC->isRecord() && 6254 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 6255 R->getAs<FunctionType>()->getResultType(), 6256 diag::err_abstract_type_in_decl, 6257 SemaRef.AbstractReturnType)) 6258 D.setInvalidType(); 6259 6260 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6261 // This is a C++ constructor declaration. 6262 assert(DC->isRecord() && 6263 "Constructors can only be declared in a member context"); 6264 6265 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6266 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6267 D.getLocStart(), NameInfo, 6268 R, TInfo, isExplicit, isInline, 6269 /*isImplicitlyDeclared=*/false, 6270 isConstexpr); 6271 6272 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6273 // This is a C++ destructor declaration. 6274 if (DC->isRecord()) { 6275 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6276 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6277 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6278 SemaRef.Context, Record, 6279 D.getLocStart(), 6280 NameInfo, R, TInfo, isInline, 6281 /*isImplicitlyDeclared=*/false); 6282 6283 // If the class is complete, then we now create the implicit exception 6284 // specification. If the class is incomplete or dependent, we can't do 6285 // it yet. 6286 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6287 Record->getDefinition() && !Record->isBeingDefined() && 6288 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6289 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6290 } 6291 6292 // The Microsoft ABI requires that we perform the destructor body 6293 // checks (i.e. operator delete() lookup) at every declaration, as 6294 // any translation unit may need to emit a deleting destructor. 6295 if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() && 6296 !Record->isDependentType() && Record->getDefinition() && 6297 !Record->isBeingDefined()) { 6298 SemaRef.CheckDestructor(NewDD); 6299 } 6300 6301 IsVirtualOkay = true; 6302 return NewDD; 6303 6304 } else { 6305 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6306 D.setInvalidType(); 6307 6308 // Create a FunctionDecl to satisfy the function definition parsing 6309 // code path. 6310 return FunctionDecl::Create(SemaRef.Context, DC, 6311 D.getLocStart(), 6312 D.getIdentifierLoc(), Name, R, TInfo, 6313 SC, isInline, 6314 /*hasPrototype=*/true, isConstexpr); 6315 } 6316 6317 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6318 if (!DC->isRecord()) { 6319 SemaRef.Diag(D.getIdentifierLoc(), 6320 diag::err_conv_function_not_member); 6321 return 0; 6322 } 6323 6324 SemaRef.CheckConversionDeclarator(D, R, SC); 6325 IsVirtualOkay = true; 6326 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6327 D.getLocStart(), NameInfo, 6328 R, TInfo, isInline, isExplicit, 6329 isConstexpr, SourceLocation()); 6330 6331 } else if (DC->isRecord()) { 6332 // If the name of the function is the same as the name of the record, 6333 // then this must be an invalid constructor that has a return type. 6334 // (The parser checks for a return type and makes the declarator a 6335 // constructor if it has no return type). 6336 if (Name.getAsIdentifierInfo() && 6337 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6338 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6339 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6340 << SourceRange(D.getIdentifierLoc()); 6341 return 0; 6342 } 6343 6344 // This is a C++ method declaration. 6345 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6346 cast<CXXRecordDecl>(DC), 6347 D.getLocStart(), NameInfo, R, 6348 TInfo, SC, isInline, 6349 isConstexpr, SourceLocation()); 6350 IsVirtualOkay = !Ret->isStatic(); 6351 return Ret; 6352 } else { 6353 // Determine whether the function was written with a 6354 // prototype. This true when: 6355 // - we're in C++ (where every function has a prototype), 6356 return FunctionDecl::Create(SemaRef.Context, DC, 6357 D.getLocStart(), 6358 NameInfo, R, TInfo, SC, isInline, 6359 true/*HasPrototype*/, isConstexpr); 6360 } 6361 } 6362 6363 void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 6364 // In C++, the empty parameter-type-list must be spelled "void"; a 6365 // typedef of void is not permitted. 6366 if (getLangOpts().CPlusPlus && 6367 Param->getType().getUnqualifiedType() != Context.VoidTy) { 6368 bool IsTypeAlias = false; 6369 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 6370 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 6371 else if (const TemplateSpecializationType *TST = 6372 Param->getType()->getAs<TemplateSpecializationType>()) 6373 IsTypeAlias = TST->isTypeAlias(); 6374 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 6375 << IsTypeAlias; 6376 } 6377 } 6378 6379 enum OpenCLParamType { 6380 ValidKernelParam, 6381 PtrPtrKernelParam, 6382 PtrKernelParam, 6383 InvalidKernelParam, 6384 RecordKernelParam 6385 }; 6386 6387 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6388 if (PT->isPointerType()) { 6389 QualType PointeeType = PT->getPointeeType(); 6390 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam; 6391 } 6392 6393 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6394 // be used as builtin types. 6395 6396 if (PT->isImageType()) 6397 return PtrKernelParam; 6398 6399 if (PT->isBooleanType()) 6400 return InvalidKernelParam; 6401 6402 if (PT->isEventT()) 6403 return InvalidKernelParam; 6404 6405 if (PT->isHalfType()) 6406 return InvalidKernelParam; 6407 6408 if (PT->isRecordType()) 6409 return RecordKernelParam; 6410 6411 return ValidKernelParam; 6412 } 6413 6414 static void checkIsValidOpenCLKernelParameter( 6415 Sema &S, 6416 Declarator &D, 6417 ParmVarDecl *Param, 6418 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6419 QualType PT = Param->getType(); 6420 6421 // Cache the valid types we encounter to avoid rechecking structs that are 6422 // used again 6423 if (ValidTypes.count(PT.getTypePtr())) 6424 return; 6425 6426 switch (getOpenCLKernelParameterType(PT)) { 6427 case PtrPtrKernelParam: 6428 // OpenCL v1.2 s6.9.a: 6429 // A kernel function argument cannot be declared as a 6430 // pointer to a pointer type. 6431 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6432 D.setInvalidType(); 6433 return; 6434 6435 // OpenCL v1.2 s6.9.k: 6436 // Arguments to kernel functions in a program cannot be declared with the 6437 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6438 // uintptr_t or a struct and/or union that contain fields declared to be 6439 // one of these built-in scalar types. 6440 6441 case InvalidKernelParam: 6442 // OpenCL v1.2 s6.8 n: 6443 // A kernel function argument cannot be declared 6444 // of event_t type. 6445 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6446 D.setInvalidType(); 6447 return; 6448 6449 case PtrKernelParam: 6450 case ValidKernelParam: 6451 ValidTypes.insert(PT.getTypePtr()); 6452 return; 6453 6454 case RecordKernelParam: 6455 break; 6456 } 6457 6458 // Track nested structs we will inspect 6459 SmallVector<const Decl *, 4> VisitStack; 6460 6461 // Track where we are in the nested structs. Items will migrate from 6462 // VisitStack to HistoryStack as we do the DFS for bad field. 6463 SmallVector<const FieldDecl *, 4> HistoryStack; 6464 HistoryStack.push_back((const FieldDecl *) 0); 6465 6466 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6467 VisitStack.push_back(PD); 6468 6469 assert(VisitStack.back() && "First decl null?"); 6470 6471 do { 6472 const Decl *Next = VisitStack.pop_back_val(); 6473 if (!Next) { 6474 assert(!HistoryStack.empty()); 6475 // Found a marker, we have gone up a level 6476 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6477 ValidTypes.insert(Hist->getType().getTypePtr()); 6478 6479 continue; 6480 } 6481 6482 // Adds everything except the original parameter declaration (which is not a 6483 // field itself) to the history stack. 6484 const RecordDecl *RD; 6485 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6486 HistoryStack.push_back(Field); 6487 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6488 } else { 6489 RD = cast<RecordDecl>(Next); 6490 } 6491 6492 // Add a null marker so we know when we've gone back up a level 6493 VisitStack.push_back((const Decl *) 0); 6494 6495 for (RecordDecl::field_iterator I = RD->field_begin(), 6496 E = RD->field_end(); I != E; ++I) { 6497 const FieldDecl *FD = *I; 6498 QualType QT = FD->getType(); 6499 6500 if (ValidTypes.count(QT.getTypePtr())) 6501 continue; 6502 6503 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6504 if (ParamType == ValidKernelParam) 6505 continue; 6506 6507 if (ParamType == RecordKernelParam) { 6508 VisitStack.push_back(FD); 6509 continue; 6510 } 6511 6512 // OpenCL v1.2 s6.9.p: 6513 // Arguments to kernel functions that are declared to be a struct or union 6514 // do not allow OpenCL objects to be passed as elements of the struct or 6515 // union. 6516 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) { 6517 S.Diag(Param->getLocation(), 6518 diag::err_record_with_pointers_kernel_param) 6519 << PT->isUnionType() 6520 << PT; 6521 } else { 6522 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6523 } 6524 6525 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6526 << PD->getDeclName(); 6527 6528 // We have an error, now let's go back up through history and show where 6529 // the offending field came from 6530 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6531 E = HistoryStack.end(); I != E; ++I) { 6532 const FieldDecl *OuterField = *I; 6533 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6534 << OuterField->getType(); 6535 } 6536 6537 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6538 << QT->isPointerType() 6539 << QT; 6540 D.setInvalidType(); 6541 return; 6542 } 6543 } while (!VisitStack.empty()); 6544 } 6545 6546 NamedDecl* 6547 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6548 TypeSourceInfo *TInfo, LookupResult &Previous, 6549 MultiTemplateParamsArg TemplateParamLists, 6550 bool &AddToScope) { 6551 QualType R = TInfo->getType(); 6552 6553 assert(R.getTypePtr()->isFunctionType()); 6554 6555 // TODO: consider using NameInfo for diagnostic. 6556 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6557 DeclarationName Name = NameInfo.getName(); 6558 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6559 6560 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6561 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6562 diag::err_invalid_thread) 6563 << DeclSpec::getSpecifierName(TSCS); 6564 6565 if (D.isFirstDeclarationOfMember()) 6566 adjustMemberFunctionCC(R, D.isStaticMember()); 6567 6568 bool isFriend = false; 6569 FunctionTemplateDecl *FunctionTemplate = 0; 6570 bool isExplicitSpecialization = false; 6571 bool isFunctionTemplateSpecialization = false; 6572 6573 bool isDependentClassScopeExplicitSpecialization = false; 6574 bool HasExplicitTemplateArgs = false; 6575 TemplateArgumentListInfo TemplateArgs; 6576 6577 bool isVirtualOkay = false; 6578 6579 DeclContext *OriginalDC = DC; 6580 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6581 6582 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6583 isVirtualOkay); 6584 if (!NewFD) return 0; 6585 6586 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6587 NewFD->setTopLevelDeclInObjCContainer(); 6588 6589 // Set the lexical context. If this is a function-scope declaration, or has a 6590 // C++ scope specifier, or is the object of a friend declaration, the lexical 6591 // context will be different from the semantic context. 6592 NewFD->setLexicalDeclContext(CurContext); 6593 6594 if (IsLocalExternDecl) 6595 NewFD->setLocalExternDecl(); 6596 6597 if (getLangOpts().CPlusPlus) { 6598 bool isInline = D.getDeclSpec().isInlineSpecified(); 6599 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6600 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6601 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6602 isFriend = D.getDeclSpec().isFriendSpecified(); 6603 if (isFriend && !isInline && D.isFunctionDefinition()) { 6604 // C++ [class.friend]p5 6605 // A function can be defined in a friend declaration of a 6606 // class . . . . Such a function is implicitly inline. 6607 NewFD->setImplicitlyInline(); 6608 } 6609 6610 // If this is a method defined in an __interface, and is not a constructor 6611 // or an overloaded operator, then set the pure flag (isVirtual will already 6612 // return true). 6613 if (const CXXRecordDecl *Parent = 6614 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6615 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6616 NewFD->setPure(true); 6617 } 6618 6619 SetNestedNameSpecifier(NewFD, D); 6620 isExplicitSpecialization = false; 6621 isFunctionTemplateSpecialization = false; 6622 if (D.isInvalidType()) 6623 NewFD->setInvalidDecl(); 6624 6625 // Match up the template parameter lists with the scope specifier, then 6626 // determine whether we have a template or a template specialization. 6627 bool Invalid = false; 6628 if (TemplateParameterList *TemplateParams = 6629 MatchTemplateParametersToScopeSpecifier( 6630 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6631 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6632 isExplicitSpecialization, Invalid)) { 6633 if (TemplateParams->size() > 0) { 6634 // This is a function template 6635 6636 // Check that we can declare a template here. 6637 if (CheckTemplateDeclScope(S, TemplateParams)) 6638 return 0; 6639 6640 // A destructor cannot be a template. 6641 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6642 Diag(NewFD->getLocation(), diag::err_destructor_template); 6643 return 0; 6644 } 6645 6646 // If we're adding a template to a dependent context, we may need to 6647 // rebuilding some of the types used within the template parameter list, 6648 // now that we know what the current instantiation is. 6649 if (DC->isDependentContext()) { 6650 ContextRAII SavedContext(*this, DC); 6651 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6652 Invalid = true; 6653 } 6654 6655 6656 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6657 NewFD->getLocation(), 6658 Name, TemplateParams, 6659 NewFD); 6660 FunctionTemplate->setLexicalDeclContext(CurContext); 6661 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6662 6663 // For source fidelity, store the other template param lists. 6664 if (TemplateParamLists.size() > 1) { 6665 NewFD->setTemplateParameterListsInfo(Context, 6666 TemplateParamLists.size() - 1, 6667 TemplateParamLists.data()); 6668 } 6669 } else { 6670 // This is a function template specialization. 6671 isFunctionTemplateSpecialization = true; 6672 // For source fidelity, store all the template param lists. 6673 NewFD->setTemplateParameterListsInfo(Context, 6674 TemplateParamLists.size(), 6675 TemplateParamLists.data()); 6676 6677 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6678 if (isFriend) { 6679 // We want to remove the "template<>", found here. 6680 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6681 6682 // If we remove the template<> and the name is not a 6683 // template-id, we're actually silently creating a problem: 6684 // the friend declaration will refer to an untemplated decl, 6685 // and clearly the user wants a template specialization. So 6686 // we need to insert '<>' after the name. 6687 SourceLocation InsertLoc; 6688 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6689 InsertLoc = D.getName().getSourceRange().getEnd(); 6690 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6691 } 6692 6693 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6694 << Name << RemoveRange 6695 << FixItHint::CreateRemoval(RemoveRange) 6696 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6697 } 6698 } 6699 } 6700 else { 6701 // All template param lists were matched against the scope specifier: 6702 // this is NOT (an explicit specialization of) a template. 6703 if (TemplateParamLists.size() > 0) 6704 // For source fidelity, store all the template param lists. 6705 NewFD->setTemplateParameterListsInfo(Context, 6706 TemplateParamLists.size(), 6707 TemplateParamLists.data()); 6708 } 6709 6710 if (Invalid) { 6711 NewFD->setInvalidDecl(); 6712 if (FunctionTemplate) 6713 FunctionTemplate->setInvalidDecl(); 6714 } 6715 6716 // C++ [dcl.fct.spec]p5: 6717 // The virtual specifier shall only be used in declarations of 6718 // nonstatic class member functions that appear within a 6719 // member-specification of a class declaration; see 10.3. 6720 // 6721 if (isVirtual && !NewFD->isInvalidDecl()) { 6722 if (!isVirtualOkay) { 6723 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6724 diag::err_virtual_non_function); 6725 } else if (!CurContext->isRecord()) { 6726 // 'virtual' was specified outside of the class. 6727 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6728 diag::err_virtual_out_of_class) 6729 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6730 } else if (NewFD->getDescribedFunctionTemplate()) { 6731 // C++ [temp.mem]p3: 6732 // A member function template shall not be virtual. 6733 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6734 diag::err_virtual_member_function_template) 6735 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6736 } else { 6737 // Okay: Add virtual to the method. 6738 NewFD->setVirtualAsWritten(true); 6739 } 6740 6741 if (getLangOpts().CPlusPlus1y && 6742 NewFD->getResultType()->isUndeducedType()) 6743 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6744 } 6745 6746 if (getLangOpts().CPlusPlus1y && 6747 (NewFD->isDependentContext() || 6748 (isFriend && CurContext->isDependentContext())) && 6749 NewFD->getResultType()->isUndeducedType()) { 6750 // If the function template is referenced directly (for instance, as a 6751 // member of the current instantiation), pretend it has a dependent type. 6752 // This is not really justified by the standard, but is the only sane 6753 // thing to do. 6754 // FIXME: For a friend function, we have not marked the function as being 6755 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6756 const FunctionProtoType *FPT = 6757 NewFD->getType()->castAs<FunctionProtoType>(); 6758 QualType Result = SubstAutoType(FPT->getResultType(), 6759 Context.DependentTy); 6760 NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(), 6761 FPT->getExtProtoInfo())); 6762 } 6763 6764 // C++ [dcl.fct.spec]p3: 6765 // The inline specifier shall not appear on a block scope function 6766 // declaration. 6767 if (isInline && !NewFD->isInvalidDecl()) { 6768 if (CurContext->isFunctionOrMethod()) { 6769 // 'inline' is not allowed on block scope function declaration. 6770 Diag(D.getDeclSpec().getInlineSpecLoc(), 6771 diag::err_inline_declaration_block_scope) << Name 6772 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6773 } 6774 } 6775 6776 // C++ [dcl.fct.spec]p6: 6777 // The explicit specifier shall be used only in the declaration of a 6778 // constructor or conversion function within its class definition; 6779 // see 12.3.1 and 12.3.2. 6780 if (isExplicit && !NewFD->isInvalidDecl()) { 6781 if (!CurContext->isRecord()) { 6782 // 'explicit' was specified outside of the class. 6783 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6784 diag::err_explicit_out_of_class) 6785 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6786 } else if (!isa<CXXConstructorDecl>(NewFD) && 6787 !isa<CXXConversionDecl>(NewFD)) { 6788 // 'explicit' was specified on a function that wasn't a constructor 6789 // or conversion function. 6790 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6791 diag::err_explicit_non_ctor_or_conv_function) 6792 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6793 } 6794 } 6795 6796 if (isConstexpr) { 6797 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6798 // are implicitly inline. 6799 NewFD->setImplicitlyInline(); 6800 6801 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6802 // be either constructors or to return a literal type. Therefore, 6803 // destructors cannot be declared constexpr. 6804 if (isa<CXXDestructorDecl>(NewFD)) 6805 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6806 } 6807 6808 // If __module_private__ was specified, mark the function accordingly. 6809 if (D.getDeclSpec().isModulePrivateSpecified()) { 6810 if (isFunctionTemplateSpecialization) { 6811 SourceLocation ModulePrivateLoc 6812 = D.getDeclSpec().getModulePrivateSpecLoc(); 6813 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6814 << 0 6815 << FixItHint::CreateRemoval(ModulePrivateLoc); 6816 } else { 6817 NewFD->setModulePrivate(); 6818 if (FunctionTemplate) 6819 FunctionTemplate->setModulePrivate(); 6820 } 6821 } 6822 6823 if (isFriend) { 6824 if (FunctionTemplate) { 6825 FunctionTemplate->setObjectOfFriendDecl(); 6826 FunctionTemplate->setAccess(AS_public); 6827 } 6828 NewFD->setObjectOfFriendDecl(); 6829 NewFD->setAccess(AS_public); 6830 } 6831 6832 // If a function is defined as defaulted or deleted, mark it as such now. 6833 switch (D.getFunctionDefinitionKind()) { 6834 case FDK_Declaration: 6835 case FDK_Definition: 6836 break; 6837 6838 case FDK_Defaulted: 6839 NewFD->setDefaulted(); 6840 break; 6841 6842 case FDK_Deleted: 6843 NewFD->setDeletedAsWritten(); 6844 break; 6845 } 6846 6847 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6848 D.isFunctionDefinition()) { 6849 // C++ [class.mfct]p2: 6850 // A member function may be defined (8.4) in its class definition, in 6851 // which case it is an inline member function (7.1.2) 6852 NewFD->setImplicitlyInline(); 6853 } 6854 6855 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6856 !CurContext->isRecord()) { 6857 // C++ [class.static]p1: 6858 // A data or function member of a class may be declared static 6859 // in a class definition, in which case it is a static member of 6860 // the class. 6861 6862 // Complain about the 'static' specifier if it's on an out-of-line 6863 // member function definition. 6864 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6865 diag::err_static_out_of_line) 6866 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6867 } 6868 6869 // C++11 [except.spec]p15: 6870 // A deallocation function with no exception-specification is treated 6871 // as if it were specified with noexcept(true). 6872 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6873 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6874 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6875 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6876 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6877 EPI.ExceptionSpecType = EST_BasicNoexcept; 6878 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 6879 FPT->getArgTypes(), EPI)); 6880 } 6881 } 6882 6883 // Filter out previous declarations that don't match the scope. 6884 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6885 D.getCXXScopeSpec().isNotEmpty() || 6886 isExplicitSpecialization || 6887 isFunctionTemplateSpecialization); 6888 6889 // Handle GNU asm-label extension (encoded as an attribute). 6890 if (Expr *E = (Expr*) D.getAsmLabel()) { 6891 // The parser guarantees this is a string. 6892 StringLiteral *SE = cast<StringLiteral>(E); 6893 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6894 SE->getString())); 6895 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6896 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6897 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6898 if (I != ExtnameUndeclaredIdentifiers.end()) { 6899 NewFD->addAttr(I->second); 6900 ExtnameUndeclaredIdentifiers.erase(I); 6901 } 6902 } 6903 6904 // Copy the parameter declarations from the declarator D to the function 6905 // declaration NewFD, if they are available. First scavenge them into Params. 6906 SmallVector<ParmVarDecl*, 16> Params; 6907 if (D.isFunctionDeclarator()) { 6908 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6909 6910 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6911 // function that takes no arguments, not a function that takes a 6912 // single void argument. 6913 // We let through "const void" here because Sema::GetTypeForDeclarator 6914 // already checks for that case. 6915 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6916 FTI.ArgInfo[0].Param && 6917 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6918 // Empty arg list, don't push any params. 6919 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6920 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6921 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6922 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6923 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6924 Param->setDeclContext(NewFD); 6925 Params.push_back(Param); 6926 6927 if (Param->isInvalidDecl()) 6928 NewFD->setInvalidDecl(); 6929 } 6930 } 6931 6932 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6933 // When we're declaring a function with a typedef, typeof, etc as in the 6934 // following example, we'll need to synthesize (unnamed) 6935 // parameters for use in the declaration. 6936 // 6937 // @code 6938 // typedef void fn(int); 6939 // fn f; 6940 // @endcode 6941 6942 // Synthesize a parameter for each argument type. 6943 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 6944 AE = FT->arg_type_end(); AI != AE; ++AI) { 6945 ParmVarDecl *Param = 6946 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6947 Param->setScopeInfo(0, Params.size()); 6948 Params.push_back(Param); 6949 } 6950 } else { 6951 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6952 "Should not need args for typedef of non-prototype fn"); 6953 } 6954 6955 // Finally, we know we have the right number of parameters, install them. 6956 NewFD->setParams(Params); 6957 6958 // Find all anonymous symbols defined during the declaration of this function 6959 // and add to NewFD. This lets us track decls such 'enum Y' in: 6960 // 6961 // void f(enum Y {AA} x) {} 6962 // 6963 // which would otherwise incorrectly end up in the translation unit scope. 6964 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6965 DeclsInPrototypeScope.clear(); 6966 6967 if (D.getDeclSpec().isNoreturnSpecified()) 6968 NewFD->addAttr( 6969 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6970 Context)); 6971 6972 // Functions returning a variably modified type violate C99 6.7.5.2p2 6973 // because all functions have linkage. 6974 if (!NewFD->isInvalidDecl() && 6975 NewFD->getResultType()->isVariablyModifiedType()) { 6976 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6977 NewFD->setInvalidDecl(); 6978 } 6979 6980 // Handle attributes. 6981 ProcessDeclAttributes(S, NewFD, D); 6982 6983 QualType RetType = NewFD->getResultType(); 6984 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6985 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6986 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6987 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6988 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6989 // Attach the attribute to the new decl. Don't apply the attribute if it 6990 // returns an instance of the class (e.g. assignment operators). 6991 if (!MD || MD->getParent() != Ret) { 6992 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 6993 Context)); 6994 } 6995 } 6996 6997 if (!getLangOpts().CPlusPlus) { 6998 // Perform semantic checking on the function declaration. 6999 bool isExplicitSpecialization=false; 7000 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7001 CheckMain(NewFD, D.getDeclSpec()); 7002 7003 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7004 CheckMSVCRTEntryPoint(NewFD); 7005 7006 if (!NewFD->isInvalidDecl()) 7007 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7008 isExplicitSpecialization)); 7009 else if (!Previous.empty()) 7010 // Make graceful recovery from an invalid redeclaration. 7011 D.setRedeclaration(true); 7012 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7013 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7014 "previous declaration set still overloaded"); 7015 } else { 7016 // C++11 [replacement.functions]p3: 7017 // The program's definitions shall not be specified as inline. 7018 // 7019 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7020 // 7021 // Suppress the diagnostic if the function is __attribute__((used)), since 7022 // that forces an external definition to be emitted. 7023 if (D.getDeclSpec().isInlineSpecified() && 7024 NewFD->isReplaceableGlobalAllocationFunction() && 7025 !NewFD->hasAttr<UsedAttr>()) 7026 Diag(D.getDeclSpec().getInlineSpecLoc(), 7027 diag::ext_operator_new_delete_declared_inline) 7028 << NewFD->getDeclName(); 7029 7030 // If the declarator is a template-id, translate the parser's template 7031 // argument list into our AST format. 7032 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7033 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7034 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7035 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7036 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7037 TemplateId->NumArgs); 7038 translateTemplateArguments(TemplateArgsPtr, 7039 TemplateArgs); 7040 7041 HasExplicitTemplateArgs = true; 7042 7043 if (NewFD->isInvalidDecl()) { 7044 HasExplicitTemplateArgs = false; 7045 } else if (FunctionTemplate) { 7046 // Function template with explicit template arguments. 7047 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7048 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7049 7050 HasExplicitTemplateArgs = false; 7051 } else if (!isFunctionTemplateSpecialization && 7052 !D.getDeclSpec().isFriendSpecified()) { 7053 // We have encountered something that the user meant to be a 7054 // specialization (because it has explicitly-specified template 7055 // arguments) but that was not introduced with a "template<>" (or had 7056 // too few of them). 7057 // FIXME: Differentiate between attempts for explicit instantiations 7058 // (starting with "template") and the rest. 7059 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7060 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7061 << FixItHint::CreateInsertion( 7062 D.getDeclSpec().getLocStart(), 7063 "template<> "); 7064 isFunctionTemplateSpecialization = true; 7065 } else { 7066 // "friend void foo<>(int);" is an implicit specialization decl. 7067 isFunctionTemplateSpecialization = true; 7068 } 7069 } else if (isFriend && isFunctionTemplateSpecialization) { 7070 // This combination is only possible in a recovery case; the user 7071 // wrote something like: 7072 // template <> friend void foo(int); 7073 // which we're recovering from as if the user had written: 7074 // friend void foo<>(int); 7075 // Go ahead and fake up a template id. 7076 HasExplicitTemplateArgs = true; 7077 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7078 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7079 } 7080 7081 // If it's a friend (and only if it's a friend), it's possible 7082 // that either the specialized function type or the specialized 7083 // template is dependent, and therefore matching will fail. In 7084 // this case, don't check the specialization yet. 7085 bool InstantiationDependent = false; 7086 if (isFunctionTemplateSpecialization && isFriend && 7087 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7088 TemplateSpecializationType::anyDependentTemplateArguments( 7089 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7090 InstantiationDependent))) { 7091 assert(HasExplicitTemplateArgs && 7092 "friend function specialization without template args"); 7093 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7094 Previous)) 7095 NewFD->setInvalidDecl(); 7096 } else if (isFunctionTemplateSpecialization) { 7097 if (CurContext->isDependentContext() && CurContext->isRecord() 7098 && !isFriend) { 7099 isDependentClassScopeExplicitSpecialization = true; 7100 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7101 diag::ext_function_specialization_in_class : 7102 diag::err_function_specialization_in_class) 7103 << NewFD->getDeclName(); 7104 } else if (CheckFunctionTemplateSpecialization(NewFD, 7105 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7106 Previous)) 7107 NewFD->setInvalidDecl(); 7108 7109 // C++ [dcl.stc]p1: 7110 // A storage-class-specifier shall not be specified in an explicit 7111 // specialization (14.7.3) 7112 FunctionTemplateSpecializationInfo *Info = 7113 NewFD->getTemplateSpecializationInfo(); 7114 if (Info && SC != SC_None) { 7115 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7116 Diag(NewFD->getLocation(), 7117 diag::err_explicit_specialization_inconsistent_storage_class) 7118 << SC 7119 << FixItHint::CreateRemoval( 7120 D.getDeclSpec().getStorageClassSpecLoc()); 7121 7122 else 7123 Diag(NewFD->getLocation(), 7124 diag::ext_explicit_specialization_storage_class) 7125 << FixItHint::CreateRemoval( 7126 D.getDeclSpec().getStorageClassSpecLoc()); 7127 } 7128 7129 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7130 if (CheckMemberSpecialization(NewFD, Previous)) 7131 NewFD->setInvalidDecl(); 7132 } 7133 7134 // Perform semantic checking on the function declaration. 7135 if (!isDependentClassScopeExplicitSpecialization) { 7136 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7137 CheckMain(NewFD, D.getDeclSpec()); 7138 7139 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7140 CheckMSVCRTEntryPoint(NewFD); 7141 7142 if (NewFD->isInvalidDecl()) { 7143 // If this is a class member, mark the class invalid immediately. 7144 // This avoids some consistency errors later. 7145 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 7146 methodDecl->getParent()->setInvalidDecl(); 7147 } else 7148 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7149 isExplicitSpecialization)); 7150 } 7151 7152 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7153 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7154 "previous declaration set still overloaded"); 7155 7156 NamedDecl *PrincipalDecl = (FunctionTemplate 7157 ? cast<NamedDecl>(FunctionTemplate) 7158 : NewFD); 7159 7160 if (isFriend && D.isRedeclaration()) { 7161 AccessSpecifier Access = AS_public; 7162 if (!NewFD->isInvalidDecl()) 7163 Access = NewFD->getPreviousDecl()->getAccess(); 7164 7165 NewFD->setAccess(Access); 7166 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7167 } 7168 7169 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7170 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7171 PrincipalDecl->setNonMemberOperator(); 7172 7173 // If we have a function template, check the template parameter 7174 // list. This will check and merge default template arguments. 7175 if (FunctionTemplate) { 7176 FunctionTemplateDecl *PrevTemplate = 7177 FunctionTemplate->getPreviousDecl(); 7178 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7179 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7180 D.getDeclSpec().isFriendSpecified() 7181 ? (D.isFunctionDefinition() 7182 ? TPC_FriendFunctionTemplateDefinition 7183 : TPC_FriendFunctionTemplate) 7184 : (D.getCXXScopeSpec().isSet() && 7185 DC && DC->isRecord() && 7186 DC->isDependentContext()) 7187 ? TPC_ClassTemplateMember 7188 : TPC_FunctionTemplate); 7189 } 7190 7191 if (NewFD->isInvalidDecl()) { 7192 // Ignore all the rest of this. 7193 } else if (!D.isRedeclaration()) { 7194 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7195 AddToScope }; 7196 // Fake up an access specifier if it's supposed to be a class member. 7197 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7198 NewFD->setAccess(AS_public); 7199 7200 // Qualified decls generally require a previous declaration. 7201 if (D.getCXXScopeSpec().isSet()) { 7202 // ...with the major exception of templated-scope or 7203 // dependent-scope friend declarations. 7204 7205 // TODO: we currently also suppress this check in dependent 7206 // contexts because (1) the parameter depth will be off when 7207 // matching friend templates and (2) we might actually be 7208 // selecting a friend based on a dependent factor. But there 7209 // are situations where these conditions don't apply and we 7210 // can actually do this check immediately. 7211 if (isFriend && 7212 (TemplateParamLists.size() || 7213 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7214 CurContext->isDependentContext())) { 7215 // ignore these 7216 } else { 7217 // The user tried to provide an out-of-line definition for a 7218 // function that is a member of a class or namespace, but there 7219 // was no such member function declared (C++ [class.mfct]p2, 7220 // C++ [namespace.memdef]p2). For example: 7221 // 7222 // class X { 7223 // void f() const; 7224 // }; 7225 // 7226 // void X::f() { } // ill-formed 7227 // 7228 // Complain about this problem, and attempt to suggest close 7229 // matches (e.g., those that differ only in cv-qualifiers and 7230 // whether the parameter types are references). 7231 7232 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7233 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7234 AddToScope = ExtraArgs.AddToScope; 7235 return Result; 7236 } 7237 } 7238 7239 // Unqualified local friend declarations are required to resolve 7240 // to something. 7241 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7242 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7243 *this, Previous, NewFD, ExtraArgs, true, S)) { 7244 AddToScope = ExtraArgs.AddToScope; 7245 return Result; 7246 } 7247 } 7248 7249 } else if (!D.isFunctionDefinition() && 7250 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7251 !isFriend && !isFunctionTemplateSpecialization && 7252 !isExplicitSpecialization) { 7253 // An out-of-line member function declaration must also be a 7254 // definition (C++ [class.mfct]p2). 7255 // Note that this is not the case for explicit specializations of 7256 // function templates or member functions of class templates, per 7257 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7258 // extension for compatibility with old SWIG code which likes to 7259 // generate them. 7260 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7261 << D.getCXXScopeSpec().getRange(); 7262 } 7263 } 7264 7265 ProcessPragmaWeak(S, NewFD); 7266 checkAttributesAfterMerging(*this, *NewFD); 7267 7268 AddKnownFunctionAttributes(NewFD); 7269 7270 if (NewFD->hasAttr<OverloadableAttr>() && 7271 !NewFD->getType()->getAs<FunctionProtoType>()) { 7272 Diag(NewFD->getLocation(), 7273 diag::err_attribute_overloadable_no_prototype) 7274 << NewFD; 7275 7276 // Turn this into a variadic function with no parameters. 7277 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7278 FunctionProtoType::ExtProtoInfo EPI( 7279 Context.getDefaultCallingConvention(true, false)); 7280 EPI.Variadic = true; 7281 EPI.ExtInfo = FT->getExtInfo(); 7282 7283 QualType R = Context.getFunctionType(FT->getResultType(), None, EPI); 7284 NewFD->setType(R); 7285 } 7286 7287 // If there's a #pragma GCC visibility in scope, and this isn't a class 7288 // member, set the visibility of this function. 7289 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7290 AddPushedVisibilityAttribute(NewFD); 7291 7292 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7293 // marking the function. 7294 AddCFAuditedAttribute(NewFD); 7295 7296 // If this is the first declaration of an extern C variable, update 7297 // the map of such variables. 7298 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7299 isIncompleteDeclExternC(*this, NewFD)) 7300 RegisterLocallyScopedExternCDecl(NewFD, S); 7301 7302 // Set this FunctionDecl's range up to the right paren. 7303 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7304 7305 if (getLangOpts().CPlusPlus) { 7306 if (FunctionTemplate) { 7307 if (NewFD->isInvalidDecl()) 7308 FunctionTemplate->setInvalidDecl(); 7309 return FunctionTemplate; 7310 } 7311 } 7312 7313 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7314 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7315 if ((getLangOpts().OpenCLVersion >= 120) 7316 && (SC == SC_Static)) { 7317 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7318 D.setInvalidType(); 7319 } 7320 7321 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7322 if (!NewFD->getResultType()->isVoidType()) { 7323 Diag(D.getIdentifierLoc(), 7324 diag::err_expected_kernel_void_return_type); 7325 D.setInvalidType(); 7326 } 7327 7328 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7329 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 7330 PE = NewFD->param_end(); PI != PE; ++PI) { 7331 ParmVarDecl *Param = *PI; 7332 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7333 } 7334 } 7335 7336 MarkUnusedFileScopedDecl(NewFD); 7337 7338 if (getLangOpts().CUDA) 7339 if (IdentifierInfo *II = NewFD->getIdentifier()) 7340 if (!NewFD->isInvalidDecl() && 7341 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7342 if (II->isStr("cudaConfigureCall")) { 7343 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 7344 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7345 7346 Context.setcudaConfigureCallDecl(NewFD); 7347 } 7348 } 7349 7350 // Here we have an function template explicit specialization at class scope. 7351 // The actually specialization will be postponed to template instatiation 7352 // time via the ClassScopeFunctionSpecializationDecl node. 7353 if (isDependentClassScopeExplicitSpecialization) { 7354 ClassScopeFunctionSpecializationDecl *NewSpec = 7355 ClassScopeFunctionSpecializationDecl::Create( 7356 Context, CurContext, SourceLocation(), 7357 cast<CXXMethodDecl>(NewFD), 7358 HasExplicitTemplateArgs, TemplateArgs); 7359 CurContext->addDecl(NewSpec); 7360 AddToScope = false; 7361 } 7362 7363 return NewFD; 7364 } 7365 7366 /// \brief Perform semantic checking of a new function declaration. 7367 /// 7368 /// Performs semantic analysis of the new function declaration 7369 /// NewFD. This routine performs all semantic checking that does not 7370 /// require the actual declarator involved in the declaration, and is 7371 /// used both for the declaration of functions as they are parsed 7372 /// (called via ActOnDeclarator) and for the declaration of functions 7373 /// that have been instantiated via C++ template instantiation (called 7374 /// via InstantiateDecl). 7375 /// 7376 /// \param IsExplicitSpecialization whether this new function declaration is 7377 /// an explicit specialization of the previous declaration. 7378 /// 7379 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7380 /// 7381 /// \returns true if the function declaration is a redeclaration. 7382 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7383 LookupResult &Previous, 7384 bool IsExplicitSpecialization) { 7385 assert(!NewFD->getResultType()->isVariablyModifiedType() 7386 && "Variably modified return types are not handled here"); 7387 7388 // Determine whether the type of this function should be merged with 7389 // a previous visible declaration. This never happens for functions in C++, 7390 // and always happens in C if the previous declaration was visible. 7391 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7392 !Previous.isShadowed(); 7393 7394 // Filter out any non-conflicting previous declarations. 7395 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7396 7397 bool Redeclaration = false; 7398 NamedDecl *OldDecl = 0; 7399 7400 // Merge or overload the declaration with an existing declaration of 7401 // the same name, if appropriate. 7402 if (!Previous.empty()) { 7403 // Determine whether NewFD is an overload of PrevDecl or 7404 // a declaration that requires merging. If it's an overload, 7405 // there's no more work to do here; we'll just add the new 7406 // function to the scope. 7407 if (!AllowOverloadingOfFunction(Previous, Context)) { 7408 NamedDecl *Candidate = Previous.getFoundDecl(); 7409 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7410 Redeclaration = true; 7411 OldDecl = Candidate; 7412 } 7413 } else { 7414 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7415 /*NewIsUsingDecl*/ false)) { 7416 case Ovl_Match: 7417 Redeclaration = true; 7418 break; 7419 7420 case Ovl_NonFunction: 7421 Redeclaration = true; 7422 break; 7423 7424 case Ovl_Overload: 7425 Redeclaration = false; 7426 break; 7427 } 7428 7429 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7430 // If a function name is overloadable in C, then every function 7431 // with that name must be marked "overloadable". 7432 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7433 << Redeclaration << NewFD; 7434 NamedDecl *OverloadedDecl = 0; 7435 if (Redeclaration) 7436 OverloadedDecl = OldDecl; 7437 else if (!Previous.empty()) 7438 OverloadedDecl = Previous.getRepresentativeDecl(); 7439 if (OverloadedDecl) 7440 Diag(OverloadedDecl->getLocation(), 7441 diag::note_attribute_overloadable_prev_overload); 7442 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 7443 Context)); 7444 } 7445 } 7446 } 7447 7448 // Check for a previous extern "C" declaration with this name. 7449 if (!Redeclaration && 7450 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7451 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7452 if (!Previous.empty()) { 7453 // This is an extern "C" declaration with the same name as a previous 7454 // declaration, and thus redeclares that entity... 7455 Redeclaration = true; 7456 OldDecl = Previous.getFoundDecl(); 7457 MergeTypeWithPrevious = false; 7458 7459 // ... except in the presence of __attribute__((overloadable)). 7460 if (OldDecl->hasAttr<OverloadableAttr>()) { 7461 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7462 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7463 << Redeclaration << NewFD; 7464 Diag(Previous.getFoundDecl()->getLocation(), 7465 diag::note_attribute_overloadable_prev_overload); 7466 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 7467 Context)); 7468 } 7469 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7470 Redeclaration = false; 7471 OldDecl = 0; 7472 } 7473 } 7474 } 7475 } 7476 7477 // C++11 [dcl.constexpr]p8: 7478 // A constexpr specifier for a non-static member function that is not 7479 // a constructor declares that member function to be const. 7480 // 7481 // This needs to be delayed until we know whether this is an out-of-line 7482 // definition of a static member function. 7483 // 7484 // This rule is not present in C++1y, so we produce a backwards 7485 // compatibility warning whenever it happens in C++11. 7486 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7487 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7488 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7489 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7490 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl); 7491 if (FunctionTemplateDecl *OldTD = 7492 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl)) 7493 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl()); 7494 if (!OldMD || !OldMD->isStatic()) { 7495 const FunctionProtoType *FPT = 7496 MD->getType()->castAs<FunctionProtoType>(); 7497 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7498 EPI.TypeQuals |= Qualifiers::Const; 7499 MD->setType(Context.getFunctionType(FPT->getResultType(), 7500 FPT->getArgTypes(), EPI)); 7501 7502 // Warn that we did this, if we're not performing template instantiation. 7503 // In that case, we'll have warned already when the template was defined. 7504 if (ActiveTemplateInstantiations.empty()) { 7505 SourceLocation AddConstLoc; 7506 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7507 .IgnoreParens().getAs<FunctionTypeLoc>()) 7508 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7509 7510 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7511 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7512 } 7513 } 7514 } 7515 7516 if (Redeclaration) { 7517 // NewFD and OldDecl represent declarations that need to be 7518 // merged. 7519 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7520 NewFD->setInvalidDecl(); 7521 return Redeclaration; 7522 } 7523 7524 Previous.clear(); 7525 Previous.addDecl(OldDecl); 7526 7527 if (FunctionTemplateDecl *OldTemplateDecl 7528 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7529 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7530 FunctionTemplateDecl *NewTemplateDecl 7531 = NewFD->getDescribedFunctionTemplate(); 7532 assert(NewTemplateDecl && "Template/non-template mismatch"); 7533 if (CXXMethodDecl *Method 7534 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7535 Method->setAccess(OldTemplateDecl->getAccess()); 7536 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7537 } 7538 7539 // If this is an explicit specialization of a member that is a function 7540 // template, mark it as a member specialization. 7541 if (IsExplicitSpecialization && 7542 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7543 NewTemplateDecl->setMemberSpecialization(); 7544 assert(OldTemplateDecl->isMemberSpecialization()); 7545 } 7546 7547 } else { 7548 // This needs to happen first so that 'inline' propagates. 7549 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7550 7551 if (isa<CXXMethodDecl>(NewFD)) { 7552 // A valid redeclaration of a C++ method must be out-of-line, 7553 // but (unfortunately) it's not necessarily a definition 7554 // because of templates, which means that the previous 7555 // declaration is not necessarily from the class definition. 7556 7557 // For just setting the access, that doesn't matter. 7558 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7559 NewFD->setAccess(oldMethod->getAccess()); 7560 7561 // Update the key-function state if necessary for this ABI. 7562 if (NewFD->isInlined() && 7563 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7564 // setNonKeyFunction needs to work with the original 7565 // declaration from the class definition, and isVirtual() is 7566 // just faster in that case, so map back to that now. 7567 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7568 if (oldMethod->isVirtual()) { 7569 Context.setNonKeyFunction(oldMethod); 7570 } 7571 } 7572 } 7573 } 7574 } 7575 7576 // Semantic checking for this function declaration (in isolation). 7577 if (getLangOpts().CPlusPlus) { 7578 // C++-specific checks. 7579 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7580 CheckConstructor(Constructor); 7581 } else if (CXXDestructorDecl *Destructor = 7582 dyn_cast<CXXDestructorDecl>(NewFD)) { 7583 CXXRecordDecl *Record = Destructor->getParent(); 7584 QualType ClassType = Context.getTypeDeclType(Record); 7585 7586 // FIXME: Shouldn't we be able to perform this check even when the class 7587 // type is dependent? Both gcc and edg can handle that. 7588 if (!ClassType->isDependentType()) { 7589 DeclarationName Name 7590 = Context.DeclarationNames.getCXXDestructorName( 7591 Context.getCanonicalType(ClassType)); 7592 if (NewFD->getDeclName() != Name) { 7593 Diag(NewFD->getLocation(), diag::err_destructor_name); 7594 NewFD->setInvalidDecl(); 7595 return Redeclaration; 7596 } 7597 } 7598 } else if (CXXConversionDecl *Conversion 7599 = dyn_cast<CXXConversionDecl>(NewFD)) { 7600 ActOnConversionDeclarator(Conversion); 7601 } 7602 7603 // Find any virtual functions that this function overrides. 7604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7605 if (!Method->isFunctionTemplateSpecialization() && 7606 !Method->getDescribedFunctionTemplate() && 7607 Method->isCanonicalDecl()) { 7608 if (AddOverriddenMethods(Method->getParent(), Method)) { 7609 // If the function was marked as "static", we have a problem. 7610 if (NewFD->getStorageClass() == SC_Static) { 7611 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7612 } 7613 } 7614 } 7615 7616 if (Method->isStatic()) 7617 checkThisInStaticMemberFunctionType(Method); 7618 } 7619 7620 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7621 if (NewFD->isOverloadedOperator() && 7622 CheckOverloadedOperatorDeclaration(NewFD)) { 7623 NewFD->setInvalidDecl(); 7624 return Redeclaration; 7625 } 7626 7627 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7628 if (NewFD->getLiteralIdentifier() && 7629 CheckLiteralOperatorDeclaration(NewFD)) { 7630 NewFD->setInvalidDecl(); 7631 return Redeclaration; 7632 } 7633 7634 // In C++, check default arguments now that we have merged decls. Unless 7635 // the lexical context is the class, because in this case this is done 7636 // during delayed parsing anyway. 7637 if (!CurContext->isRecord()) 7638 CheckCXXDefaultArguments(NewFD); 7639 7640 // If this function declares a builtin function, check the type of this 7641 // declaration against the expected type for the builtin. 7642 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7643 ASTContext::GetBuiltinTypeError Error; 7644 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7645 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7646 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7647 // The type of this function differs from the type of the builtin, 7648 // so forget about the builtin entirely. 7649 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7650 } 7651 } 7652 7653 // If this function is declared as being extern "C", then check to see if 7654 // the function returns a UDT (class, struct, or union type) that is not C 7655 // compatible, and if it does, warn the user. 7656 // But, issue any diagnostic on the first declaration only. 7657 if (NewFD->isExternC() && Previous.empty()) { 7658 QualType R = NewFD->getResultType(); 7659 if (R->isIncompleteType() && !R->isVoidType()) 7660 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7661 << NewFD << R; 7662 else if (!R.isPODType(Context) && !R->isVoidType() && 7663 !R->isObjCObjectPointerType()) 7664 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7665 } 7666 } 7667 return Redeclaration; 7668 } 7669 7670 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7671 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7672 if (!TSI) 7673 return SourceRange(); 7674 7675 TypeLoc TL = TSI->getTypeLoc(); 7676 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7677 if (!FunctionTL) 7678 return SourceRange(); 7679 7680 TypeLoc ResultTL = FunctionTL.getResultLoc(); 7681 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7682 return ResultTL.getSourceRange(); 7683 7684 return SourceRange(); 7685 } 7686 7687 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7688 // C++11 [basic.start.main]p3: A program that declares main to be inline, 7689 // static or constexpr is ill-formed. 7690 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7691 // appear in a declaration of main. 7692 // static main is not an error under C99, but we should warn about it. 7693 // We accept _Noreturn main as an extension. 7694 if (FD->getStorageClass() == SC_Static) 7695 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7696 ? diag::err_static_main : diag::warn_static_main) 7697 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7698 if (FD->isInlineSpecified()) 7699 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7700 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7701 if (DS.isNoreturnSpecified()) { 7702 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7703 SourceRange NoreturnRange(NoreturnLoc, 7704 PP.getLocForEndOfToken(NoreturnLoc)); 7705 Diag(NoreturnLoc, diag::ext_noreturn_main); 7706 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7707 << FixItHint::CreateRemoval(NoreturnRange); 7708 } 7709 if (FD->isConstexpr()) { 7710 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7711 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7712 FD->setConstexpr(false); 7713 } 7714 7715 if (getLangOpts().OpenCL) { 7716 Diag(FD->getLocation(), diag::err_opencl_no_main) 7717 << FD->hasAttr<OpenCLKernelAttr>(); 7718 FD->setInvalidDecl(); 7719 return; 7720 } 7721 7722 QualType T = FD->getType(); 7723 assert(T->isFunctionType() && "function decl is not of function type"); 7724 const FunctionType* FT = T->castAs<FunctionType>(); 7725 7726 // All the standards say that main() should should return 'int'. 7727 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 7728 // In C and C++, main magically returns 0 if you fall off the end; 7729 // set the flag which tells us that. 7730 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7731 FD->setHasImplicitReturnZero(true); 7732 7733 // In C with GNU extensions we allow main() to have non-integer return 7734 // type, but we should warn about the extension, and we disable the 7735 // implicit-return-zero rule. 7736 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7737 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7738 7739 SourceRange ResultRange = getResultSourceRange(FD); 7740 if (ResultRange.isValid()) 7741 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7742 << FixItHint::CreateReplacement(ResultRange, "int"); 7743 7744 // Otherwise, this is just a flat-out error. 7745 } else { 7746 SourceRange ResultRange = getResultSourceRange(FD); 7747 if (ResultRange.isValid()) 7748 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7749 << FixItHint::CreateReplacement(ResultRange, "int"); 7750 else 7751 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7752 7753 FD->setInvalidDecl(true); 7754 } 7755 7756 // Treat protoless main() as nullary. 7757 if (isa<FunctionNoProtoType>(FT)) return; 7758 7759 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7760 unsigned nparams = FTP->getNumArgs(); 7761 assert(FD->getNumParams() == nparams); 7762 7763 bool HasExtraParameters = (nparams > 3); 7764 7765 // Darwin passes an undocumented fourth argument of type char**. If 7766 // other platforms start sprouting these, the logic below will start 7767 // getting shifty. 7768 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7769 HasExtraParameters = false; 7770 7771 if (HasExtraParameters) { 7772 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7773 FD->setInvalidDecl(true); 7774 nparams = 3; 7775 } 7776 7777 // FIXME: a lot of the following diagnostics would be improved 7778 // if we had some location information about types. 7779 7780 QualType CharPP = 7781 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7782 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7783 7784 for (unsigned i = 0; i < nparams; ++i) { 7785 QualType AT = FTP->getArgType(i); 7786 7787 bool mismatch = true; 7788 7789 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7790 mismatch = false; 7791 else if (Expected[i] == CharPP) { 7792 // As an extension, the following forms are okay: 7793 // char const ** 7794 // char const * const * 7795 // char * const * 7796 7797 QualifierCollector qs; 7798 const PointerType* PT; 7799 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7800 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7801 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7802 Context.CharTy)) { 7803 qs.removeConst(); 7804 mismatch = !qs.empty(); 7805 } 7806 } 7807 7808 if (mismatch) { 7809 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7810 // TODO: suggest replacing given type with expected type 7811 FD->setInvalidDecl(true); 7812 } 7813 } 7814 7815 if (nparams == 1 && !FD->isInvalidDecl()) { 7816 Diag(FD->getLocation(), diag::warn_main_one_arg); 7817 } 7818 7819 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7820 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName(); 7821 FD->setInvalidDecl(); 7822 } 7823 } 7824 7825 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7826 QualType T = FD->getType(); 7827 assert(T->isFunctionType() && "function decl is not of function type"); 7828 const FunctionType *FT = T->castAs<FunctionType>(); 7829 7830 // Set an implicit return of 'zero' if the function can return some integral, 7831 // enumeration, pointer or nullptr type. 7832 if (FT->getResultType()->isIntegralOrEnumerationType() || 7833 FT->getResultType()->isAnyPointerType() || 7834 FT->getResultType()->isNullPtrType()) 7835 // DllMain is exempt because a return value of zero means it failed. 7836 if (FD->getName() != "DllMain") 7837 FD->setHasImplicitReturnZero(true); 7838 7839 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7840 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName(); 7841 FD->setInvalidDecl(); 7842 } 7843 } 7844 7845 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7846 // FIXME: Need strict checking. In C89, we need to check for 7847 // any assignment, increment, decrement, function-calls, or 7848 // commas outside of a sizeof. In C99, it's the same list, 7849 // except that the aforementioned are allowed in unevaluated 7850 // expressions. Everything else falls under the 7851 // "may accept other forms of constant expressions" exception. 7852 // (We never end up here for C++, so the constant expression 7853 // rules there don't matter.) 7854 if (Init->isConstantInitializer(Context, false)) 7855 return false; 7856 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7857 << Init->getSourceRange(); 7858 return true; 7859 } 7860 7861 namespace { 7862 // Visits an initialization expression to see if OrigDecl is evaluated in 7863 // its own initialization and throws a warning if it does. 7864 class SelfReferenceChecker 7865 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7866 Sema &S; 7867 Decl *OrigDecl; 7868 bool isRecordType; 7869 bool isPODType; 7870 bool isReferenceType; 7871 7872 public: 7873 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7874 7875 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7876 S(S), OrigDecl(OrigDecl) { 7877 isPODType = false; 7878 isRecordType = false; 7879 isReferenceType = false; 7880 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7881 isPODType = VD->getType().isPODType(S.Context); 7882 isRecordType = VD->getType()->isRecordType(); 7883 isReferenceType = VD->getType()->isReferenceType(); 7884 } 7885 } 7886 7887 // For most expressions, the cast is directly above the DeclRefExpr. 7888 // For conditional operators, the cast can be outside the conditional 7889 // operator if both expressions are DeclRefExpr's. 7890 void HandleValue(Expr *E) { 7891 if (isReferenceType) 7892 return; 7893 E = E->IgnoreParenImpCasts(); 7894 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7895 HandleDeclRefExpr(DRE); 7896 return; 7897 } 7898 7899 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7900 HandleValue(CO->getTrueExpr()); 7901 HandleValue(CO->getFalseExpr()); 7902 return; 7903 } 7904 7905 if (isa<MemberExpr>(E)) { 7906 Expr *Base = E->IgnoreParenImpCasts(); 7907 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7908 // Check for static member variables and don't warn on them. 7909 if (!isa<FieldDecl>(ME->getMemberDecl())) 7910 return; 7911 Base = ME->getBase()->IgnoreParenImpCasts(); 7912 } 7913 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7914 HandleDeclRefExpr(DRE); 7915 return; 7916 } 7917 } 7918 7919 // Reference types are handled here since all uses of references are 7920 // bad, not just r-value uses. 7921 void VisitDeclRefExpr(DeclRefExpr *E) { 7922 if (isReferenceType) 7923 HandleDeclRefExpr(E); 7924 } 7925 7926 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7927 if (E->getCastKind() == CK_LValueToRValue || 7928 (isRecordType && E->getCastKind() == CK_NoOp)) 7929 HandleValue(E->getSubExpr()); 7930 7931 Inherited::VisitImplicitCastExpr(E); 7932 } 7933 7934 void VisitMemberExpr(MemberExpr *E) { 7935 // Don't warn on arrays since they can be treated as pointers. 7936 if (E->getType()->canDecayToPointerType()) return; 7937 7938 // Warn when a non-static method call is followed by non-static member 7939 // field accesses, which is followed by a DeclRefExpr. 7940 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7941 bool Warn = (MD && !MD->isStatic()); 7942 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7943 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7944 if (!isa<FieldDecl>(ME->getMemberDecl())) 7945 Warn = false; 7946 Base = ME->getBase()->IgnoreParenImpCasts(); 7947 } 7948 7949 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7950 if (Warn) 7951 HandleDeclRefExpr(DRE); 7952 return; 7953 } 7954 7955 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7956 // Visit that expression. 7957 Visit(Base); 7958 } 7959 7960 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7961 if (E->getNumArgs() > 0) 7962 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7963 HandleDeclRefExpr(DRE); 7964 7965 Inherited::VisitCXXOperatorCallExpr(E); 7966 } 7967 7968 void VisitUnaryOperator(UnaryOperator *E) { 7969 // For POD record types, addresses of its own members are well-defined. 7970 if (E->getOpcode() == UO_AddrOf && isRecordType && 7971 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7972 if (!isPODType) 7973 HandleValue(E->getSubExpr()); 7974 return; 7975 } 7976 Inherited::VisitUnaryOperator(E); 7977 } 7978 7979 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7980 7981 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7982 Decl* ReferenceDecl = DRE->getDecl(); 7983 if (OrigDecl != ReferenceDecl) return; 7984 unsigned diag; 7985 if (isReferenceType) { 7986 diag = diag::warn_uninit_self_reference_in_reference_init; 7987 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7988 diag = diag::warn_static_self_reference_in_init; 7989 } else { 7990 diag = diag::warn_uninit_self_reference_in_init; 7991 } 7992 7993 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7994 S.PDiag(diag) 7995 << DRE->getNameInfo().getName() 7996 << OrigDecl->getLocation() 7997 << DRE->getSourceRange()); 7998 } 7999 }; 8000 8001 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8002 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8003 bool DirectInit) { 8004 // Parameters arguments are occassionially constructed with itself, 8005 // for instance, in recursive functions. Skip them. 8006 if (isa<ParmVarDecl>(OrigDecl)) 8007 return; 8008 8009 E = E->IgnoreParens(); 8010 8011 // Skip checking T a = a where T is not a record or reference type. 8012 // Doing so is a way to silence uninitialized warnings. 8013 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8014 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8015 if (ICE->getCastKind() == CK_LValueToRValue) 8016 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8017 if (DRE->getDecl() == OrigDecl) 8018 return; 8019 8020 SelfReferenceChecker(S, OrigDecl).Visit(E); 8021 } 8022 } 8023 8024 /// AddInitializerToDecl - Adds the initializer Init to the 8025 /// declaration dcl. If DirectInit is true, this is C++ direct 8026 /// initialization rather than copy initialization. 8027 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8028 bool DirectInit, bool TypeMayContainAuto) { 8029 // If there is no declaration, there was an error parsing it. Just ignore 8030 // the initializer. 8031 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8032 return; 8033 8034 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8035 // With declarators parsed the way they are, the parser cannot 8036 // distinguish between a normal initializer and a pure-specifier. 8037 // Thus this grotesque test. 8038 IntegerLiteral *IL; 8039 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8040 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8041 CheckPureMethod(Method, Init->getSourceRange()); 8042 else { 8043 Diag(Method->getLocation(), diag::err_member_function_initialization) 8044 << Method->getDeclName() << Init->getSourceRange(); 8045 Method->setInvalidDecl(); 8046 } 8047 return; 8048 } 8049 8050 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8051 if (!VDecl) { 8052 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8053 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8054 RealDecl->setInvalidDecl(); 8055 return; 8056 } 8057 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8058 8059 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8060 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8061 Expr *DeduceInit = Init; 8062 // Initializer could be a C++ direct-initializer. Deduction only works if it 8063 // contains exactly one expression. 8064 if (CXXDirectInit) { 8065 if (CXXDirectInit->getNumExprs() == 0) { 8066 // It isn't possible to write this directly, but it is possible to 8067 // end up in this situation with "auto x(some_pack...);" 8068 Diag(CXXDirectInit->getLocStart(), 8069 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8070 : diag::err_auto_var_init_no_expression) 8071 << VDecl->getDeclName() << VDecl->getType() 8072 << VDecl->getSourceRange(); 8073 RealDecl->setInvalidDecl(); 8074 return; 8075 } else if (CXXDirectInit->getNumExprs() > 1) { 8076 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8077 VDecl->isInitCapture() 8078 ? diag::err_init_capture_multiple_expressions 8079 : diag::err_auto_var_init_multiple_expressions) 8080 << VDecl->getDeclName() << VDecl->getType() 8081 << VDecl->getSourceRange(); 8082 RealDecl->setInvalidDecl(); 8083 return; 8084 } else { 8085 DeduceInit = CXXDirectInit->getExpr(0); 8086 } 8087 } 8088 8089 // Expressions default to 'id' when we're in a debugger. 8090 bool DefaultedToAuto = false; 8091 if (getLangOpts().DebuggerCastResultToId && 8092 Init->getType() == Context.UnknownAnyTy) { 8093 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8094 if (Result.isInvalid()) { 8095 VDecl->setInvalidDecl(); 8096 return; 8097 } 8098 Init = Result.take(); 8099 DefaultedToAuto = true; 8100 } 8101 8102 QualType DeducedType; 8103 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8104 DAR_Failed) 8105 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8106 if (DeducedType.isNull()) { 8107 RealDecl->setInvalidDecl(); 8108 return; 8109 } 8110 VDecl->setType(DeducedType); 8111 assert(VDecl->isLinkageValid()); 8112 8113 // In ARC, infer lifetime. 8114 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8115 VDecl->setInvalidDecl(); 8116 8117 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8118 // 'id' instead of a specific object type prevents most of our usual checks. 8119 // We only want to warn outside of template instantiations, though: 8120 // inside a template, the 'id' could have come from a parameter. 8121 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8122 DeducedType->isObjCIdType()) { 8123 SourceLocation Loc = 8124 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8125 Diag(Loc, diag::warn_auto_var_is_id) 8126 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8127 } 8128 8129 // If this is a redeclaration, check that the type we just deduced matches 8130 // the previously declared type. 8131 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8132 // We never need to merge the type, because we cannot form an incomplete 8133 // array of auto, nor deduce such a type. 8134 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8135 } 8136 8137 // Check the deduced type is valid for a variable declaration. 8138 CheckVariableDeclarationType(VDecl); 8139 if (VDecl->isInvalidDecl()) 8140 return; 8141 } 8142 8143 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8144 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8145 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8146 VDecl->setInvalidDecl(); 8147 return; 8148 } 8149 8150 if (!VDecl->getType()->isDependentType()) { 8151 // A definition must end up with a complete type, which means it must be 8152 // complete with the restriction that an array type might be completed by 8153 // the initializer; note that later code assumes this restriction. 8154 QualType BaseDeclType = VDecl->getType(); 8155 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8156 BaseDeclType = Array->getElementType(); 8157 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8158 diag::err_typecheck_decl_incomplete_type)) { 8159 RealDecl->setInvalidDecl(); 8160 return; 8161 } 8162 8163 // The variable can not have an abstract class type. 8164 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8165 diag::err_abstract_type_in_decl, 8166 AbstractVariableType)) 8167 VDecl->setInvalidDecl(); 8168 } 8169 8170 const VarDecl *Def; 8171 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8172 Diag(VDecl->getLocation(), diag::err_redefinition) 8173 << VDecl->getDeclName(); 8174 Diag(Def->getLocation(), diag::note_previous_definition); 8175 VDecl->setInvalidDecl(); 8176 return; 8177 } 8178 8179 const VarDecl* PrevInit = 0; 8180 if (getLangOpts().CPlusPlus) { 8181 // C++ [class.static.data]p4 8182 // If a static data member is of const integral or const 8183 // enumeration type, its declaration in the class definition can 8184 // specify a constant-initializer which shall be an integral 8185 // constant expression (5.19). In that case, the member can appear 8186 // in integral constant expressions. The member shall still be 8187 // defined in a namespace scope if it is used in the program and the 8188 // namespace scope definition shall not contain an initializer. 8189 // 8190 // We already performed a redefinition check above, but for static 8191 // data members we also need to check whether there was an in-class 8192 // declaration with an initializer. 8193 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8194 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8195 << VDecl->getDeclName(); 8196 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8197 return; 8198 } 8199 8200 if (VDecl->hasLocalStorage()) 8201 getCurFunction()->setHasBranchProtectedScope(); 8202 8203 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8204 VDecl->setInvalidDecl(); 8205 return; 8206 } 8207 } 8208 8209 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8210 // a kernel function cannot be initialized." 8211 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8212 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8213 VDecl->setInvalidDecl(); 8214 return; 8215 } 8216 8217 // Get the decls type and save a reference for later, since 8218 // CheckInitializerTypes may change it. 8219 QualType DclT = VDecl->getType(), SavT = DclT; 8220 8221 // Expressions default to 'id' when we're in a debugger 8222 // and we are assigning it to a variable of Objective-C pointer type. 8223 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8224 Init->getType() == Context.UnknownAnyTy) { 8225 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8226 if (Result.isInvalid()) { 8227 VDecl->setInvalidDecl(); 8228 return; 8229 } 8230 Init = Result.take(); 8231 } 8232 8233 // Perform the initialization. 8234 if (!VDecl->isInvalidDecl()) { 8235 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8236 InitializationKind Kind 8237 = DirectInit ? 8238 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8239 Init->getLocStart(), 8240 Init->getLocEnd()) 8241 : InitializationKind::CreateDirectList( 8242 VDecl->getLocation()) 8243 : InitializationKind::CreateCopy(VDecl->getLocation(), 8244 Init->getLocStart()); 8245 8246 MultiExprArg Args = Init; 8247 if (CXXDirectInit) 8248 Args = MultiExprArg(CXXDirectInit->getExprs(), 8249 CXXDirectInit->getNumExprs()); 8250 8251 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8252 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8253 if (Result.isInvalid()) { 8254 VDecl->setInvalidDecl(); 8255 return; 8256 } 8257 8258 Init = Result.takeAs<Expr>(); 8259 } 8260 8261 // Check for self-references within variable initializers. 8262 // Variables declared within a function/method body (except for references) 8263 // are handled by a dataflow analysis. 8264 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8265 VDecl->getType()->isReferenceType()) { 8266 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8267 } 8268 8269 // If the type changed, it means we had an incomplete type that was 8270 // completed by the initializer. For example: 8271 // int ary[] = { 1, 3, 5 }; 8272 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8273 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8274 VDecl->setType(DclT); 8275 8276 if (!VDecl->isInvalidDecl()) { 8277 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8278 8279 if (VDecl->hasAttr<BlocksAttr>()) 8280 checkRetainCycles(VDecl, Init); 8281 8282 // It is safe to assign a weak reference into a strong variable. 8283 // Although this code can still have problems: 8284 // id x = self.weakProp; 8285 // id y = self.weakProp; 8286 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8287 // paths through the function. This should be revisited if 8288 // -Wrepeated-use-of-weak is made flow-sensitive. 8289 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8290 DiagnosticsEngine::Level Level = 8291 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8292 Init->getLocStart()); 8293 if (Level != DiagnosticsEngine::Ignored) 8294 getCurFunction()->markSafeWeakUse(Init); 8295 } 8296 } 8297 8298 // The initialization is usually a full-expression. 8299 // 8300 // FIXME: If this is a braced initialization of an aggregate, it is not 8301 // an expression, and each individual field initializer is a separate 8302 // full-expression. For instance, in: 8303 // 8304 // struct Temp { ~Temp(); }; 8305 // struct S { S(Temp); }; 8306 // struct T { S a, b; } t = { Temp(), Temp() } 8307 // 8308 // we should destroy the first Temp before constructing the second. 8309 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8310 false, 8311 VDecl->isConstexpr()); 8312 if (Result.isInvalid()) { 8313 VDecl->setInvalidDecl(); 8314 return; 8315 } 8316 Init = Result.take(); 8317 8318 // Attach the initializer to the decl. 8319 VDecl->setInit(Init); 8320 8321 if (VDecl->isLocalVarDecl()) { 8322 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8323 // static storage duration shall be constant expressions or string literals. 8324 // C++ does not have this restriction. 8325 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8326 if (VDecl->getStorageClass() == SC_Static) 8327 CheckForConstantInitializer(Init, DclT); 8328 // C89 is stricter than C99 for non-static aggregate types. 8329 // C89 6.5.7p3: All the expressions [...] in an initializer list 8330 // for an object that has aggregate or union type shall be 8331 // constant expressions. 8332 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8333 isa<InitListExpr>(Init) && 8334 !Init->isConstantInitializer(Context, false)) 8335 Diag(Init->getExprLoc(), 8336 diag::ext_aggregate_init_not_constant) 8337 << Init->getSourceRange(); 8338 } 8339 } else if (VDecl->isStaticDataMember() && 8340 VDecl->getLexicalDeclContext()->isRecord()) { 8341 // This is an in-class initialization for a static data member, e.g., 8342 // 8343 // struct S { 8344 // static const int value = 17; 8345 // }; 8346 8347 // C++ [class.mem]p4: 8348 // A member-declarator can contain a constant-initializer only 8349 // if it declares a static member (9.4) of const integral or 8350 // const enumeration type, see 9.4.2. 8351 // 8352 // C++11 [class.static.data]p3: 8353 // If a non-volatile const static data member is of integral or 8354 // enumeration type, its declaration in the class definition can 8355 // specify a brace-or-equal-initializer in which every initalizer-clause 8356 // that is an assignment-expression is a constant expression. A static 8357 // data member of literal type can be declared in the class definition 8358 // with the constexpr specifier; if so, its declaration shall specify a 8359 // brace-or-equal-initializer in which every initializer-clause that is 8360 // an assignment-expression is a constant expression. 8361 8362 // Do nothing on dependent types. 8363 if (DclT->isDependentType()) { 8364 8365 // Allow any 'static constexpr' members, whether or not they are of literal 8366 // type. We separately check that every constexpr variable is of literal 8367 // type. 8368 } else if (VDecl->isConstexpr()) { 8369 8370 // Require constness. 8371 } else if (!DclT.isConstQualified()) { 8372 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8373 << Init->getSourceRange(); 8374 VDecl->setInvalidDecl(); 8375 8376 // We allow integer constant expressions in all cases. 8377 } else if (DclT->isIntegralOrEnumerationType()) { 8378 // Check whether the expression is a constant expression. 8379 SourceLocation Loc; 8380 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8381 // In C++11, a non-constexpr const static data member with an 8382 // in-class initializer cannot be volatile. 8383 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8384 else if (Init->isValueDependent()) 8385 ; // Nothing to check. 8386 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8387 ; // Ok, it's an ICE! 8388 else if (Init->isEvaluatable(Context)) { 8389 // If we can constant fold the initializer through heroics, accept it, 8390 // but report this as a use of an extension for -pedantic. 8391 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8392 << Init->getSourceRange(); 8393 } else { 8394 // Otherwise, this is some crazy unknown case. Report the issue at the 8395 // location provided by the isIntegerConstantExpr failed check. 8396 Diag(Loc, diag::err_in_class_initializer_non_constant) 8397 << Init->getSourceRange(); 8398 VDecl->setInvalidDecl(); 8399 } 8400 8401 // We allow foldable floating-point constants as an extension. 8402 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8403 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8404 // it anyway and provide a fixit to add the 'constexpr'. 8405 if (getLangOpts().CPlusPlus11) { 8406 Diag(VDecl->getLocation(), 8407 diag::ext_in_class_initializer_float_type_cxx11) 8408 << DclT << Init->getSourceRange(); 8409 Diag(VDecl->getLocStart(), 8410 diag::note_in_class_initializer_float_type_cxx11) 8411 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8412 } else { 8413 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8414 << DclT << Init->getSourceRange(); 8415 8416 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8417 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8418 << Init->getSourceRange(); 8419 VDecl->setInvalidDecl(); 8420 } 8421 } 8422 8423 // Suggest adding 'constexpr' in C++11 for literal types. 8424 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8425 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8426 << DclT << Init->getSourceRange() 8427 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8428 VDecl->setConstexpr(true); 8429 8430 } else { 8431 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8432 << DclT << Init->getSourceRange(); 8433 VDecl->setInvalidDecl(); 8434 } 8435 } else if (VDecl->isFileVarDecl()) { 8436 if (VDecl->getStorageClass() == SC_Extern && 8437 (!getLangOpts().CPlusPlus || 8438 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8439 VDecl->isExternC())) && 8440 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8441 Diag(VDecl->getLocation(), diag::warn_extern_init); 8442 8443 // C99 6.7.8p4. All file scoped initializers need to be constant. 8444 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8445 CheckForConstantInitializer(Init, DclT); 8446 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8447 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8448 !Init->isValueDependent() && !VDecl->isConstexpr() && 8449 !Init->isConstantInitializer( 8450 Context, VDecl->getType()->isReferenceType())) { 8451 // GNU C++98 edits for __thread, [basic.start.init]p4: 8452 // An object of thread storage duration shall not require dynamic 8453 // initialization. 8454 // FIXME: Need strict checking here. 8455 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8456 if (getLangOpts().CPlusPlus11) 8457 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8458 } 8459 } 8460 8461 // We will represent direct-initialization similarly to copy-initialization: 8462 // int x(1); -as-> int x = 1; 8463 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8464 // 8465 // Clients that want to distinguish between the two forms, can check for 8466 // direct initializer using VarDecl::getInitStyle(). 8467 // A major benefit is that clients that don't particularly care about which 8468 // exactly form was it (like the CodeGen) can handle both cases without 8469 // special case code. 8470 8471 // C++ 8.5p11: 8472 // The form of initialization (using parentheses or '=') is generally 8473 // insignificant, but does matter when the entity being initialized has a 8474 // class type. 8475 if (CXXDirectInit) { 8476 assert(DirectInit && "Call-style initializer must be direct init."); 8477 VDecl->setInitStyle(VarDecl::CallInit); 8478 } else if (DirectInit) { 8479 // This must be list-initialization. No other way is direct-initialization. 8480 VDecl->setInitStyle(VarDecl::ListInit); 8481 } 8482 8483 CheckCompleteVariableDeclaration(VDecl); 8484 } 8485 8486 /// ActOnInitializerError - Given that there was an error parsing an 8487 /// initializer for the given declaration, try to return to some form 8488 /// of sanity. 8489 void Sema::ActOnInitializerError(Decl *D) { 8490 // Our main concern here is re-establishing invariants like "a 8491 // variable's type is either dependent or complete". 8492 if (!D || D->isInvalidDecl()) return; 8493 8494 VarDecl *VD = dyn_cast<VarDecl>(D); 8495 if (!VD) return; 8496 8497 // Auto types are meaningless if we can't make sense of the initializer. 8498 if (ParsingInitForAutoVars.count(D)) { 8499 D->setInvalidDecl(); 8500 return; 8501 } 8502 8503 QualType Ty = VD->getType(); 8504 if (Ty->isDependentType()) return; 8505 8506 // Require a complete type. 8507 if (RequireCompleteType(VD->getLocation(), 8508 Context.getBaseElementType(Ty), 8509 diag::err_typecheck_decl_incomplete_type)) { 8510 VD->setInvalidDecl(); 8511 return; 8512 } 8513 8514 // Require an abstract type. 8515 if (RequireNonAbstractType(VD->getLocation(), Ty, 8516 diag::err_abstract_type_in_decl, 8517 AbstractVariableType)) { 8518 VD->setInvalidDecl(); 8519 return; 8520 } 8521 8522 // Don't bother complaining about constructors or destructors, 8523 // though. 8524 } 8525 8526 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8527 bool TypeMayContainAuto) { 8528 // If there is no declaration, there was an error parsing it. Just ignore it. 8529 if (RealDecl == 0) 8530 return; 8531 8532 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8533 QualType Type = Var->getType(); 8534 8535 // C++11 [dcl.spec.auto]p3 8536 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8537 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8538 << Var->getDeclName() << Type; 8539 Var->setInvalidDecl(); 8540 return; 8541 } 8542 8543 // C++11 [class.static.data]p3: A static data member can be declared with 8544 // the constexpr specifier; if so, its declaration shall specify 8545 // a brace-or-equal-initializer. 8546 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8547 // the definition of a variable [...] or the declaration of a static data 8548 // member. 8549 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8550 if (Var->isStaticDataMember()) 8551 Diag(Var->getLocation(), 8552 diag::err_constexpr_static_mem_var_requires_init) 8553 << Var->getDeclName(); 8554 else 8555 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8556 Var->setInvalidDecl(); 8557 return; 8558 } 8559 8560 switch (Var->isThisDeclarationADefinition()) { 8561 case VarDecl::Definition: 8562 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8563 break; 8564 8565 // We have an out-of-line definition of a static data member 8566 // that has an in-class initializer, so we type-check this like 8567 // a declaration. 8568 // 8569 // Fall through 8570 8571 case VarDecl::DeclarationOnly: 8572 // It's only a declaration. 8573 8574 // Block scope. C99 6.7p7: If an identifier for an object is 8575 // declared with no linkage (C99 6.2.2p6), the type for the 8576 // object shall be complete. 8577 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8578 !Var->hasLinkage() && !Var->isInvalidDecl() && 8579 RequireCompleteType(Var->getLocation(), Type, 8580 diag::err_typecheck_decl_incomplete_type)) 8581 Var->setInvalidDecl(); 8582 8583 // Make sure that the type is not abstract. 8584 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8585 RequireNonAbstractType(Var->getLocation(), Type, 8586 diag::err_abstract_type_in_decl, 8587 AbstractVariableType)) 8588 Var->setInvalidDecl(); 8589 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8590 Var->getStorageClass() == SC_PrivateExtern) { 8591 Diag(Var->getLocation(), diag::warn_private_extern); 8592 Diag(Var->getLocation(), diag::note_private_extern); 8593 } 8594 8595 return; 8596 8597 case VarDecl::TentativeDefinition: 8598 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8599 // object that has file scope without an initializer, and without a 8600 // storage-class specifier or with the storage-class specifier "static", 8601 // constitutes a tentative definition. Note: A tentative definition with 8602 // external linkage is valid (C99 6.2.2p5). 8603 if (!Var->isInvalidDecl()) { 8604 if (const IncompleteArrayType *ArrayT 8605 = Context.getAsIncompleteArrayType(Type)) { 8606 if (RequireCompleteType(Var->getLocation(), 8607 ArrayT->getElementType(), 8608 diag::err_illegal_decl_array_incomplete_type)) 8609 Var->setInvalidDecl(); 8610 } else if (Var->getStorageClass() == SC_Static) { 8611 // C99 6.9.2p3: If the declaration of an identifier for an object is 8612 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8613 // declared type shall not be an incomplete type. 8614 // NOTE: code such as the following 8615 // static struct s; 8616 // struct s { int a; }; 8617 // is accepted by gcc. Hence here we issue a warning instead of 8618 // an error and we do not invalidate the static declaration. 8619 // NOTE: to avoid multiple warnings, only check the first declaration. 8620 if (Var->isFirstDecl()) 8621 RequireCompleteType(Var->getLocation(), Type, 8622 diag::ext_typecheck_decl_incomplete_type); 8623 } 8624 } 8625 8626 // Record the tentative definition; we're done. 8627 if (!Var->isInvalidDecl()) 8628 TentativeDefinitions.push_back(Var); 8629 return; 8630 } 8631 8632 // Provide a specific diagnostic for uninitialized variable 8633 // definitions with incomplete array type. 8634 if (Type->isIncompleteArrayType()) { 8635 Diag(Var->getLocation(), 8636 diag::err_typecheck_incomplete_array_needs_initializer); 8637 Var->setInvalidDecl(); 8638 return; 8639 } 8640 8641 // Provide a specific diagnostic for uninitialized variable 8642 // definitions with reference type. 8643 if (Type->isReferenceType()) { 8644 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8645 << Var->getDeclName() 8646 << SourceRange(Var->getLocation(), Var->getLocation()); 8647 Var->setInvalidDecl(); 8648 return; 8649 } 8650 8651 // Do not attempt to type-check the default initializer for a 8652 // variable with dependent type. 8653 if (Type->isDependentType()) 8654 return; 8655 8656 if (Var->isInvalidDecl()) 8657 return; 8658 8659 if (RequireCompleteType(Var->getLocation(), 8660 Context.getBaseElementType(Type), 8661 diag::err_typecheck_decl_incomplete_type)) { 8662 Var->setInvalidDecl(); 8663 return; 8664 } 8665 8666 // The variable can not have an abstract class type. 8667 if (RequireNonAbstractType(Var->getLocation(), Type, 8668 diag::err_abstract_type_in_decl, 8669 AbstractVariableType)) { 8670 Var->setInvalidDecl(); 8671 return; 8672 } 8673 8674 // Check for jumps past the implicit initializer. C++0x 8675 // clarifies that this applies to a "variable with automatic 8676 // storage duration", not a "local variable". 8677 // C++11 [stmt.dcl]p3 8678 // A program that jumps from a point where a variable with automatic 8679 // storage duration is not in scope to a point where it is in scope is 8680 // ill-formed unless the variable has scalar type, class type with a 8681 // trivial default constructor and a trivial destructor, a cv-qualified 8682 // version of one of these types, or an array of one of the preceding 8683 // types and is declared without an initializer. 8684 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8685 if (const RecordType *Record 8686 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8687 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8688 // Mark the function for further checking even if the looser rules of 8689 // C++11 do not require such checks, so that we can diagnose 8690 // incompatibilities with C++98. 8691 if (!CXXRecord->isPOD()) 8692 getCurFunction()->setHasBranchProtectedScope(); 8693 } 8694 } 8695 8696 // C++03 [dcl.init]p9: 8697 // If no initializer is specified for an object, and the 8698 // object is of (possibly cv-qualified) non-POD class type (or 8699 // array thereof), the object shall be default-initialized; if 8700 // the object is of const-qualified type, the underlying class 8701 // type shall have a user-declared default 8702 // constructor. Otherwise, if no initializer is specified for 8703 // a non- static object, the object and its subobjects, if 8704 // any, have an indeterminate initial value); if the object 8705 // or any of its subobjects are of const-qualified type, the 8706 // program is ill-formed. 8707 // C++0x [dcl.init]p11: 8708 // If no initializer is specified for an object, the object is 8709 // default-initialized; [...]. 8710 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8711 InitializationKind Kind 8712 = InitializationKind::CreateDefault(Var->getLocation()); 8713 8714 InitializationSequence InitSeq(*this, Entity, Kind, None); 8715 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8716 if (Init.isInvalid()) 8717 Var->setInvalidDecl(); 8718 else if (Init.get()) { 8719 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8720 // This is important for template substitution. 8721 Var->setInitStyle(VarDecl::CallInit); 8722 } 8723 8724 CheckCompleteVariableDeclaration(Var); 8725 } 8726 } 8727 8728 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8729 VarDecl *VD = dyn_cast<VarDecl>(D); 8730 if (!VD) { 8731 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8732 D->setInvalidDecl(); 8733 return; 8734 } 8735 8736 VD->setCXXForRangeDecl(true); 8737 8738 // for-range-declaration cannot be given a storage class specifier. 8739 int Error = -1; 8740 switch (VD->getStorageClass()) { 8741 case SC_None: 8742 break; 8743 case SC_Extern: 8744 Error = 0; 8745 break; 8746 case SC_Static: 8747 Error = 1; 8748 break; 8749 case SC_PrivateExtern: 8750 Error = 2; 8751 break; 8752 case SC_Auto: 8753 Error = 3; 8754 break; 8755 case SC_Register: 8756 Error = 4; 8757 break; 8758 case SC_OpenCLWorkGroupLocal: 8759 llvm_unreachable("Unexpected storage class"); 8760 } 8761 if (VD->isConstexpr()) 8762 Error = 5; 8763 if (Error != -1) { 8764 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8765 << VD->getDeclName() << Error; 8766 D->setInvalidDecl(); 8767 } 8768 } 8769 8770 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8771 if (var->isInvalidDecl()) return; 8772 8773 // In ARC, don't allow jumps past the implicit initialization of a 8774 // local retaining variable. 8775 if (getLangOpts().ObjCAutoRefCount && 8776 var->hasLocalStorage()) { 8777 switch (var->getType().getObjCLifetime()) { 8778 case Qualifiers::OCL_None: 8779 case Qualifiers::OCL_ExplicitNone: 8780 case Qualifiers::OCL_Autoreleasing: 8781 break; 8782 8783 case Qualifiers::OCL_Weak: 8784 case Qualifiers::OCL_Strong: 8785 getCurFunction()->setHasBranchProtectedScope(); 8786 break; 8787 } 8788 } 8789 8790 if (var->isThisDeclarationADefinition() && 8791 var->isExternallyVisible() && var->hasLinkage() && 8792 getDiagnostics().getDiagnosticLevel( 8793 diag::warn_missing_variable_declarations, 8794 var->getLocation())) { 8795 // Find a previous declaration that's not a definition. 8796 VarDecl *prev = var->getPreviousDecl(); 8797 while (prev && prev->isThisDeclarationADefinition()) 8798 prev = prev->getPreviousDecl(); 8799 8800 if (!prev) 8801 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8802 } 8803 8804 if (var->getTLSKind() == VarDecl::TLS_Static && 8805 var->getType().isDestructedType()) { 8806 // GNU C++98 edits for __thread, [basic.start.term]p3: 8807 // The type of an object with thread storage duration shall not 8808 // have a non-trivial destructor. 8809 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8810 if (getLangOpts().CPlusPlus11) 8811 Diag(var->getLocation(), diag::note_use_thread_local); 8812 } 8813 8814 // All the following checks are C++ only. 8815 if (!getLangOpts().CPlusPlus) return; 8816 8817 QualType type = var->getType(); 8818 if (type->isDependentType()) return; 8819 8820 // __block variables might require us to capture a copy-initializer. 8821 if (var->hasAttr<BlocksAttr>()) { 8822 // It's currently invalid to ever have a __block variable with an 8823 // array type; should we diagnose that here? 8824 8825 // Regardless, we don't want to ignore array nesting when 8826 // constructing this copy. 8827 if (type->isStructureOrClassType()) { 8828 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8829 SourceLocation poi = var->getLocation(); 8830 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8831 ExprResult result 8832 = PerformMoveOrCopyInitialization( 8833 InitializedEntity::InitializeBlock(poi, type, false), 8834 var, var->getType(), varRef, /*AllowNRVO=*/true); 8835 if (!result.isInvalid()) { 8836 result = MaybeCreateExprWithCleanups(result); 8837 Expr *init = result.takeAs<Expr>(); 8838 Context.setBlockVarCopyInits(var, init); 8839 } 8840 } 8841 } 8842 8843 Expr *Init = var->getInit(); 8844 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8845 QualType baseType = Context.getBaseElementType(type); 8846 8847 if (!var->getDeclContext()->isDependentContext() && 8848 Init && !Init->isValueDependent()) { 8849 if (IsGlobal && !var->isConstexpr() && 8850 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8851 var->getLocation()) 8852 != DiagnosticsEngine::Ignored) { 8853 // Warn about globals which don't have a constant initializer. Don't 8854 // warn about globals with a non-trivial destructor because we already 8855 // warned about them. 8856 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8857 if (!(RD && !RD->hasTrivialDestructor()) && 8858 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8859 Diag(var->getLocation(), diag::warn_global_constructor) 8860 << Init->getSourceRange(); 8861 } 8862 8863 if (var->isConstexpr()) { 8864 SmallVector<PartialDiagnosticAt, 8> Notes; 8865 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8866 SourceLocation DiagLoc = var->getLocation(); 8867 // If the note doesn't add any useful information other than a source 8868 // location, fold it into the primary diagnostic. 8869 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 8870 diag::note_invalid_subexpr_in_const_expr) { 8871 DiagLoc = Notes[0].first; 8872 Notes.clear(); 8873 } 8874 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 8875 << var << Init->getSourceRange(); 8876 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 8877 Diag(Notes[I].first, Notes[I].second); 8878 } 8879 } else if (var->isUsableInConstantExpressions(Context)) { 8880 // Check whether the initializer of a const variable of integral or 8881 // enumeration type is an ICE now, since we can't tell whether it was 8882 // initialized by a constant expression if we check later. 8883 var->checkInitIsICE(); 8884 } 8885 } 8886 8887 // Require the destructor. 8888 if (const RecordType *recordType = baseType->getAs<RecordType>()) 8889 FinalizeVarWithDestructor(var, recordType); 8890 } 8891 8892 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 8893 /// any semantic actions necessary after any initializer has been attached. 8894 void 8895 Sema::FinalizeDeclaration(Decl *ThisDecl) { 8896 // Note that we are no longer parsing the initializer for this declaration. 8897 ParsingInitForAutoVars.erase(ThisDecl); 8898 8899 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 8900 if (!VD) 8901 return; 8902 8903 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 8904 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 8905 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used"; 8906 VD->dropAttr<UsedAttr>(); 8907 } 8908 } 8909 8910 if (!VD->isInvalidDecl() && 8911 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 8912 if (const VarDecl *Def = VD->getDefinition()) { 8913 if (Def->hasAttr<AliasAttr>()) { 8914 Diag(VD->getLocation(), diag::err_tentative_after_alias) 8915 << VD->getDeclName(); 8916 Diag(Def->getLocation(), diag::note_previous_definition); 8917 VD->setInvalidDecl(); 8918 } 8919 } 8920 } 8921 8922 const DeclContext *DC = VD->getDeclContext(); 8923 // If there's a #pragma GCC visibility in scope, and this isn't a class 8924 // member, set the visibility of this variable. 8925 if (!DC->isRecord() && VD->isExternallyVisible()) 8926 AddPushedVisibilityAttribute(VD); 8927 8928 if (VD->isFileVarDecl()) 8929 MarkUnusedFileScopedDecl(VD); 8930 8931 // Now we have parsed the initializer and can update the table of magic 8932 // tag values. 8933 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8934 !VD->getType()->isIntegralOrEnumerationType()) 8935 return; 8936 8937 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8938 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8939 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8940 I != E; ++I) { 8941 const Expr *MagicValueExpr = VD->getInit(); 8942 if (!MagicValueExpr) { 8943 continue; 8944 } 8945 llvm::APSInt MagicValueInt; 8946 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8947 Diag(I->getRange().getBegin(), 8948 diag::err_type_tag_for_datatype_not_ice) 8949 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8950 continue; 8951 } 8952 if (MagicValueInt.getActiveBits() > 64) { 8953 Diag(I->getRange().getBegin(), 8954 diag::err_type_tag_for_datatype_too_large) 8955 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8956 continue; 8957 } 8958 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8959 RegisterTypeTagForDatatype(I->getArgumentKind(), 8960 MagicValue, 8961 I->getMatchingCType(), 8962 I->getLayoutCompatible(), 8963 I->getMustBeNull()); 8964 } 8965 } 8966 8967 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8968 ArrayRef<Decl *> Group) { 8969 SmallVector<Decl*, 8> Decls; 8970 8971 if (DS.isTypeSpecOwned()) 8972 Decls.push_back(DS.getRepAsDecl()); 8973 8974 DeclaratorDecl *FirstDeclaratorInGroup = 0; 8975 for (unsigned i = 0, e = Group.size(); i != e; ++i) 8976 if (Decl *D = Group[i]) { 8977 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 8978 if (!FirstDeclaratorInGroup) 8979 FirstDeclaratorInGroup = DD; 8980 Decls.push_back(D); 8981 } 8982 8983 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 8984 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 8985 HandleTagNumbering(*this, Tag); 8986 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 8987 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 8988 } 8989 } 8990 8991 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 8992 } 8993 8994 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 8995 /// group, performing any necessary semantic checking. 8996 Sema::DeclGroupPtrTy 8997 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 8998 bool TypeMayContainAuto) { 8999 // C++0x [dcl.spec.auto]p7: 9000 // If the type deduced for the template parameter U is not the same in each 9001 // deduction, the program is ill-formed. 9002 // FIXME: When initializer-list support is added, a distinction is needed 9003 // between the deduced type U and the deduced type which 'auto' stands for. 9004 // auto a = 0, b = { 1, 2, 3 }; 9005 // is legal because the deduced type U is 'int' in both cases. 9006 if (TypeMayContainAuto && Group.size() > 1) { 9007 QualType Deduced; 9008 CanQualType DeducedCanon; 9009 VarDecl *DeducedDecl = 0; 9010 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9011 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9012 AutoType *AT = D->getType()->getContainedAutoType(); 9013 // Don't reissue diagnostics when instantiating a template. 9014 if (AT && D->isInvalidDecl()) 9015 break; 9016 QualType U = AT ? AT->getDeducedType() : QualType(); 9017 if (!U.isNull()) { 9018 CanQualType UCanon = Context.getCanonicalType(U); 9019 if (Deduced.isNull()) { 9020 Deduced = U; 9021 DeducedCanon = UCanon; 9022 DeducedDecl = D; 9023 } else if (DeducedCanon != UCanon) { 9024 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9025 diag::err_auto_different_deductions) 9026 << (AT->isDecltypeAuto() ? 1 : 0) 9027 << Deduced << DeducedDecl->getDeclName() 9028 << U << D->getDeclName() 9029 << DeducedDecl->getInit()->getSourceRange() 9030 << D->getInit()->getSourceRange(); 9031 D->setInvalidDecl(); 9032 break; 9033 } 9034 } 9035 } 9036 } 9037 } 9038 9039 ActOnDocumentableDecls(Group); 9040 9041 return DeclGroupPtrTy::make( 9042 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9043 } 9044 9045 void Sema::ActOnDocumentableDecl(Decl *D) { 9046 ActOnDocumentableDecls(D); 9047 } 9048 9049 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9050 // Don't parse the comment if Doxygen diagnostics are ignored. 9051 if (Group.empty() || !Group[0]) 9052 return; 9053 9054 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9055 Group[0]->getLocation()) 9056 == DiagnosticsEngine::Ignored) 9057 return; 9058 9059 if (Group.size() >= 2) { 9060 // This is a decl group. Normally it will contain only declarations 9061 // produced from declarator list. But in case we have any definitions or 9062 // additional declaration references: 9063 // 'typedef struct S {} S;' 9064 // 'typedef struct S *S;' 9065 // 'struct S *pS;' 9066 // FinalizeDeclaratorGroup adds these as separate declarations. 9067 Decl *MaybeTagDecl = Group[0]; 9068 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9069 Group = Group.slice(1); 9070 } 9071 } 9072 9073 // See if there are any new comments that are not attached to a decl. 9074 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9075 if (!Comments.empty() && 9076 !Comments.back()->isAttached()) { 9077 // There is at least one comment that not attached to a decl. 9078 // Maybe it should be attached to one of these decls? 9079 // 9080 // Note that this way we pick up not only comments that precede the 9081 // declaration, but also comments that *follow* the declaration -- thanks to 9082 // the lookahead in the lexer: we've consumed the semicolon and looked 9083 // ahead through comments. 9084 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9085 Context.getCommentForDecl(Group[i], &PP); 9086 } 9087 } 9088 9089 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9090 /// to introduce parameters into function prototype scope. 9091 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9092 const DeclSpec &DS = D.getDeclSpec(); 9093 9094 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9095 9096 // C++03 [dcl.stc]p2 also permits 'auto'. 9097 VarDecl::StorageClass StorageClass = SC_None; 9098 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9099 StorageClass = SC_Register; 9100 } else if (getLangOpts().CPlusPlus && 9101 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9102 StorageClass = SC_Auto; 9103 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9104 Diag(DS.getStorageClassSpecLoc(), 9105 diag::err_invalid_storage_class_in_func_decl); 9106 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9107 } 9108 9109 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9110 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9111 << DeclSpec::getSpecifierName(TSCS); 9112 if (DS.isConstexprSpecified()) 9113 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9114 << 0; 9115 9116 DiagnoseFunctionSpecifiers(DS); 9117 9118 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9119 QualType parmDeclType = TInfo->getType(); 9120 9121 if (getLangOpts().CPlusPlus) { 9122 // Check that there are no default arguments inside the type of this 9123 // parameter. 9124 CheckExtraCXXDefaultArguments(D); 9125 9126 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9127 if (D.getCXXScopeSpec().isSet()) { 9128 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9129 << D.getCXXScopeSpec().getRange(); 9130 D.getCXXScopeSpec().clear(); 9131 } 9132 } 9133 9134 // Ensure we have a valid name 9135 IdentifierInfo *II = 0; 9136 if (D.hasName()) { 9137 II = D.getIdentifier(); 9138 if (!II) { 9139 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9140 << GetNameForDeclarator(D).getName().getAsString(); 9141 D.setInvalidType(true); 9142 } 9143 } 9144 9145 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9146 if (II) { 9147 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9148 ForRedeclaration); 9149 LookupName(R, S); 9150 if (R.isSingleResult()) { 9151 NamedDecl *PrevDecl = R.getFoundDecl(); 9152 if (PrevDecl->isTemplateParameter()) { 9153 // Maybe we will complain about the shadowed template parameter. 9154 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9155 // Just pretend that we didn't see the previous declaration. 9156 PrevDecl = 0; 9157 } else if (S->isDeclScope(PrevDecl)) { 9158 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9159 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9160 9161 // Recover by removing the name 9162 II = 0; 9163 D.SetIdentifier(0, D.getIdentifierLoc()); 9164 D.setInvalidType(true); 9165 } 9166 } 9167 } 9168 9169 // Temporarily put parameter variables in the translation unit, not 9170 // the enclosing context. This prevents them from accidentally 9171 // looking like class members in C++. 9172 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9173 D.getLocStart(), 9174 D.getIdentifierLoc(), II, 9175 parmDeclType, TInfo, 9176 StorageClass); 9177 9178 if (D.isInvalidType()) 9179 New->setInvalidDecl(); 9180 9181 assert(S->isFunctionPrototypeScope()); 9182 assert(S->getFunctionPrototypeDepth() >= 1); 9183 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9184 S->getNextFunctionPrototypeIndex()); 9185 9186 // Add the parameter declaration into this scope. 9187 S->AddDecl(New); 9188 if (II) 9189 IdResolver.AddDecl(New); 9190 9191 ProcessDeclAttributes(S, New, D); 9192 9193 if (D.getDeclSpec().isModulePrivateSpecified()) 9194 Diag(New->getLocation(), diag::err_module_private_local) 9195 << 1 << New->getDeclName() 9196 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9197 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9198 9199 if (New->hasAttr<BlocksAttr>()) { 9200 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9201 } 9202 return New; 9203 } 9204 9205 /// \brief Synthesizes a variable for a parameter arising from a 9206 /// typedef. 9207 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9208 SourceLocation Loc, 9209 QualType T) { 9210 /* FIXME: setting StartLoc == Loc. 9211 Would it be worth to modify callers so as to provide proper source 9212 location for the unnamed parameters, embedding the parameter's type? */ 9213 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9214 T, Context.getTrivialTypeSourceInfo(T, Loc), 9215 SC_None, 0); 9216 Param->setImplicit(); 9217 return Param; 9218 } 9219 9220 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9221 ParmVarDecl * const *ParamEnd) { 9222 // Don't diagnose unused-parameter errors in template instantiations; we 9223 // will already have done so in the template itself. 9224 if (!ActiveTemplateInstantiations.empty()) 9225 return; 9226 9227 for (; Param != ParamEnd; ++Param) { 9228 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9229 !(*Param)->hasAttr<UnusedAttr>()) { 9230 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9231 << (*Param)->getDeclName(); 9232 } 9233 } 9234 } 9235 9236 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9237 ParmVarDecl * const *ParamEnd, 9238 QualType ReturnTy, 9239 NamedDecl *D) { 9240 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9241 return; 9242 9243 // Warn if the return value is pass-by-value and larger than the specified 9244 // threshold. 9245 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9246 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9247 if (Size > LangOpts.NumLargeByValueCopy) 9248 Diag(D->getLocation(), diag::warn_return_value_size) 9249 << D->getDeclName() << Size; 9250 } 9251 9252 // Warn if any parameter is pass-by-value and larger than the specified 9253 // threshold. 9254 for (; Param != ParamEnd; ++Param) { 9255 QualType T = (*Param)->getType(); 9256 if (T->isDependentType() || !T.isPODType(Context)) 9257 continue; 9258 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9259 if (Size > LangOpts.NumLargeByValueCopy) 9260 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9261 << (*Param)->getDeclName() << Size; 9262 } 9263 } 9264 9265 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9266 SourceLocation NameLoc, IdentifierInfo *Name, 9267 QualType T, TypeSourceInfo *TSInfo, 9268 VarDecl::StorageClass StorageClass) { 9269 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9270 if (getLangOpts().ObjCAutoRefCount && 9271 T.getObjCLifetime() == Qualifiers::OCL_None && 9272 T->isObjCLifetimeType()) { 9273 9274 Qualifiers::ObjCLifetime lifetime; 9275 9276 // Special cases for arrays: 9277 // - if it's const, use __unsafe_unretained 9278 // - otherwise, it's an error 9279 if (T->isArrayType()) { 9280 if (!T.isConstQualified()) { 9281 DelayedDiagnostics.add( 9282 sema::DelayedDiagnostic::makeForbiddenType( 9283 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9284 } 9285 lifetime = Qualifiers::OCL_ExplicitNone; 9286 } else { 9287 lifetime = T->getObjCARCImplicitLifetime(); 9288 } 9289 T = Context.getLifetimeQualifiedType(T, lifetime); 9290 } 9291 9292 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9293 Context.getAdjustedParameterType(T), 9294 TSInfo, 9295 StorageClass, 0); 9296 9297 // Parameters can not be abstract class types. 9298 // For record types, this is done by the AbstractClassUsageDiagnoser once 9299 // the class has been completely parsed. 9300 if (!CurContext->isRecord() && 9301 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9302 AbstractParamType)) 9303 New->setInvalidDecl(); 9304 9305 // Parameter declarators cannot be interface types. All ObjC objects are 9306 // passed by reference. 9307 if (T->isObjCObjectType()) { 9308 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9309 Diag(NameLoc, 9310 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9311 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9312 T = Context.getObjCObjectPointerType(T); 9313 New->setType(T); 9314 } 9315 9316 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9317 // duration shall not be qualified by an address-space qualifier." 9318 // Since all parameters have automatic store duration, they can not have 9319 // an address space. 9320 if (T.getAddressSpace() != 0) { 9321 Diag(NameLoc, diag::err_arg_with_address_space); 9322 New->setInvalidDecl(); 9323 } 9324 9325 return New; 9326 } 9327 9328 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9329 SourceLocation LocAfterDecls) { 9330 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9331 9332 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9333 // for a K&R function. 9334 if (!FTI.hasPrototype) { 9335 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 9336 --i; 9337 if (FTI.ArgInfo[i].Param == 0) { 9338 SmallString<256> Code; 9339 llvm::raw_svector_ostream(Code) << " int " 9340 << FTI.ArgInfo[i].Ident->getName() 9341 << ";\n"; 9342 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 9343 << FTI.ArgInfo[i].Ident 9344 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9345 9346 // Implicitly declare the argument as type 'int' for lack of a better 9347 // type. 9348 AttributeFactory attrs; 9349 DeclSpec DS(attrs); 9350 const char* PrevSpec; // unused 9351 unsigned DiagID; // unused 9352 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 9353 PrevSpec, DiagID); 9354 // Use the identifier location for the type source range. 9355 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 9356 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 9357 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9358 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 9359 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 9360 } 9361 } 9362 } 9363 } 9364 9365 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9366 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9367 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9368 Scope *ParentScope = FnBodyScope->getParent(); 9369 9370 D.setFunctionDefinitionKind(FDK_Definition); 9371 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9372 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9373 } 9374 9375 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9376 const FunctionDecl*& PossibleZeroParamPrototype) { 9377 // Don't warn about invalid declarations. 9378 if (FD->isInvalidDecl()) 9379 return false; 9380 9381 // Or declarations that aren't global. 9382 if (!FD->isGlobal()) 9383 return false; 9384 9385 // Don't warn about C++ member functions. 9386 if (isa<CXXMethodDecl>(FD)) 9387 return false; 9388 9389 // Don't warn about 'main'. 9390 if (FD->isMain()) 9391 return false; 9392 9393 // Don't warn about inline functions. 9394 if (FD->isInlined()) 9395 return false; 9396 9397 // Don't warn about function templates. 9398 if (FD->getDescribedFunctionTemplate()) 9399 return false; 9400 9401 // Don't warn about function template specializations. 9402 if (FD->isFunctionTemplateSpecialization()) 9403 return false; 9404 9405 // Don't warn for OpenCL kernels. 9406 if (FD->hasAttr<OpenCLKernelAttr>()) 9407 return false; 9408 9409 bool MissingPrototype = true; 9410 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9411 Prev; Prev = Prev->getPreviousDecl()) { 9412 // Ignore any declarations that occur in function or method 9413 // scope, because they aren't visible from the header. 9414 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9415 continue; 9416 9417 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9418 if (FD->getNumParams() == 0) 9419 PossibleZeroParamPrototype = Prev; 9420 break; 9421 } 9422 9423 return MissingPrototype; 9424 } 9425 9426 void 9427 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9428 const FunctionDecl *EffectiveDefinition) { 9429 // Don't complain if we're in GNU89 mode and the previous definition 9430 // was an extern inline function. 9431 const FunctionDecl *Definition = EffectiveDefinition; 9432 if (!Definition) 9433 if (!FD->isDefined(Definition)) 9434 return; 9435 9436 if (canRedefineFunction(Definition, getLangOpts())) 9437 return; 9438 9439 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9440 Definition->getStorageClass() == SC_Extern) 9441 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9442 << FD->getDeclName() << getLangOpts().CPlusPlus; 9443 else 9444 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9445 9446 Diag(Definition->getLocation(), diag::note_previous_definition); 9447 FD->setInvalidDecl(); 9448 } 9449 9450 9451 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9452 Sema &S) { 9453 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9454 9455 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9456 LSI->CallOperator = CallOperator; 9457 LSI->Lambda = LambdaClass; 9458 LSI->ReturnType = CallOperator->getResultType(); 9459 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9460 9461 if (LCD == LCD_None) 9462 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9463 else if (LCD == LCD_ByCopy) 9464 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9465 else if (LCD == LCD_ByRef) 9466 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9467 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9468 9469 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9470 LSI->Mutable = !CallOperator->isConst(); 9471 9472 // Add the captures to the LSI so they can be noted as already 9473 // captured within tryCaptureVar. 9474 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(), 9475 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) { 9476 if (C->capturesVariable()) { 9477 VarDecl *VD = C->getCapturedVar(); 9478 if (VD->isInitCapture()) 9479 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9480 QualType CaptureType = VD->getType(); 9481 const bool ByRef = C->getCaptureKind() == LCK_ByRef; 9482 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9483 /*RefersToEnclosingLocal*/true, C->getLocation(), 9484 /*EllipsisLoc*/C->isPackExpansion() 9485 ? C->getEllipsisLoc() : SourceLocation(), 9486 CaptureType, /*Expr*/ 0); 9487 9488 } else if (C->capturesThis()) { 9489 LSI->addThisCapture(/*Nested*/ false, C->getLocation(), 9490 S.getCurrentThisType(), /*Expr*/ 0); 9491 } 9492 } 9493 } 9494 9495 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9496 // Clear the last template instantiation error context. 9497 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9498 9499 if (!D) 9500 return D; 9501 FunctionDecl *FD = 0; 9502 9503 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9504 FD = FunTmpl->getTemplatedDecl(); 9505 else 9506 FD = cast<FunctionDecl>(D); 9507 // If we are instantiating a generic lambda call operator, push 9508 // a LambdaScopeInfo onto the function stack. But use the information 9509 // that's already been calculated (ActOnLambdaExpr) to prime the current 9510 // LambdaScopeInfo. 9511 // When the template operator is being specialized, the LambdaScopeInfo, 9512 // has to be properly restored so that tryCaptureVariable doesn't try 9513 // and capture any new variables. In addition when calculating potential 9514 // captures during transformation of nested lambdas, it is necessary to 9515 // have the LSI properly restored. 9516 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9517 assert(ActiveTemplateInstantiations.size() && 9518 "There should be an active template instantiation on the stack " 9519 "when instantiating a generic lambda!"); 9520 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9521 } 9522 else 9523 // Enter a new function scope 9524 PushFunctionScope(); 9525 9526 // See if this is a redefinition. 9527 if (!FD->isLateTemplateParsed()) 9528 CheckForFunctionRedefinition(FD); 9529 9530 // Builtin functions cannot be defined. 9531 if (unsigned BuiltinID = FD->getBuiltinID()) { 9532 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9533 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9534 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9535 FD->setInvalidDecl(); 9536 } 9537 } 9538 9539 // The return type of a function definition must be complete 9540 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9541 QualType ResultType = FD->getResultType(); 9542 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9543 !FD->isInvalidDecl() && 9544 RequireCompleteType(FD->getLocation(), ResultType, 9545 diag::err_func_def_incomplete_result)) 9546 FD->setInvalidDecl(); 9547 9548 // GNU warning -Wmissing-prototypes: 9549 // Warn if a global function is defined without a previous 9550 // prototype declaration. This warning is issued even if the 9551 // definition itself provides a prototype. The aim is to detect 9552 // global functions that fail to be declared in header files. 9553 const FunctionDecl *PossibleZeroParamPrototype = 0; 9554 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9555 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9556 9557 if (PossibleZeroParamPrototype) { 9558 // We found a declaration that is not a prototype, 9559 // but that could be a zero-parameter prototype 9560 if (TypeSourceInfo *TI = 9561 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9562 TypeLoc TL = TI->getTypeLoc(); 9563 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9564 Diag(PossibleZeroParamPrototype->getLocation(), 9565 diag::note_declaration_not_a_prototype) 9566 << PossibleZeroParamPrototype 9567 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9568 } 9569 } 9570 } 9571 9572 if (FnBodyScope) 9573 PushDeclContext(FnBodyScope, FD); 9574 9575 // Check the validity of our function parameters 9576 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9577 /*CheckParameterNames=*/true); 9578 9579 // Introduce our parameters into the function scope 9580 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 9581 ParmVarDecl *Param = FD->getParamDecl(p); 9582 Param->setOwningFunction(FD); 9583 9584 // If this has an identifier, add it to the scope stack. 9585 if (Param->getIdentifier() && FnBodyScope) { 9586 CheckShadow(FnBodyScope, Param); 9587 9588 PushOnScopeChains(Param, FnBodyScope); 9589 } 9590 } 9591 9592 // If we had any tags defined in the function prototype, 9593 // introduce them into the function scope. 9594 if (FnBodyScope) { 9595 for (ArrayRef<NamedDecl *>::iterator 9596 I = FD->getDeclsInPrototypeScope().begin(), 9597 E = FD->getDeclsInPrototypeScope().end(); 9598 I != E; ++I) { 9599 NamedDecl *D = *I; 9600 9601 // Some of these decls (like enums) may have been pinned to the translation unit 9602 // for lack of a real context earlier. If so, remove from the translation unit 9603 // and reattach to the current context. 9604 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9605 // Is the decl actually in the context? 9606 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 9607 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 9608 if (*DI == D) { 9609 Context.getTranslationUnitDecl()->removeDecl(D); 9610 break; 9611 } 9612 } 9613 // Either way, reassign the lexical decl context to our FunctionDecl. 9614 D->setLexicalDeclContext(CurContext); 9615 } 9616 9617 // If the decl has a non-null name, make accessible in the current scope. 9618 if (!D->getName().empty()) 9619 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9620 9621 // Similarly, dive into enums and fish their constants out, making them 9622 // accessible in this scope. 9623 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 9624 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 9625 EE = ED->enumerator_end(); EI != EE; ++EI) 9626 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 9627 } 9628 } 9629 } 9630 9631 // Ensure that the function's exception specification is instantiated. 9632 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9633 ResolveExceptionSpec(D->getLocation(), FPT); 9634 9635 // Checking attributes of current function definition 9636 // dllimport attribute. 9637 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9638 if (DA && (!FD->getAttr<DLLExportAttr>())) { 9639 // dllimport attribute cannot be directly applied to definition. 9640 // Microsoft accepts dllimport for functions defined within class scope. 9641 if (!DA->isInherited() && 9642 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9643 Diag(FD->getLocation(), 9644 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9645 << "dllimport"; 9646 FD->setInvalidDecl(); 9647 return D; 9648 } 9649 9650 // Visual C++ appears to not think this is an issue, so only issue 9651 // a warning when Microsoft extensions are disabled. 9652 if (!LangOpts.MicrosoftExt) { 9653 // If a symbol previously declared dllimport is later defined, the 9654 // attribute is ignored in subsequent references, and a warning is 9655 // emitted. 9656 Diag(FD->getLocation(), 9657 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 9658 << FD->getName() << "dllimport"; 9659 } 9660 } 9661 // We want to attach documentation to original Decl (which might be 9662 // a function template). 9663 ActOnDocumentableDecl(D); 9664 return D; 9665 } 9666 9667 /// \brief Given the set of return statements within a function body, 9668 /// compute the variables that are subject to the named return value 9669 /// optimization. 9670 /// 9671 /// Each of the variables that is subject to the named return value 9672 /// optimization will be marked as NRVO variables in the AST, and any 9673 /// return statement that has a marked NRVO variable as its NRVO candidate can 9674 /// use the named return value optimization. 9675 /// 9676 /// This function applies a very simplistic algorithm for NRVO: if every return 9677 /// statement in the function has the same NRVO candidate, that candidate is 9678 /// the NRVO variable. 9679 /// 9680 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9681 /// statements and the lifetimes of the NRVO candidates. We should be able to 9682 /// find a maximal set of NRVO variables. 9683 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9684 ReturnStmt **Returns = Scope->Returns.data(); 9685 9686 const VarDecl *NRVOCandidate = 0; 9687 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9688 if (!Returns[I]->getNRVOCandidate()) 9689 return; 9690 9691 if (!NRVOCandidate) 9692 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9693 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9694 return; 9695 } 9696 9697 if (NRVOCandidate) 9698 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9699 } 9700 9701 bool Sema::canSkipFunctionBody(Decl *D) { 9702 if (!Consumer.shouldSkipFunctionBody(D)) 9703 return false; 9704 9705 if (isa<ObjCMethodDecl>(D)) 9706 return true; 9707 9708 FunctionDecl *FD = 0; 9709 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 9710 FD = FTD->getTemplatedDecl(); 9711 else 9712 FD = cast<FunctionDecl>(D); 9713 9714 // We cannot skip the body of a function (or function template) which is 9715 // constexpr, since we may need to evaluate its body in order to parse the 9716 // rest of the file. 9717 // We cannot skip the body of a function with an undeduced return type, 9718 // because any callers of that function need to know the type. 9719 return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType(); 9720 } 9721 9722 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9723 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9724 FD->setHasSkippedBody(); 9725 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9726 MD->setHasSkippedBody(); 9727 return ActOnFinishFunctionBody(Decl, 0); 9728 } 9729 9730 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9731 return ActOnFinishFunctionBody(D, BodyArg, false); 9732 } 9733 9734 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9735 bool IsInstantiation) { 9736 FunctionDecl *FD = 0; 9737 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 9738 if (FunTmpl) 9739 FD = FunTmpl->getTemplatedDecl(); 9740 else 9741 FD = dyn_cast_or_null<FunctionDecl>(dcl); 9742 9743 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9744 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9745 9746 if (FD) { 9747 FD->setBody(Body); 9748 9749 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9750 !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) { 9751 // If the function has a deduced result type but contains no 'return' 9752 // statements, the result type as written must be exactly 'auto', and 9753 // the deduced result type is 'void'. 9754 if (!FD->getResultType()->getAs<AutoType>()) { 9755 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9756 << FD->getResultType(); 9757 FD->setInvalidDecl(); 9758 } else { 9759 // Substitute 'void' for the 'auto' in the type. 9760 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9761 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc(); 9762 Context.adjustDeducedFunctionResultType( 9763 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9764 } 9765 } 9766 9767 // The only way to be included in UndefinedButUsed is if there is an 9768 // ODR use before the definition. Avoid the expensive map lookup if this 9769 // is the first declaration. 9770 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9771 if (!FD->isExternallyVisible()) 9772 UndefinedButUsed.erase(FD); 9773 else if (FD->isInlined() && 9774 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9775 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9776 UndefinedButUsed.erase(FD); 9777 } 9778 9779 // If the function implicitly returns zero (like 'main') or is naked, 9780 // don't complain about missing return statements. 9781 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9782 WP.disableCheckFallThrough(); 9783 9784 // MSVC permits the use of pure specifier (=0) on function definition, 9785 // defined at class scope, warn about this non-standard construct. 9786 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9787 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9788 9789 if (!FD->isInvalidDecl()) { 9790 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9791 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9792 FD->getResultType(), FD); 9793 9794 // If this is a constructor, we need a vtable. 9795 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9796 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9797 9798 // Try to apply the named return value optimization. We have to check 9799 // if we can do this here because lambdas keep return statements around 9800 // to deduce an implicit return type. 9801 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 9802 !FD->isDependentContext()) 9803 computeNRVO(Body, getCurFunction()); 9804 } 9805 9806 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9807 "Function parsing confused"); 9808 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9809 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9810 MD->setBody(Body); 9811 if (!MD->isInvalidDecl()) { 9812 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9813 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9814 MD->getResultType(), MD); 9815 9816 if (Body) 9817 computeNRVO(Body, getCurFunction()); 9818 } 9819 if (getCurFunction()->ObjCShouldCallSuper) { 9820 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9821 << MD->getSelector().getAsString(); 9822 getCurFunction()->ObjCShouldCallSuper = false; 9823 } 9824 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 9825 const ObjCMethodDecl *InitMethod = 0; 9826 bool isDesignated = 9827 MD->isDesignatedInitializerForTheInterface(&InitMethod); 9828 assert(isDesignated && InitMethod); 9829 (void)isDesignated; 9830 Diag(MD->getLocation(), 9831 diag::warn_objc_designated_init_missing_super_call); 9832 Diag(InitMethod->getLocation(), 9833 diag::note_objc_designated_init_marked_here); 9834 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 9835 } 9836 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 9837 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 9838 getCurFunction()->ObjCWarnForNoInitDelegation = false; 9839 } 9840 } else { 9841 return 0; 9842 } 9843 9844 assert(!getCurFunction()->ObjCShouldCallSuper && 9845 "This should only be set for ObjC methods, which should have been " 9846 "handled in the block above."); 9847 9848 // Verify and clean out per-function state. 9849 if (Body) { 9850 // C++ constructors that have function-try-blocks can't have return 9851 // statements in the handlers of that block. (C++ [except.handle]p14) 9852 // Verify this. 9853 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 9854 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 9855 9856 // Verify that gotos and switch cases don't jump into scopes illegally. 9857 if (getCurFunction()->NeedsScopeChecking() && 9858 !dcl->isInvalidDecl() && 9859 !hasAnyUnrecoverableErrorsInThisFunction() && 9860 !PP.isCodeCompletionEnabled()) 9861 DiagnoseInvalidJumps(Body); 9862 9863 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 9864 if (!Destructor->getParent()->isDependentType()) 9865 CheckDestructor(Destructor); 9866 9867 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9868 Destructor->getParent()); 9869 } 9870 9871 // If any errors have occurred, clear out any temporaries that may have 9872 // been leftover. This ensures that these temporaries won't be picked up for 9873 // deletion in some later function. 9874 if (PP.getDiagnostics().hasErrorOccurred() || 9875 PP.getDiagnostics().getSuppressAllDiagnostics()) { 9876 DiscardCleanupsInEvaluationContext(); 9877 } 9878 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 9879 !isa<FunctionTemplateDecl>(dcl)) { 9880 // Since the body is valid, issue any analysis-based warnings that are 9881 // enabled. 9882 ActivePolicy = &WP; 9883 } 9884 9885 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 9886 (!CheckConstexprFunctionDecl(FD) || 9887 !CheckConstexprFunctionBody(FD, Body))) 9888 FD->setInvalidDecl(); 9889 9890 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 9891 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 9892 assert(MaybeODRUseExprs.empty() && 9893 "Leftover expressions for odr-use checking"); 9894 } 9895 9896 if (!IsInstantiation) 9897 PopDeclContext(); 9898 9899 PopFunctionScopeInfo(ActivePolicy, dcl); 9900 // If any errors have occurred, clear out any temporaries that may have 9901 // been leftover. This ensures that these temporaries won't be picked up for 9902 // deletion in some later function. 9903 if (getDiagnostics().hasErrorOccurred()) { 9904 DiscardCleanupsInEvaluationContext(); 9905 } 9906 9907 return dcl; 9908 } 9909 9910 9911 /// When we finish delayed parsing of an attribute, we must attach it to the 9912 /// relevant Decl. 9913 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 9914 ParsedAttributes &Attrs) { 9915 // Always attach attributes to the underlying decl. 9916 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9917 D = TD->getTemplatedDecl(); 9918 ProcessDeclAttributeList(S, D, Attrs.getList()); 9919 9920 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 9921 if (Method->isStatic()) 9922 checkThisInStaticMemberFunctionAttributes(Method); 9923 } 9924 9925 9926 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 9927 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 9928 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 9929 IdentifierInfo &II, Scope *S) { 9930 // Before we produce a declaration for an implicitly defined 9931 // function, see whether there was a locally-scoped declaration of 9932 // this name as a function or variable. If so, use that 9933 // (non-visible) declaration, and complain about it. 9934 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 9935 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 9936 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 9937 return ExternCPrev; 9938 } 9939 9940 // Extension in C99. Legal in C90, but warn about it. 9941 unsigned diag_id; 9942 if (II.getName().startswith("__builtin_")) 9943 diag_id = diag::warn_builtin_unknown; 9944 else if (getLangOpts().C99) 9945 diag_id = diag::ext_implicit_function_decl; 9946 else 9947 diag_id = diag::warn_implicit_function_decl; 9948 Diag(Loc, diag_id) << &II; 9949 9950 // Because typo correction is expensive, only do it if the implicit 9951 // function declaration is going to be treated as an error. 9952 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 9953 TypoCorrection Corrected; 9954 DeclFilterCCC<FunctionDecl> Validator; 9955 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 9956 LookupOrdinaryName, S, 0, Validator))) 9957 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 9958 /*ErrorRecovery*/false); 9959 } 9960 9961 // Set a Declarator for the implicit definition: int foo(); 9962 const char *Dummy; 9963 AttributeFactory attrFactory; 9964 DeclSpec DS(attrFactory); 9965 unsigned DiagID; 9966 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 9967 (void)Error; // Silence warning. 9968 assert(!Error && "Error setting up implicit decl!"); 9969 SourceLocation NoLoc; 9970 Declarator D(DS, Declarator::BlockContext); 9971 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 9972 /*IsAmbiguous=*/false, 9973 /*RParenLoc=*/NoLoc, 9974 /*ArgInfo=*/0, 9975 /*NumArgs=*/0, 9976 /*EllipsisLoc=*/NoLoc, 9977 /*RParenLoc=*/NoLoc, 9978 /*TypeQuals=*/0, 9979 /*RefQualifierIsLvalueRef=*/true, 9980 /*RefQualifierLoc=*/NoLoc, 9981 /*ConstQualifierLoc=*/NoLoc, 9982 /*VolatileQualifierLoc=*/NoLoc, 9983 /*MutableLoc=*/NoLoc, 9984 EST_None, 9985 /*ESpecLoc=*/NoLoc, 9986 /*Exceptions=*/0, 9987 /*ExceptionRanges=*/0, 9988 /*NumExceptions=*/0, 9989 /*NoexceptExpr=*/0, 9990 Loc, Loc, D), 9991 DS.getAttributes(), 9992 SourceLocation()); 9993 D.SetIdentifier(&II, Loc); 9994 9995 // Insert this function into translation-unit scope. 9996 9997 DeclContext *PrevDC = CurContext; 9998 CurContext = Context.getTranslationUnitDecl(); 9999 10000 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10001 FD->setImplicit(); 10002 10003 CurContext = PrevDC; 10004 10005 AddKnownFunctionAttributes(FD); 10006 10007 return FD; 10008 } 10009 10010 /// \brief Adds any function attributes that we know a priori based on 10011 /// the declaration of this function. 10012 /// 10013 /// These attributes can apply both to implicitly-declared builtins 10014 /// (like __builtin___printf_chk) or to library-declared functions 10015 /// like NSLog or printf. 10016 /// 10017 /// We need to check for duplicate attributes both here and where user-written 10018 /// attributes are applied to declarations. 10019 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10020 if (FD->isInvalidDecl()) 10021 return; 10022 10023 // If this is a built-in function, map its builtin attributes to 10024 // actual attributes. 10025 if (unsigned BuiltinID = FD->getBuiltinID()) { 10026 // Handle printf-formatting attributes. 10027 unsigned FormatIdx; 10028 bool HasVAListArg; 10029 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10030 if (!FD->getAttr<FormatAttr>()) { 10031 const char *fmt = "printf"; 10032 unsigned int NumParams = FD->getNumParams(); 10033 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10034 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10035 fmt = "NSString"; 10036 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10037 &Context.Idents.get(fmt), 10038 FormatIdx+1, 10039 HasVAListArg ? 0 : FormatIdx+2)); 10040 } 10041 } 10042 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10043 HasVAListArg)) { 10044 if (!FD->getAttr<FormatAttr>()) 10045 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10046 &Context.Idents.get("scanf"), 10047 FormatIdx+1, 10048 HasVAListArg ? 0 : FormatIdx+2)); 10049 } 10050 10051 // Mark const if we don't care about errno and that is the only 10052 // thing preventing the function from being const. This allows 10053 // IRgen to use LLVM intrinsics for such functions. 10054 if (!getLangOpts().MathErrno && 10055 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10056 if (!FD->getAttr<ConstAttr>()) 10057 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 10058 } 10059 10060 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10061 !FD->getAttr<ReturnsTwiceAttr>()) 10062 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 10063 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 10064 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 10065 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 10066 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 10067 } 10068 10069 IdentifierInfo *Name = FD->getIdentifier(); 10070 if (!Name) 10071 return; 10072 if ((!getLangOpts().CPlusPlus && 10073 FD->getDeclContext()->isTranslationUnit()) || 10074 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10075 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10076 LinkageSpecDecl::lang_c)) { 10077 // Okay: this could be a libc/libm/Objective-C function we know 10078 // about. 10079 } else 10080 return; 10081 10082 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10083 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10084 // target-specific builtins, perhaps? 10085 if (!FD->getAttr<FormatAttr>()) 10086 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 10087 &Context.Idents.get("printf"), 2, 10088 Name->isStr("vasprintf") ? 0 : 3)); 10089 } 10090 10091 if (Name->isStr("__CFStringMakeConstantString")) { 10092 // We already have a __builtin___CFStringMakeConstantString, 10093 // but builds that use -fno-constant-cfstrings don't go through that. 10094 if (!FD->getAttr<FormatArgAttr>()) 10095 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 10096 } 10097 } 10098 10099 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10100 TypeSourceInfo *TInfo) { 10101 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10102 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10103 10104 if (!TInfo) { 10105 assert(D.isInvalidType() && "no declarator info for valid type"); 10106 TInfo = Context.getTrivialTypeSourceInfo(T); 10107 } 10108 10109 // Scope manipulation handled by caller. 10110 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10111 D.getLocStart(), 10112 D.getIdentifierLoc(), 10113 D.getIdentifier(), 10114 TInfo); 10115 10116 // Bail out immediately if we have an invalid declaration. 10117 if (D.isInvalidType()) { 10118 NewTD->setInvalidDecl(); 10119 return NewTD; 10120 } 10121 10122 if (D.getDeclSpec().isModulePrivateSpecified()) { 10123 if (CurContext->isFunctionOrMethod()) 10124 Diag(NewTD->getLocation(), diag::err_module_private_local) 10125 << 2 << NewTD->getDeclName() 10126 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10127 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10128 else 10129 NewTD->setModulePrivate(); 10130 } 10131 10132 // C++ [dcl.typedef]p8: 10133 // If the typedef declaration defines an unnamed class (or 10134 // enum), the first typedef-name declared by the declaration 10135 // to be that class type (or enum type) is used to denote the 10136 // class type (or enum type) for linkage purposes only. 10137 // We need to check whether the type was declared in the declaration. 10138 switch (D.getDeclSpec().getTypeSpecType()) { 10139 case TST_enum: 10140 case TST_struct: 10141 case TST_interface: 10142 case TST_union: 10143 case TST_class: { 10144 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10145 10146 // Do nothing if the tag is not anonymous or already has an 10147 // associated typedef (from an earlier typedef in this decl group). 10148 if (tagFromDeclSpec->getIdentifier()) break; 10149 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10150 10151 // A well-formed anonymous tag must always be a TUK_Definition. 10152 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10153 10154 // The type must match the tag exactly; no qualifiers allowed. 10155 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10156 break; 10157 10158 // Otherwise, set this is the anon-decl typedef for the tag. 10159 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10160 break; 10161 } 10162 10163 default: 10164 break; 10165 } 10166 10167 return NewTD; 10168 } 10169 10170 10171 /// \brief Check that this is a valid underlying type for an enum declaration. 10172 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10173 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10174 QualType T = TI->getType(); 10175 10176 if (T->isDependentType()) 10177 return false; 10178 10179 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10180 if (BT->isInteger()) 10181 return false; 10182 10183 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10184 return true; 10185 } 10186 10187 /// Check whether this is a valid redeclaration of a previous enumeration. 10188 /// \return true if the redeclaration was invalid. 10189 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10190 QualType EnumUnderlyingTy, 10191 const EnumDecl *Prev) { 10192 bool IsFixed = !EnumUnderlyingTy.isNull(); 10193 10194 if (IsScoped != Prev->isScoped()) { 10195 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10196 << Prev->isScoped(); 10197 Diag(Prev->getLocation(), diag::note_previous_use); 10198 return true; 10199 } 10200 10201 if (IsFixed && Prev->isFixed()) { 10202 if (!EnumUnderlyingTy->isDependentType() && 10203 !Prev->getIntegerType()->isDependentType() && 10204 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10205 Prev->getIntegerType())) { 10206 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10207 << EnumUnderlyingTy << Prev->getIntegerType(); 10208 Diag(Prev->getLocation(), diag::note_previous_use); 10209 return true; 10210 } 10211 } else if (IsFixed != Prev->isFixed()) { 10212 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10213 << Prev->isFixed(); 10214 Diag(Prev->getLocation(), diag::note_previous_use); 10215 return true; 10216 } 10217 10218 return false; 10219 } 10220 10221 /// \brief Get diagnostic %select index for tag kind for 10222 /// redeclaration diagnostic message. 10223 /// WARNING: Indexes apply to particular diagnostics only! 10224 /// 10225 /// \returns diagnostic %select index. 10226 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10227 switch (Tag) { 10228 case TTK_Struct: return 0; 10229 case TTK_Interface: return 1; 10230 case TTK_Class: return 2; 10231 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10232 } 10233 } 10234 10235 /// \brief Determine if tag kind is a class-key compatible with 10236 /// class for redeclaration (class, struct, or __interface). 10237 /// 10238 /// \returns true iff the tag kind is compatible. 10239 static bool isClassCompatTagKind(TagTypeKind Tag) 10240 { 10241 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10242 } 10243 10244 /// \brief Determine whether a tag with a given kind is acceptable 10245 /// as a redeclaration of the given tag declaration. 10246 /// 10247 /// \returns true if the new tag kind is acceptable, false otherwise. 10248 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10249 TagTypeKind NewTag, bool isDefinition, 10250 SourceLocation NewTagLoc, 10251 const IdentifierInfo &Name) { 10252 // C++ [dcl.type.elab]p3: 10253 // The class-key or enum keyword present in the 10254 // elaborated-type-specifier shall agree in kind with the 10255 // declaration to which the name in the elaborated-type-specifier 10256 // refers. This rule also applies to the form of 10257 // elaborated-type-specifier that declares a class-name or 10258 // friend class since it can be construed as referring to the 10259 // definition of the class. Thus, in any 10260 // elaborated-type-specifier, the enum keyword shall be used to 10261 // refer to an enumeration (7.2), the union class-key shall be 10262 // used to refer to a union (clause 9), and either the class or 10263 // struct class-key shall be used to refer to a class (clause 9) 10264 // declared using the class or struct class-key. 10265 TagTypeKind OldTag = Previous->getTagKind(); 10266 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10267 if (OldTag == NewTag) 10268 return true; 10269 10270 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10271 // Warn about the struct/class tag mismatch. 10272 bool isTemplate = false; 10273 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10274 isTemplate = Record->getDescribedClassTemplate(); 10275 10276 if (!ActiveTemplateInstantiations.empty()) { 10277 // In a template instantiation, do not offer fix-its for tag mismatches 10278 // since they usually mess up the template instead of fixing the problem. 10279 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10280 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10281 << getRedeclDiagFromTagKind(OldTag); 10282 return true; 10283 } 10284 10285 if (isDefinition) { 10286 // On definitions, check previous tags and issue a fix-it for each 10287 // one that doesn't match the current tag. 10288 if (Previous->getDefinition()) { 10289 // Don't suggest fix-its for redefinitions. 10290 return true; 10291 } 10292 10293 bool previousMismatch = false; 10294 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 10295 E(Previous->redecls_end()); I != E; ++I) { 10296 if (I->getTagKind() != NewTag) { 10297 if (!previousMismatch) { 10298 previousMismatch = true; 10299 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10300 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10301 << getRedeclDiagFromTagKind(I->getTagKind()); 10302 } 10303 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10304 << getRedeclDiagFromTagKind(NewTag) 10305 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10306 TypeWithKeyword::getTagTypeKindName(NewTag)); 10307 } 10308 } 10309 return true; 10310 } 10311 10312 // Check for a previous definition. If current tag and definition 10313 // are same type, do nothing. If no definition, but disagree with 10314 // with previous tag type, give a warning, but no fix-it. 10315 const TagDecl *Redecl = Previous->getDefinition() ? 10316 Previous->getDefinition() : Previous; 10317 if (Redecl->getTagKind() == NewTag) { 10318 return true; 10319 } 10320 10321 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10322 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10323 << getRedeclDiagFromTagKind(OldTag); 10324 Diag(Redecl->getLocation(), diag::note_previous_use); 10325 10326 // If there is a previous definition, suggest a fix-it. 10327 if (Previous->getDefinition()) { 10328 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10329 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10330 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10331 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10332 } 10333 10334 return true; 10335 } 10336 return false; 10337 } 10338 10339 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10340 /// former case, Name will be non-null. In the later case, Name will be null. 10341 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10342 /// reference/declaration/definition of a tag. 10343 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10344 SourceLocation KWLoc, CXXScopeSpec &SS, 10345 IdentifierInfo *Name, SourceLocation NameLoc, 10346 AttributeList *Attr, AccessSpecifier AS, 10347 SourceLocation ModulePrivateLoc, 10348 MultiTemplateParamsArg TemplateParameterLists, 10349 bool &OwnedDecl, bool &IsDependent, 10350 SourceLocation ScopedEnumKWLoc, 10351 bool ScopedEnumUsesClassTag, 10352 TypeResult UnderlyingType) { 10353 // If this is not a definition, it must have a name. 10354 IdentifierInfo *OrigName = Name; 10355 assert((Name != 0 || TUK == TUK_Definition) && 10356 "Nameless record must be a definition!"); 10357 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10358 10359 OwnedDecl = false; 10360 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10361 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10362 10363 // FIXME: Check explicit specializations more carefully. 10364 bool isExplicitSpecialization = false; 10365 bool Invalid = false; 10366 10367 // We only need to do this matching if we have template parameters 10368 // or a scope specifier, which also conveniently avoids this work 10369 // for non-C++ cases. 10370 if (TemplateParameterLists.size() > 0 || 10371 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10372 if (TemplateParameterList *TemplateParams = 10373 MatchTemplateParametersToScopeSpecifier( 10374 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10375 isExplicitSpecialization, Invalid)) { 10376 if (Kind == TTK_Enum) { 10377 Diag(KWLoc, diag::err_enum_template); 10378 return 0; 10379 } 10380 10381 if (TemplateParams->size() > 0) { 10382 // This is a declaration or definition of a class template (which may 10383 // be a member of another template). 10384 10385 if (Invalid) 10386 return 0; 10387 10388 OwnedDecl = false; 10389 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10390 SS, Name, NameLoc, Attr, 10391 TemplateParams, AS, 10392 ModulePrivateLoc, 10393 TemplateParameterLists.size()-1, 10394 TemplateParameterLists.data()); 10395 return Result.get(); 10396 } else { 10397 // The "template<>" header is extraneous. 10398 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10399 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10400 isExplicitSpecialization = true; 10401 } 10402 } 10403 } 10404 10405 // Figure out the underlying type if this a enum declaration. We need to do 10406 // this early, because it's needed to detect if this is an incompatible 10407 // redeclaration. 10408 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10409 10410 if (Kind == TTK_Enum) { 10411 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10412 // No underlying type explicitly specified, or we failed to parse the 10413 // type, default to int. 10414 EnumUnderlying = Context.IntTy.getTypePtr(); 10415 else if (UnderlyingType.get()) { 10416 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10417 // integral type; any cv-qualification is ignored. 10418 TypeSourceInfo *TI = 0; 10419 GetTypeFromParser(UnderlyingType.get(), &TI); 10420 EnumUnderlying = TI; 10421 10422 if (CheckEnumUnderlyingType(TI)) 10423 // Recover by falling back to int. 10424 EnumUnderlying = Context.IntTy.getTypePtr(); 10425 10426 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10427 UPPC_FixedUnderlyingType)) 10428 EnumUnderlying = Context.IntTy.getTypePtr(); 10429 10430 } else if (getLangOpts().MicrosoftMode) 10431 // Microsoft enums are always of int type. 10432 EnumUnderlying = Context.IntTy.getTypePtr(); 10433 } 10434 10435 DeclContext *SearchDC = CurContext; 10436 DeclContext *DC = CurContext; 10437 bool isStdBadAlloc = false; 10438 10439 RedeclarationKind Redecl = ForRedeclaration; 10440 if (TUK == TUK_Friend || TUK == TUK_Reference) 10441 Redecl = NotForRedeclaration; 10442 10443 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10444 bool FriendSawTagOutsideEnclosingNamespace = false; 10445 if (Name && SS.isNotEmpty()) { 10446 // We have a nested-name tag ('struct foo::bar'). 10447 10448 // Check for invalid 'foo::'. 10449 if (SS.isInvalid()) { 10450 Name = 0; 10451 goto CreateNewDecl; 10452 } 10453 10454 // If this is a friend or a reference to a class in a dependent 10455 // context, don't try to make a decl for it. 10456 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10457 DC = computeDeclContext(SS, false); 10458 if (!DC) { 10459 IsDependent = true; 10460 return 0; 10461 } 10462 } else { 10463 DC = computeDeclContext(SS, true); 10464 if (!DC) { 10465 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10466 << SS.getRange(); 10467 return 0; 10468 } 10469 } 10470 10471 if (RequireCompleteDeclContext(SS, DC)) 10472 return 0; 10473 10474 SearchDC = DC; 10475 // Look-up name inside 'foo::'. 10476 LookupQualifiedName(Previous, DC); 10477 10478 if (Previous.isAmbiguous()) 10479 return 0; 10480 10481 if (Previous.empty()) { 10482 // Name lookup did not find anything. However, if the 10483 // nested-name-specifier refers to the current instantiation, 10484 // and that current instantiation has any dependent base 10485 // classes, we might find something at instantiation time: treat 10486 // this as a dependent elaborated-type-specifier. 10487 // But this only makes any sense for reference-like lookups. 10488 if (Previous.wasNotFoundInCurrentInstantiation() && 10489 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10490 IsDependent = true; 10491 return 0; 10492 } 10493 10494 // A tag 'foo::bar' must already exist. 10495 Diag(NameLoc, diag::err_not_tag_in_scope) 10496 << Kind << Name << DC << SS.getRange(); 10497 Name = 0; 10498 Invalid = true; 10499 goto CreateNewDecl; 10500 } 10501 } else if (Name) { 10502 // If this is a named struct, check to see if there was a previous forward 10503 // declaration or definition. 10504 // FIXME: We're looking into outer scopes here, even when we 10505 // shouldn't be. Doing so can result in ambiguities that we 10506 // shouldn't be diagnosing. 10507 LookupName(Previous, S); 10508 10509 // When declaring or defining a tag, ignore ambiguities introduced 10510 // by types using'ed into this scope. 10511 if (Previous.isAmbiguous() && 10512 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10513 LookupResult::Filter F = Previous.makeFilter(); 10514 while (F.hasNext()) { 10515 NamedDecl *ND = F.next(); 10516 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10517 F.erase(); 10518 } 10519 F.done(); 10520 } 10521 10522 // C++11 [namespace.memdef]p3: 10523 // If the name in a friend declaration is neither qualified nor 10524 // a template-id and the declaration is a function or an 10525 // elaborated-type-specifier, the lookup to determine whether 10526 // the entity has been previously declared shall not consider 10527 // any scopes outside the innermost enclosing namespace. 10528 // 10529 // Does it matter that this should be by scope instead of by 10530 // semantic context? 10531 if (!Previous.empty() && TUK == TUK_Friend) { 10532 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10533 LookupResult::Filter F = Previous.makeFilter(); 10534 while (F.hasNext()) { 10535 NamedDecl *ND = F.next(); 10536 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10537 if (DC->isFileContext() && 10538 !EnclosingNS->Encloses(ND->getDeclContext())) { 10539 F.erase(); 10540 FriendSawTagOutsideEnclosingNamespace = true; 10541 } 10542 } 10543 F.done(); 10544 } 10545 10546 // Note: there used to be some attempt at recovery here. 10547 if (Previous.isAmbiguous()) 10548 return 0; 10549 10550 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10551 // FIXME: This makes sure that we ignore the contexts associated 10552 // with C structs, unions, and enums when looking for a matching 10553 // tag declaration or definition. See the similar lookup tweak 10554 // in Sema::LookupName; is there a better way to deal with this? 10555 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10556 SearchDC = SearchDC->getParent(); 10557 } 10558 } else if (S->isFunctionPrototypeScope()) { 10559 // If this is an enum declaration in function prototype scope, set its 10560 // initial context to the translation unit. 10561 // FIXME: [citation needed] 10562 SearchDC = Context.getTranslationUnitDecl(); 10563 } 10564 10565 if (Previous.isSingleResult() && 10566 Previous.getFoundDecl()->isTemplateParameter()) { 10567 // Maybe we will complain about the shadowed template parameter. 10568 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10569 // Just pretend that we didn't see the previous declaration. 10570 Previous.clear(); 10571 } 10572 10573 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10574 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10575 // This is a declaration of or a reference to "std::bad_alloc". 10576 isStdBadAlloc = true; 10577 10578 if (Previous.empty() && StdBadAlloc) { 10579 // std::bad_alloc has been implicitly declared (but made invisible to 10580 // name lookup). Fill in this implicit declaration as the previous 10581 // declaration, so that the declarations get chained appropriately. 10582 Previous.addDecl(getStdBadAlloc()); 10583 } 10584 } 10585 10586 // If we didn't find a previous declaration, and this is a reference 10587 // (or friend reference), move to the correct scope. In C++, we 10588 // also need to do a redeclaration lookup there, just in case 10589 // there's a shadow friend decl. 10590 if (Name && Previous.empty() && 10591 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10592 if (Invalid) goto CreateNewDecl; 10593 assert(SS.isEmpty()); 10594 10595 if (TUK == TUK_Reference) { 10596 // C++ [basic.scope.pdecl]p5: 10597 // -- for an elaborated-type-specifier of the form 10598 // 10599 // class-key identifier 10600 // 10601 // if the elaborated-type-specifier is used in the 10602 // decl-specifier-seq or parameter-declaration-clause of a 10603 // function defined in namespace scope, the identifier is 10604 // declared as a class-name in the namespace that contains 10605 // the declaration; otherwise, except as a friend 10606 // declaration, the identifier is declared in the smallest 10607 // non-class, non-function-prototype scope that contains the 10608 // declaration. 10609 // 10610 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10611 // C structs and unions. 10612 // 10613 // It is an error in C++ to declare (rather than define) an enum 10614 // type, including via an elaborated type specifier. We'll 10615 // diagnose that later; for now, declare the enum in the same 10616 // scope as we would have picked for any other tag type. 10617 // 10618 // GNU C also supports this behavior as part of its incomplete 10619 // enum types extension, while GNU C++ does not. 10620 // 10621 // Find the context where we'll be declaring the tag. 10622 // FIXME: We would like to maintain the current DeclContext as the 10623 // lexical context, 10624 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10625 SearchDC = SearchDC->getParent(); 10626 10627 // Find the scope where we'll be declaring the tag. 10628 while (S->isClassScope() || 10629 (getLangOpts().CPlusPlus && 10630 S->isFunctionPrototypeScope()) || 10631 ((S->getFlags() & Scope::DeclScope) == 0) || 10632 (S->getEntity() && S->getEntity()->isTransparentContext())) 10633 S = S->getParent(); 10634 } else { 10635 assert(TUK == TUK_Friend); 10636 // C++ [namespace.memdef]p3: 10637 // If a friend declaration in a non-local class first declares a 10638 // class or function, the friend class or function is a member of 10639 // the innermost enclosing namespace. 10640 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10641 } 10642 10643 // In C++, we need to do a redeclaration lookup to properly 10644 // diagnose some problems. 10645 if (getLangOpts().CPlusPlus) { 10646 Previous.setRedeclarationKind(ForRedeclaration); 10647 LookupQualifiedName(Previous, SearchDC); 10648 } 10649 } 10650 10651 if (!Previous.empty()) { 10652 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 10653 10654 // It's okay to have a tag decl in the same scope as a typedef 10655 // which hides a tag decl in the same scope. Finding this 10656 // insanity with a redeclaration lookup can only actually happen 10657 // in C++. 10658 // 10659 // This is also okay for elaborated-type-specifiers, which is 10660 // technically forbidden by the current standard but which is 10661 // okay according to the likely resolution of an open issue; 10662 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10663 if (getLangOpts().CPlusPlus) { 10664 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10665 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10666 TagDecl *Tag = TT->getDecl(); 10667 if (Tag->getDeclName() == Name && 10668 Tag->getDeclContext()->getRedeclContext() 10669 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10670 PrevDecl = Tag; 10671 Previous.clear(); 10672 Previous.addDecl(Tag); 10673 Previous.resolveKind(); 10674 } 10675 } 10676 } 10677 } 10678 10679 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10680 // If this is a use of a previous tag, or if the tag is already declared 10681 // in the same scope (so that the definition/declaration completes or 10682 // rementions the tag), reuse the decl. 10683 if (TUK == TUK_Reference || TUK == TUK_Friend || 10684 isDeclInScope(PrevDecl, SearchDC, S, 10685 SS.isNotEmpty() || isExplicitSpecialization)) { 10686 // Make sure that this wasn't declared as an enum and now used as a 10687 // struct or something similar. 10688 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10689 TUK == TUK_Definition, KWLoc, 10690 *Name)) { 10691 bool SafeToContinue 10692 = (PrevTagDecl->getTagKind() != TTK_Enum && 10693 Kind != TTK_Enum); 10694 if (SafeToContinue) 10695 Diag(KWLoc, diag::err_use_with_wrong_tag) 10696 << Name 10697 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10698 PrevTagDecl->getKindName()); 10699 else 10700 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10701 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10702 10703 if (SafeToContinue) 10704 Kind = PrevTagDecl->getTagKind(); 10705 else { 10706 // Recover by making this an anonymous redefinition. 10707 Name = 0; 10708 Previous.clear(); 10709 Invalid = true; 10710 } 10711 } 10712 10713 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10714 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10715 10716 // If this is an elaborated-type-specifier for a scoped enumeration, 10717 // the 'class' keyword is not necessary and not permitted. 10718 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10719 if (ScopedEnum) 10720 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10721 << PrevEnum->isScoped() 10722 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10723 return PrevTagDecl; 10724 } 10725 10726 QualType EnumUnderlyingTy; 10727 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10728 EnumUnderlyingTy = TI->getType(); 10729 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10730 EnumUnderlyingTy = QualType(T, 0); 10731 10732 // All conflicts with previous declarations are recovered by 10733 // returning the previous declaration, unless this is a definition, 10734 // in which case we want the caller to bail out. 10735 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10736 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10737 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10738 } 10739 10740 // C++11 [class.mem]p1: 10741 // A member shall not be declared twice in the member-specification, 10742 // except that a nested class or member class template can be declared 10743 // and then later defined. 10744 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10745 S->isDeclScope(PrevDecl)) { 10746 Diag(NameLoc, diag::ext_member_redeclared); 10747 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10748 } 10749 10750 if (!Invalid) { 10751 // If this is a use, just return the declaration we found. 10752 10753 // FIXME: In the future, return a variant or some other clue 10754 // for the consumer of this Decl to know it doesn't own it. 10755 // For our current ASTs this shouldn't be a problem, but will 10756 // need to be changed with DeclGroups. 10757 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10758 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10759 return PrevTagDecl; 10760 10761 // Diagnose attempts to redefine a tag. 10762 if (TUK == TUK_Definition) { 10763 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10764 // If we're defining a specialization and the previous definition 10765 // is from an implicit instantiation, don't emit an error 10766 // here; we'll catch this in the general case below. 10767 bool IsExplicitSpecializationAfterInstantiation = false; 10768 if (isExplicitSpecialization) { 10769 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10770 IsExplicitSpecializationAfterInstantiation = 10771 RD->getTemplateSpecializationKind() != 10772 TSK_ExplicitSpecialization; 10773 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10774 IsExplicitSpecializationAfterInstantiation = 10775 ED->getTemplateSpecializationKind() != 10776 TSK_ExplicitSpecialization; 10777 } 10778 10779 if (!IsExplicitSpecializationAfterInstantiation) { 10780 // A redeclaration in function prototype scope in C isn't 10781 // visible elsewhere, so merely issue a warning. 10782 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10783 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10784 else 10785 Diag(NameLoc, diag::err_redefinition) << Name; 10786 Diag(Def->getLocation(), diag::note_previous_definition); 10787 // If this is a redefinition, recover by making this 10788 // struct be anonymous, which will make any later 10789 // references get the previous definition. 10790 Name = 0; 10791 Previous.clear(); 10792 Invalid = true; 10793 } 10794 } else { 10795 // If the type is currently being defined, complain 10796 // about a nested redefinition. 10797 const TagType *Tag 10798 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10799 if (Tag->isBeingDefined()) { 10800 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10801 Diag(PrevTagDecl->getLocation(), 10802 diag::note_previous_definition); 10803 Name = 0; 10804 Previous.clear(); 10805 Invalid = true; 10806 } 10807 } 10808 10809 // Okay, this is definition of a previously declared or referenced 10810 // tag PrevDecl. We're going to create a new Decl for it. 10811 } 10812 } 10813 // If we get here we have (another) forward declaration or we 10814 // have a definition. Just create a new decl. 10815 10816 } else { 10817 // If we get here, this is a definition of a new tag type in a nested 10818 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 10819 // new decl/type. We set PrevDecl to NULL so that the entities 10820 // have distinct types. 10821 Previous.clear(); 10822 } 10823 // If we get here, we're going to create a new Decl. If PrevDecl 10824 // is non-NULL, it's a definition of the tag declared by 10825 // PrevDecl. If it's NULL, we have a new definition. 10826 10827 10828 // Otherwise, PrevDecl is not a tag, but was found with tag 10829 // lookup. This is only actually possible in C++, where a few 10830 // things like templates still live in the tag namespace. 10831 } else { 10832 // Use a better diagnostic if an elaborated-type-specifier 10833 // found the wrong kind of type on the first 10834 // (non-redeclaration) lookup. 10835 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 10836 !Previous.isForRedeclaration()) { 10837 unsigned Kind = 0; 10838 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10839 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10840 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10841 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 10842 Diag(PrevDecl->getLocation(), diag::note_declared_at); 10843 Invalid = true; 10844 10845 // Otherwise, only diagnose if the declaration is in scope. 10846 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 10847 SS.isNotEmpty() || isExplicitSpecialization)) { 10848 // do nothing 10849 10850 // Diagnose implicit declarations introduced by elaborated types. 10851 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 10852 unsigned Kind = 0; 10853 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10854 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10855 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10856 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 10857 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10858 Invalid = true; 10859 10860 // Otherwise it's a declaration. Call out a particularly common 10861 // case here. 10862 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10863 unsigned Kind = 0; 10864 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 10865 Diag(NameLoc, diag::err_tag_definition_of_typedef) 10866 << Name << Kind << TND->getUnderlyingType(); 10867 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10868 Invalid = true; 10869 10870 // Otherwise, diagnose. 10871 } else { 10872 // The tag name clashes with something else in the target scope, 10873 // issue an error and recover by making this tag be anonymous. 10874 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 10875 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10876 Name = 0; 10877 Invalid = true; 10878 } 10879 10880 // The existing declaration isn't relevant to us; we're in a 10881 // new scope, so clear out the previous declaration. 10882 Previous.clear(); 10883 } 10884 } 10885 10886 CreateNewDecl: 10887 10888 TagDecl *PrevDecl = 0; 10889 if (Previous.isSingleResult()) 10890 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 10891 10892 // If there is an identifier, use the location of the identifier as the 10893 // location of the decl, otherwise use the location of the struct/union 10894 // keyword. 10895 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 10896 10897 // Otherwise, create a new declaration. If there is a previous 10898 // declaration of the same entity, the two will be linked via 10899 // PrevDecl. 10900 TagDecl *New; 10901 10902 bool IsForwardReference = false; 10903 if (Kind == TTK_Enum) { 10904 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10905 // enum X { A, B, C } D; D should chain to X. 10906 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 10907 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 10908 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 10909 // If this is an undefined enum, warn. 10910 if (TUK != TUK_Definition && !Invalid) { 10911 TagDecl *Def; 10912 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 10913 cast<EnumDecl>(New)->isFixed()) { 10914 // C++0x: 7.2p2: opaque-enum-declaration. 10915 // Conflicts are diagnosed above. Do nothing. 10916 } 10917 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 10918 Diag(Loc, diag::ext_forward_ref_enum_def) 10919 << New; 10920 Diag(Def->getLocation(), diag::note_previous_definition); 10921 } else { 10922 unsigned DiagID = diag::ext_forward_ref_enum; 10923 if (getLangOpts().MicrosoftMode) 10924 DiagID = diag::ext_ms_forward_ref_enum; 10925 else if (getLangOpts().CPlusPlus) 10926 DiagID = diag::err_forward_ref_enum; 10927 Diag(Loc, DiagID); 10928 10929 // If this is a forward-declared reference to an enumeration, make a 10930 // note of it; we won't actually be introducing the declaration into 10931 // the declaration context. 10932 if (TUK == TUK_Reference) 10933 IsForwardReference = true; 10934 } 10935 } 10936 10937 if (EnumUnderlying) { 10938 EnumDecl *ED = cast<EnumDecl>(New); 10939 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10940 ED->setIntegerTypeSourceInfo(TI); 10941 else 10942 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 10943 ED->setPromotionType(ED->getIntegerType()); 10944 } 10945 10946 } else { 10947 // struct/union/class 10948 10949 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10950 // struct X { int A; } D; D should chain to X. 10951 if (getLangOpts().CPlusPlus) { 10952 // FIXME: Look for a way to use RecordDecl for simple structs. 10953 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10954 cast_or_null<CXXRecordDecl>(PrevDecl)); 10955 10956 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 10957 StdBadAlloc = cast<CXXRecordDecl>(New); 10958 } else 10959 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10960 cast_or_null<RecordDecl>(PrevDecl)); 10961 } 10962 10963 // Maybe add qualifier info. 10964 if (SS.isNotEmpty()) { 10965 if (SS.isSet()) { 10966 // If this is either a declaration or a definition, check the 10967 // nested-name-specifier against the current context. We don't do this 10968 // for explicit specializations, because they have similar checking 10969 // (with more specific diagnostics) in the call to 10970 // CheckMemberSpecialization, below. 10971 if (!isExplicitSpecialization && 10972 (TUK == TUK_Definition || TUK == TUK_Declaration) && 10973 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 10974 Invalid = true; 10975 10976 New->setQualifierInfo(SS.getWithLocInContext(Context)); 10977 if (TemplateParameterLists.size() > 0) { 10978 New->setTemplateParameterListsInfo(Context, 10979 TemplateParameterLists.size(), 10980 TemplateParameterLists.data()); 10981 } 10982 } 10983 else 10984 Invalid = true; 10985 } 10986 10987 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 10988 // Add alignment attributes if necessary; these attributes are checked when 10989 // the ASTContext lays out the structure. 10990 // 10991 // It is important for implementing the correct semantics that this 10992 // happen here (in act on tag decl). The #pragma pack stack is 10993 // maintained as a result of parser callbacks which can occur at 10994 // many points during the parsing of a struct declaration (because 10995 // the #pragma tokens are effectively skipped over during the 10996 // parsing of the struct). 10997 if (TUK == TUK_Definition) { 10998 AddAlignmentAttributesForRecord(RD); 10999 AddMsStructLayoutForRecord(RD); 11000 } 11001 } 11002 11003 if (ModulePrivateLoc.isValid()) { 11004 if (isExplicitSpecialization) 11005 Diag(New->getLocation(), diag::err_module_private_specialization) 11006 << 2 11007 << FixItHint::CreateRemoval(ModulePrivateLoc); 11008 // __module_private__ does not apply to local classes. However, we only 11009 // diagnose this as an error when the declaration specifiers are 11010 // freestanding. Here, we just ignore the __module_private__. 11011 else if (!SearchDC->isFunctionOrMethod()) 11012 New->setModulePrivate(); 11013 } 11014 11015 // If this is a specialization of a member class (of a class template), 11016 // check the specialization. 11017 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11018 Invalid = true; 11019 11020 if (Invalid) 11021 New->setInvalidDecl(); 11022 11023 if (Attr) 11024 ProcessDeclAttributeList(S, New, Attr); 11025 11026 // If we're declaring or defining a tag in function prototype scope 11027 // in C, note that this type can only be used within the function. 11028 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 11029 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11030 11031 // Set the lexical context. If the tag has a C++ scope specifier, the 11032 // lexical context will be different from the semantic context. 11033 New->setLexicalDeclContext(CurContext); 11034 11035 // Mark this as a friend decl if applicable. 11036 // In Microsoft mode, a friend declaration also acts as a forward 11037 // declaration so we always pass true to setObjectOfFriendDecl to make 11038 // the tag name visible. 11039 if (TUK == TUK_Friend) 11040 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11041 getLangOpts().MicrosoftExt); 11042 11043 // Set the access specifier. 11044 if (!Invalid && SearchDC->isRecord()) 11045 SetMemberAccessSpecifier(New, PrevDecl, AS); 11046 11047 if (TUK == TUK_Definition) 11048 New->startDefinition(); 11049 11050 // If this has an identifier, add it to the scope stack. 11051 if (TUK == TUK_Friend) { 11052 // We might be replacing an existing declaration in the lookup tables; 11053 // if so, borrow its access specifier. 11054 if (PrevDecl) 11055 New->setAccess(PrevDecl->getAccess()); 11056 11057 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11058 DC->makeDeclVisibleInContext(New); 11059 if (Name) // can be null along some error paths 11060 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11061 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11062 } else if (Name) { 11063 S = getNonFieldDeclScope(S); 11064 PushOnScopeChains(New, S, !IsForwardReference); 11065 if (IsForwardReference) 11066 SearchDC->makeDeclVisibleInContext(New); 11067 11068 } else { 11069 CurContext->addDecl(New); 11070 } 11071 11072 // If this is the C FILE type, notify the AST context. 11073 if (IdentifierInfo *II = New->getIdentifier()) 11074 if (!New->isInvalidDecl() && 11075 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11076 II->isStr("FILE")) 11077 Context.setFILEDecl(New); 11078 11079 // If we were in function prototype scope (and not in C++ mode), add this 11080 // tag to the list of decls to inject into the function definition scope. 11081 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 11082 InFunctionDeclarator && Name) 11083 DeclsInPrototypeScope.push_back(New); 11084 11085 if (PrevDecl) 11086 mergeDeclAttributes(New, PrevDecl); 11087 11088 // If there's a #pragma GCC visibility in scope, set the visibility of this 11089 // record. 11090 AddPushedVisibilityAttribute(New); 11091 11092 OwnedDecl = true; 11093 // In C++, don't return an invalid declaration. We can't recover well from 11094 // the cases where we make the type anonymous. 11095 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11096 } 11097 11098 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11099 AdjustDeclIfTemplate(TagD); 11100 TagDecl *Tag = cast<TagDecl>(TagD); 11101 11102 // Enter the tag context. 11103 PushDeclContext(S, Tag); 11104 11105 ActOnDocumentableDecl(TagD); 11106 11107 // If there's a #pragma GCC visibility in scope, set the visibility of this 11108 // record. 11109 AddPushedVisibilityAttribute(Tag); 11110 } 11111 11112 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11113 assert(isa<ObjCContainerDecl>(IDecl) && 11114 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11115 DeclContext *OCD = cast<DeclContext>(IDecl); 11116 assert(getContainingDC(OCD) == CurContext && 11117 "The next DeclContext should be lexically contained in the current one."); 11118 CurContext = OCD; 11119 return IDecl; 11120 } 11121 11122 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11123 SourceLocation FinalLoc, 11124 bool IsFinalSpelledSealed, 11125 SourceLocation LBraceLoc) { 11126 AdjustDeclIfTemplate(TagD); 11127 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11128 11129 FieldCollector->StartClass(); 11130 11131 if (!Record->getIdentifier()) 11132 return; 11133 11134 if (FinalLoc.isValid()) 11135 Record->addAttr(new (Context) 11136 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11137 11138 // C++ [class]p2: 11139 // [...] The class-name is also inserted into the scope of the 11140 // class itself; this is known as the injected-class-name. For 11141 // purposes of access checking, the injected-class-name is treated 11142 // as if it were a public member name. 11143 CXXRecordDecl *InjectedClassName 11144 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11145 Record->getLocStart(), Record->getLocation(), 11146 Record->getIdentifier(), 11147 /*PrevDecl=*/0, 11148 /*DelayTypeCreation=*/true); 11149 Context.getTypeDeclType(InjectedClassName, Record); 11150 InjectedClassName->setImplicit(); 11151 InjectedClassName->setAccess(AS_public); 11152 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11153 InjectedClassName->setDescribedClassTemplate(Template); 11154 PushOnScopeChains(InjectedClassName, S); 11155 assert(InjectedClassName->isInjectedClassName() && 11156 "Broken injected-class-name"); 11157 } 11158 11159 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11160 SourceLocation RBraceLoc) { 11161 AdjustDeclIfTemplate(TagD); 11162 TagDecl *Tag = cast<TagDecl>(TagD); 11163 Tag->setRBraceLoc(RBraceLoc); 11164 11165 // Make sure we "complete" the definition even it is invalid. 11166 if (Tag->isBeingDefined()) { 11167 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11168 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11169 RD->completeDefinition(); 11170 } 11171 11172 if (isa<CXXRecordDecl>(Tag)) 11173 FieldCollector->FinishClass(); 11174 11175 // Exit this scope of this tag's definition. 11176 PopDeclContext(); 11177 11178 if (getCurLexicalContext()->isObjCContainer() && 11179 Tag->getDeclContext()->isFileContext()) 11180 Tag->setTopLevelDeclInObjCContainer(); 11181 11182 // Notify the consumer that we've defined a tag. 11183 if (!Tag->isInvalidDecl()) 11184 Consumer.HandleTagDeclDefinition(Tag); 11185 } 11186 11187 void Sema::ActOnObjCContainerFinishDefinition() { 11188 // Exit this scope of this interface definition. 11189 PopDeclContext(); 11190 } 11191 11192 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11193 assert(DC == CurContext && "Mismatch of container contexts"); 11194 OriginalLexicalContext = DC; 11195 ActOnObjCContainerFinishDefinition(); 11196 } 11197 11198 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11199 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11200 OriginalLexicalContext = 0; 11201 } 11202 11203 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11204 AdjustDeclIfTemplate(TagD); 11205 TagDecl *Tag = cast<TagDecl>(TagD); 11206 Tag->setInvalidDecl(); 11207 11208 // Make sure we "complete" the definition even it is invalid. 11209 if (Tag->isBeingDefined()) { 11210 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11211 RD->completeDefinition(); 11212 } 11213 11214 // We're undoing ActOnTagStartDefinition here, not 11215 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11216 // the FieldCollector. 11217 11218 PopDeclContext(); 11219 } 11220 11221 // Note that FieldName may be null for anonymous bitfields. 11222 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11223 IdentifierInfo *FieldName, 11224 QualType FieldTy, bool IsMsStruct, 11225 Expr *BitWidth, bool *ZeroWidth) { 11226 // Default to true; that shouldn't confuse checks for emptiness 11227 if (ZeroWidth) 11228 *ZeroWidth = true; 11229 11230 // C99 6.7.2.1p4 - verify the field type. 11231 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11232 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11233 // Handle incomplete types with specific error. 11234 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11235 return ExprError(); 11236 if (FieldName) 11237 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11238 << FieldName << FieldTy << BitWidth->getSourceRange(); 11239 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11240 << FieldTy << BitWidth->getSourceRange(); 11241 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11242 UPPC_BitFieldWidth)) 11243 return ExprError(); 11244 11245 // If the bit-width is type- or value-dependent, don't try to check 11246 // it now. 11247 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11248 return Owned(BitWidth); 11249 11250 llvm::APSInt Value; 11251 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11252 if (ICE.isInvalid()) 11253 return ICE; 11254 BitWidth = ICE.take(); 11255 11256 if (Value != 0 && ZeroWidth) 11257 *ZeroWidth = false; 11258 11259 // Zero-width bitfield is ok for anonymous field. 11260 if (Value == 0 && FieldName) 11261 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11262 11263 if (Value.isSigned() && Value.isNegative()) { 11264 if (FieldName) 11265 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11266 << FieldName << Value.toString(10); 11267 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11268 << Value.toString(10); 11269 } 11270 11271 if (!FieldTy->isDependentType()) { 11272 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11273 if (Value.getZExtValue() > TypeSize) { 11274 if (!getLangOpts().CPlusPlus || IsMsStruct) { 11275 if (FieldName) 11276 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11277 << FieldName << (unsigned)Value.getZExtValue() 11278 << (unsigned)TypeSize; 11279 11280 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11281 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11282 } 11283 11284 if (FieldName) 11285 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11286 << FieldName << (unsigned)Value.getZExtValue() 11287 << (unsigned)TypeSize; 11288 else 11289 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11290 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11291 } 11292 } 11293 11294 return Owned(BitWidth); 11295 } 11296 11297 /// ActOnField - Each field of a C struct/union is passed into this in order 11298 /// to create a FieldDecl object for it. 11299 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11300 Declarator &D, Expr *BitfieldWidth) { 11301 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11302 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11303 /*InitStyle=*/ICIS_NoInit, AS_public); 11304 return Res; 11305 } 11306 11307 /// HandleField - Analyze a field of a C struct or a C++ data member. 11308 /// 11309 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11310 SourceLocation DeclStart, 11311 Declarator &D, Expr *BitWidth, 11312 InClassInitStyle InitStyle, 11313 AccessSpecifier AS) { 11314 IdentifierInfo *II = D.getIdentifier(); 11315 SourceLocation Loc = DeclStart; 11316 if (II) Loc = D.getIdentifierLoc(); 11317 11318 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11319 QualType T = TInfo->getType(); 11320 if (getLangOpts().CPlusPlus) { 11321 CheckExtraCXXDefaultArguments(D); 11322 11323 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11324 UPPC_DataMemberType)) { 11325 D.setInvalidType(); 11326 T = Context.IntTy; 11327 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11328 } 11329 } 11330 11331 // TR 18037 does not allow fields to be declared with address spaces. 11332 if (T.getQualifiers().hasAddressSpace()) { 11333 Diag(Loc, diag::err_field_with_address_space); 11334 D.setInvalidType(); 11335 } 11336 11337 // OpenCL 1.2 spec, s6.9 r: 11338 // The event type cannot be used to declare a structure or union field. 11339 if (LangOpts.OpenCL && T->isEventT()) { 11340 Diag(Loc, diag::err_event_t_struct_field); 11341 D.setInvalidType(); 11342 } 11343 11344 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11345 11346 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11347 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11348 diag::err_invalid_thread) 11349 << DeclSpec::getSpecifierName(TSCS); 11350 11351 // Check to see if this name was declared as a member previously 11352 NamedDecl *PrevDecl = 0; 11353 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11354 LookupName(Previous, S); 11355 switch (Previous.getResultKind()) { 11356 case LookupResult::Found: 11357 case LookupResult::FoundUnresolvedValue: 11358 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11359 break; 11360 11361 case LookupResult::FoundOverloaded: 11362 PrevDecl = Previous.getRepresentativeDecl(); 11363 break; 11364 11365 case LookupResult::NotFound: 11366 case LookupResult::NotFoundInCurrentInstantiation: 11367 case LookupResult::Ambiguous: 11368 break; 11369 } 11370 Previous.suppressDiagnostics(); 11371 11372 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11373 // Maybe we will complain about the shadowed template parameter. 11374 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11375 // Just pretend that we didn't see the previous declaration. 11376 PrevDecl = 0; 11377 } 11378 11379 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11380 PrevDecl = 0; 11381 11382 bool Mutable 11383 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11384 SourceLocation TSSL = D.getLocStart(); 11385 FieldDecl *NewFD 11386 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11387 TSSL, AS, PrevDecl, &D); 11388 11389 if (NewFD->isInvalidDecl()) 11390 Record->setInvalidDecl(); 11391 11392 if (D.getDeclSpec().isModulePrivateSpecified()) 11393 NewFD->setModulePrivate(); 11394 11395 if (NewFD->isInvalidDecl() && PrevDecl) { 11396 // Don't introduce NewFD into scope; there's already something 11397 // with the same name in the same scope. 11398 } else if (II) { 11399 PushOnScopeChains(NewFD, S); 11400 } else 11401 Record->addDecl(NewFD); 11402 11403 return NewFD; 11404 } 11405 11406 /// \brief Build a new FieldDecl and check its well-formedness. 11407 /// 11408 /// This routine builds a new FieldDecl given the fields name, type, 11409 /// record, etc. \p PrevDecl should refer to any previous declaration 11410 /// with the same name and in the same scope as the field to be 11411 /// created. 11412 /// 11413 /// \returns a new FieldDecl. 11414 /// 11415 /// \todo The Declarator argument is a hack. It will be removed once 11416 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11417 TypeSourceInfo *TInfo, 11418 RecordDecl *Record, SourceLocation Loc, 11419 bool Mutable, Expr *BitWidth, 11420 InClassInitStyle InitStyle, 11421 SourceLocation TSSL, 11422 AccessSpecifier AS, NamedDecl *PrevDecl, 11423 Declarator *D) { 11424 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11425 bool InvalidDecl = false; 11426 if (D) InvalidDecl = D->isInvalidType(); 11427 11428 // If we receive a broken type, recover by assuming 'int' and 11429 // marking this declaration as invalid. 11430 if (T.isNull()) { 11431 InvalidDecl = true; 11432 T = Context.IntTy; 11433 } 11434 11435 QualType EltTy = Context.getBaseElementType(T); 11436 if (!EltTy->isDependentType()) { 11437 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11438 // Fields of incomplete type force their record to be invalid. 11439 Record->setInvalidDecl(); 11440 InvalidDecl = true; 11441 } else { 11442 NamedDecl *Def; 11443 EltTy->isIncompleteType(&Def); 11444 if (Def && Def->isInvalidDecl()) { 11445 Record->setInvalidDecl(); 11446 InvalidDecl = true; 11447 } 11448 } 11449 } 11450 11451 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11452 if (BitWidth && getLangOpts().OpenCL) { 11453 Diag(Loc, diag::err_opencl_bitfields); 11454 InvalidDecl = true; 11455 } 11456 11457 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11458 // than a variably modified type. 11459 if (!InvalidDecl && T->isVariablyModifiedType()) { 11460 bool SizeIsNegative; 11461 llvm::APSInt Oversized; 11462 11463 TypeSourceInfo *FixedTInfo = 11464 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11465 SizeIsNegative, 11466 Oversized); 11467 if (FixedTInfo) { 11468 Diag(Loc, diag::warn_illegal_constant_array_size); 11469 TInfo = FixedTInfo; 11470 T = FixedTInfo->getType(); 11471 } else { 11472 if (SizeIsNegative) 11473 Diag(Loc, diag::err_typecheck_negative_array_size); 11474 else if (Oversized.getBoolValue()) 11475 Diag(Loc, diag::err_array_too_large) 11476 << Oversized.toString(10); 11477 else 11478 Diag(Loc, diag::err_typecheck_field_variable_size); 11479 InvalidDecl = true; 11480 } 11481 } 11482 11483 // Fields can not have abstract class types 11484 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11485 diag::err_abstract_type_in_decl, 11486 AbstractFieldType)) 11487 InvalidDecl = true; 11488 11489 bool ZeroWidth = false; 11490 // If this is declared as a bit-field, check the bit-field. 11491 if (!InvalidDecl && BitWidth) { 11492 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11493 &ZeroWidth).take(); 11494 if (!BitWidth) { 11495 InvalidDecl = true; 11496 BitWidth = 0; 11497 ZeroWidth = false; 11498 } 11499 } 11500 11501 // Check that 'mutable' is consistent with the type of the declaration. 11502 if (!InvalidDecl && Mutable) { 11503 unsigned DiagID = 0; 11504 if (T->isReferenceType()) 11505 DiagID = diag::err_mutable_reference; 11506 else if (T.isConstQualified()) 11507 DiagID = diag::err_mutable_const; 11508 11509 if (DiagID) { 11510 SourceLocation ErrLoc = Loc; 11511 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11512 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11513 Diag(ErrLoc, DiagID); 11514 Mutable = false; 11515 InvalidDecl = true; 11516 } 11517 } 11518 11519 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11520 BitWidth, Mutable, InitStyle); 11521 if (InvalidDecl) 11522 NewFD->setInvalidDecl(); 11523 11524 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11525 Diag(Loc, diag::err_duplicate_member) << II; 11526 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11527 NewFD->setInvalidDecl(); 11528 } 11529 11530 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11531 if (Record->isUnion()) { 11532 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11533 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11534 if (RDecl->getDefinition()) { 11535 // C++ [class.union]p1: An object of a class with a non-trivial 11536 // constructor, a non-trivial copy constructor, a non-trivial 11537 // destructor, or a non-trivial copy assignment operator 11538 // cannot be a member of a union, nor can an array of such 11539 // objects. 11540 if (CheckNontrivialField(NewFD)) 11541 NewFD->setInvalidDecl(); 11542 } 11543 } 11544 11545 // C++ [class.union]p1: If a union contains a member of reference type, 11546 // the program is ill-formed, except when compiling with MSVC extensions 11547 // enabled. 11548 if (EltTy->isReferenceType()) { 11549 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11550 diag::ext_union_member_of_reference_type : 11551 diag::err_union_member_of_reference_type) 11552 << NewFD->getDeclName() << EltTy; 11553 if (!getLangOpts().MicrosoftExt) 11554 NewFD->setInvalidDecl(); 11555 } 11556 } 11557 } 11558 11559 // FIXME: We need to pass in the attributes given an AST 11560 // representation, not a parser representation. 11561 if (D) { 11562 // FIXME: The current scope is almost... but not entirely... correct here. 11563 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11564 11565 if (NewFD->hasAttrs()) 11566 CheckAlignasUnderalignment(NewFD); 11567 } 11568 11569 // In auto-retain/release, infer strong retension for fields of 11570 // retainable type. 11571 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11572 NewFD->setInvalidDecl(); 11573 11574 if (T.isObjCGCWeak()) 11575 Diag(Loc, diag::warn_attribute_weak_on_field); 11576 11577 NewFD->setAccess(AS); 11578 return NewFD; 11579 } 11580 11581 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11582 assert(FD); 11583 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11584 11585 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11586 return false; 11587 11588 QualType EltTy = Context.getBaseElementType(FD->getType()); 11589 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11590 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11591 if (RDecl->getDefinition()) { 11592 // We check for copy constructors before constructors 11593 // because otherwise we'll never get complaints about 11594 // copy constructors. 11595 11596 CXXSpecialMember member = CXXInvalid; 11597 // We're required to check for any non-trivial constructors. Since the 11598 // implicit default constructor is suppressed if there are any 11599 // user-declared constructors, we just need to check that there is a 11600 // trivial default constructor and a trivial copy constructor. (We don't 11601 // worry about move constructors here, since this is a C++98 check.) 11602 if (RDecl->hasNonTrivialCopyConstructor()) 11603 member = CXXCopyConstructor; 11604 else if (!RDecl->hasTrivialDefaultConstructor()) 11605 member = CXXDefaultConstructor; 11606 else if (RDecl->hasNonTrivialCopyAssignment()) 11607 member = CXXCopyAssignment; 11608 else if (RDecl->hasNonTrivialDestructor()) 11609 member = CXXDestructor; 11610 11611 if (member != CXXInvalid) { 11612 if (!getLangOpts().CPlusPlus11 && 11613 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11614 // Objective-C++ ARC: it is an error to have a non-trivial field of 11615 // a union. However, system headers in Objective-C programs 11616 // occasionally have Objective-C lifetime objects within unions, 11617 // and rather than cause the program to fail, we make those 11618 // members unavailable. 11619 SourceLocation Loc = FD->getLocation(); 11620 if (getSourceManager().isInSystemHeader(Loc)) { 11621 if (!FD->hasAttr<UnavailableAttr>()) 11622 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 11623 "this system field has retaining ownership")); 11624 return false; 11625 } 11626 } 11627 11628 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11629 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11630 diag::err_illegal_union_or_anon_struct_member) 11631 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11632 DiagnoseNontrivial(RDecl, member); 11633 return !getLangOpts().CPlusPlus11; 11634 } 11635 } 11636 } 11637 11638 return false; 11639 } 11640 11641 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11642 /// AST enum value. 11643 static ObjCIvarDecl::AccessControl 11644 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11645 switch (ivarVisibility) { 11646 default: llvm_unreachable("Unknown visitibility kind"); 11647 case tok::objc_private: return ObjCIvarDecl::Private; 11648 case tok::objc_public: return ObjCIvarDecl::Public; 11649 case tok::objc_protected: return ObjCIvarDecl::Protected; 11650 case tok::objc_package: return ObjCIvarDecl::Package; 11651 } 11652 } 11653 11654 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11655 /// in order to create an IvarDecl object for it. 11656 Decl *Sema::ActOnIvar(Scope *S, 11657 SourceLocation DeclStart, 11658 Declarator &D, Expr *BitfieldWidth, 11659 tok::ObjCKeywordKind Visibility) { 11660 11661 IdentifierInfo *II = D.getIdentifier(); 11662 Expr *BitWidth = (Expr*)BitfieldWidth; 11663 SourceLocation Loc = DeclStart; 11664 if (II) Loc = D.getIdentifierLoc(); 11665 11666 // FIXME: Unnamed fields can be handled in various different ways, for 11667 // example, unnamed unions inject all members into the struct namespace! 11668 11669 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11670 QualType T = TInfo->getType(); 11671 11672 if (BitWidth) { 11673 // 6.7.2.1p3, 6.7.2.1p4 11674 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11675 if (!BitWidth) 11676 D.setInvalidType(); 11677 } else { 11678 // Not a bitfield. 11679 11680 // validate II. 11681 11682 } 11683 if (T->isReferenceType()) { 11684 Diag(Loc, diag::err_ivar_reference_type); 11685 D.setInvalidType(); 11686 } 11687 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11688 // than a variably modified type. 11689 else if (T->isVariablyModifiedType()) { 11690 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11691 D.setInvalidType(); 11692 } 11693 11694 // Get the visibility (access control) for this ivar. 11695 ObjCIvarDecl::AccessControl ac = 11696 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11697 : ObjCIvarDecl::None; 11698 // Must set ivar's DeclContext to its enclosing interface. 11699 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11700 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11701 return 0; 11702 ObjCContainerDecl *EnclosingContext; 11703 if (ObjCImplementationDecl *IMPDecl = 11704 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11705 if (LangOpts.ObjCRuntime.isFragile()) { 11706 // Case of ivar declared in an implementation. Context is that of its class. 11707 EnclosingContext = IMPDecl->getClassInterface(); 11708 assert(EnclosingContext && "Implementation has no class interface!"); 11709 } 11710 else 11711 EnclosingContext = EnclosingDecl; 11712 } else { 11713 if (ObjCCategoryDecl *CDecl = 11714 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11715 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11716 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11717 return 0; 11718 } 11719 } 11720 EnclosingContext = EnclosingDecl; 11721 } 11722 11723 // Construct the decl. 11724 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11725 DeclStart, Loc, II, T, 11726 TInfo, ac, (Expr *)BitfieldWidth); 11727 11728 if (II) { 11729 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11730 ForRedeclaration); 11731 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11732 && !isa<TagDecl>(PrevDecl)) { 11733 Diag(Loc, diag::err_duplicate_member) << II; 11734 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11735 NewID->setInvalidDecl(); 11736 } 11737 } 11738 11739 // Process attributes attached to the ivar. 11740 ProcessDeclAttributes(S, NewID, D); 11741 11742 if (D.isInvalidType()) 11743 NewID->setInvalidDecl(); 11744 11745 // In ARC, infer 'retaining' for ivars of retainable type. 11746 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11747 NewID->setInvalidDecl(); 11748 11749 if (D.getDeclSpec().isModulePrivateSpecified()) 11750 NewID->setModulePrivate(); 11751 11752 if (II) { 11753 // FIXME: When interfaces are DeclContexts, we'll need to add 11754 // these to the interface. 11755 S->AddDecl(NewID); 11756 IdResolver.AddDecl(NewID); 11757 } 11758 11759 if (LangOpts.ObjCRuntime.isNonFragile() && 11760 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11761 Diag(Loc, diag::warn_ivars_in_interface); 11762 11763 return NewID; 11764 } 11765 11766 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11767 /// class and class extensions. For every class \@interface and class 11768 /// extension \@interface, if the last ivar is a bitfield of any type, 11769 /// then add an implicit `char :0` ivar to the end of that interface. 11770 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11771 SmallVectorImpl<Decl *> &AllIvarDecls) { 11772 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11773 return; 11774 11775 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11776 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11777 11778 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11779 return; 11780 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11781 if (!ID) { 11782 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11783 if (!CD->IsClassExtension()) 11784 return; 11785 } 11786 // No need to add this to end of @implementation. 11787 else 11788 return; 11789 } 11790 // All conditions are met. Add a new bitfield to the tail end of ivars. 11791 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11792 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11793 11794 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11795 DeclLoc, DeclLoc, 0, 11796 Context.CharTy, 11797 Context.getTrivialTypeSourceInfo(Context.CharTy, 11798 DeclLoc), 11799 ObjCIvarDecl::Private, BW, 11800 true); 11801 AllIvarDecls.push_back(Ivar); 11802 } 11803 11804 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 11805 ArrayRef<Decl *> Fields, SourceLocation LBrac, 11806 SourceLocation RBrac, AttributeList *Attr) { 11807 assert(EnclosingDecl && "missing record or interface decl"); 11808 11809 // If this is an Objective-C @implementation or category and we have 11810 // new fields here we should reset the layout of the interface since 11811 // it will now change. 11812 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 11813 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 11814 switch (DC->getKind()) { 11815 default: break; 11816 case Decl::ObjCCategory: 11817 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 11818 break; 11819 case Decl::ObjCImplementation: 11820 Context. 11821 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 11822 break; 11823 } 11824 } 11825 11826 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 11827 11828 // Start counting up the number of named members; make sure to include 11829 // members of anonymous structs and unions in the total. 11830 unsigned NumNamedMembers = 0; 11831 if (Record) { 11832 for (RecordDecl::decl_iterator i = Record->decls_begin(), 11833 e = Record->decls_end(); i != e; i++) { 11834 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 11835 if (IFD->getDeclName()) 11836 ++NumNamedMembers; 11837 } 11838 } 11839 11840 // Verify that all the fields are okay. 11841 SmallVector<FieldDecl*, 32> RecFields; 11842 11843 bool ARCErrReported = false; 11844 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 11845 i != end; ++i) { 11846 FieldDecl *FD = cast<FieldDecl>(*i); 11847 11848 // Get the type for the field. 11849 const Type *FDTy = FD->getType().getTypePtr(); 11850 11851 if (!FD->isAnonymousStructOrUnion()) { 11852 // Remember all fields written by the user. 11853 RecFields.push_back(FD); 11854 } 11855 11856 // If the field is already invalid for some reason, don't emit more 11857 // diagnostics about it. 11858 if (FD->isInvalidDecl()) { 11859 EnclosingDecl->setInvalidDecl(); 11860 continue; 11861 } 11862 11863 // C99 6.7.2.1p2: 11864 // A structure or union shall not contain a member with 11865 // incomplete or function type (hence, a structure shall not 11866 // contain an instance of itself, but may contain a pointer to 11867 // an instance of itself), except that the last member of a 11868 // structure with more than one named member may have incomplete 11869 // array type; such a structure (and any union containing, 11870 // possibly recursively, a member that is such a structure) 11871 // shall not be a member of a structure or an element of an 11872 // array. 11873 if (FDTy->isFunctionType()) { 11874 // Field declared as a function. 11875 Diag(FD->getLocation(), diag::err_field_declared_as_function) 11876 << FD->getDeclName(); 11877 FD->setInvalidDecl(); 11878 EnclosingDecl->setInvalidDecl(); 11879 continue; 11880 } else if (FDTy->isIncompleteArrayType() && Record && 11881 ((i + 1 == Fields.end() && !Record->isUnion()) || 11882 ((getLangOpts().MicrosoftExt || 11883 getLangOpts().CPlusPlus) && 11884 (i + 1 == Fields.end() || Record->isUnion())))) { 11885 // Flexible array member. 11886 // Microsoft and g++ is more permissive regarding flexible array. 11887 // It will accept flexible array in union and also 11888 // as the sole element of a struct/class. 11889 unsigned DiagID = 0; 11890 if (Record->isUnion()) 11891 DiagID = getLangOpts().MicrosoftExt 11892 ? diag::ext_flexible_array_union_ms 11893 : getLangOpts().CPlusPlus 11894 ? diag::ext_flexible_array_union_gnu 11895 : diag::err_flexible_array_union; 11896 else if (Fields.size() == 1) 11897 DiagID = getLangOpts().MicrosoftExt 11898 ? diag::ext_flexible_array_empty_aggregate_ms 11899 : getLangOpts().CPlusPlus 11900 ? diag::ext_flexible_array_empty_aggregate_gnu 11901 : NumNamedMembers < 1 11902 ? diag::err_flexible_array_empty_aggregate 11903 : 0; 11904 11905 if (DiagID) 11906 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 11907 << Record->getTagKind(); 11908 // While the layout of types that contain virtual bases is not specified 11909 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 11910 // virtual bases after the derived members. This would make a flexible 11911 // array member declared at the end of an object not adjacent to the end 11912 // of the type. 11913 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 11914 if (RD->getNumVBases() != 0) 11915 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 11916 << FD->getDeclName() << Record->getTagKind(); 11917 if (!getLangOpts().C99) 11918 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11919 << FD->getDeclName() << Record->getTagKind(); 11920 11921 if (!FD->getType()->isDependentType() && 11922 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 11923 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 11924 << FD->getDeclName() << FD->getType(); 11925 FD->setInvalidDecl(); 11926 EnclosingDecl->setInvalidDecl(); 11927 continue; 11928 } 11929 // Okay, we have a legal flexible array member at the end of the struct. 11930 if (Record) 11931 Record->setHasFlexibleArrayMember(true); 11932 } else if (!FDTy->isDependentType() && 11933 RequireCompleteType(FD->getLocation(), FD->getType(), 11934 diag::err_field_incomplete)) { 11935 // Incomplete type 11936 FD->setInvalidDecl(); 11937 EnclosingDecl->setInvalidDecl(); 11938 continue; 11939 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 11940 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 11941 // If this is a member of a union, then entire union becomes "flexible". 11942 if (Record && Record->isUnion()) { 11943 Record->setHasFlexibleArrayMember(true); 11944 } else { 11945 // If this is a struct/class and this is not the last element, reject 11946 // it. Note that GCC supports variable sized arrays in the middle of 11947 // structures. 11948 if (i + 1 != Fields.end()) 11949 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 11950 << FD->getDeclName() << FD->getType(); 11951 else { 11952 // We support flexible arrays at the end of structs in 11953 // other structs as an extension. 11954 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 11955 << FD->getDeclName(); 11956 if (Record) 11957 Record->setHasFlexibleArrayMember(true); 11958 } 11959 } 11960 } 11961 if (isa<ObjCContainerDecl>(EnclosingDecl) && 11962 RequireNonAbstractType(FD->getLocation(), FD->getType(), 11963 diag::err_abstract_type_in_decl, 11964 AbstractIvarType)) { 11965 // Ivars can not have abstract class types 11966 FD->setInvalidDecl(); 11967 } 11968 if (Record && FDTTy->getDecl()->hasObjectMember()) 11969 Record->setHasObjectMember(true); 11970 if (Record && FDTTy->getDecl()->hasVolatileMember()) 11971 Record->setHasVolatileMember(true); 11972 } else if (FDTy->isObjCObjectType()) { 11973 /// A field cannot be an Objective-c object 11974 Diag(FD->getLocation(), diag::err_statically_allocated_object) 11975 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 11976 QualType T = Context.getObjCObjectPointerType(FD->getType()); 11977 FD->setType(T); 11978 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 11979 (!getLangOpts().CPlusPlus || Record->isUnion())) { 11980 // It's an error in ARC if a field has lifetime. 11981 // We don't want to report this in a system header, though, 11982 // so we just make the field unavailable. 11983 // FIXME: that's really not sufficient; we need to make the type 11984 // itself invalid to, say, initialize or copy. 11985 QualType T = FD->getType(); 11986 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 11987 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 11988 SourceLocation loc = FD->getLocation(); 11989 if (getSourceManager().isInSystemHeader(loc)) { 11990 if (!FD->hasAttr<UnavailableAttr>()) { 11991 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 11992 "this system field has retaining ownership")); 11993 } 11994 } else { 11995 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 11996 << T->isBlockPointerType() << Record->getTagKind(); 11997 } 11998 ARCErrReported = true; 11999 } 12000 } else if (getLangOpts().ObjC1 && 12001 getLangOpts().getGC() != LangOptions::NonGC && 12002 Record && !Record->hasObjectMember()) { 12003 if (FD->getType()->isObjCObjectPointerType() || 12004 FD->getType().isObjCGCStrong()) 12005 Record->setHasObjectMember(true); 12006 else if (Context.getAsArrayType(FD->getType())) { 12007 QualType BaseType = Context.getBaseElementType(FD->getType()); 12008 if (BaseType->isRecordType() && 12009 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12010 Record->setHasObjectMember(true); 12011 else if (BaseType->isObjCObjectPointerType() || 12012 BaseType.isObjCGCStrong()) 12013 Record->setHasObjectMember(true); 12014 } 12015 } 12016 if (Record && FD->getType().isVolatileQualified()) 12017 Record->setHasVolatileMember(true); 12018 // Keep track of the number of named members. 12019 if (FD->getIdentifier()) 12020 ++NumNamedMembers; 12021 } 12022 12023 // Okay, we successfully defined 'Record'. 12024 if (Record) { 12025 bool Completed = false; 12026 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12027 if (!CXXRecord->isInvalidDecl()) { 12028 // Set access bits correctly on the directly-declared conversions. 12029 for (CXXRecordDecl::conversion_iterator 12030 I = CXXRecord->conversion_begin(), 12031 E = CXXRecord->conversion_end(); I != E; ++I) 12032 I.setAccess((*I)->getAccess()); 12033 12034 if (!CXXRecord->isDependentType()) { 12035 if (CXXRecord->hasUserDeclaredDestructor()) { 12036 // Adjust user-defined destructor exception spec. 12037 if (getLangOpts().CPlusPlus11) 12038 AdjustDestructorExceptionSpec(CXXRecord, 12039 CXXRecord->getDestructor()); 12040 12041 // The Microsoft ABI requires that we perform the destructor body 12042 // checks (i.e. operator delete() lookup) at every declaration, as 12043 // any translation unit may need to emit a deleting destructor. 12044 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12045 CheckDestructor(CXXRecord->getDestructor()); 12046 } 12047 12048 // Add any implicitly-declared members to this class. 12049 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12050 12051 // If we have virtual base classes, we may end up finding multiple 12052 // final overriders for a given virtual function. Check for this 12053 // problem now. 12054 if (CXXRecord->getNumVBases()) { 12055 CXXFinalOverriderMap FinalOverriders; 12056 CXXRecord->getFinalOverriders(FinalOverriders); 12057 12058 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12059 MEnd = FinalOverriders.end(); 12060 M != MEnd; ++M) { 12061 for (OverridingMethods::iterator SO = M->second.begin(), 12062 SOEnd = M->second.end(); 12063 SO != SOEnd; ++SO) { 12064 assert(SO->second.size() > 0 && 12065 "Virtual function without overridding functions?"); 12066 if (SO->second.size() == 1) 12067 continue; 12068 12069 // C++ [class.virtual]p2: 12070 // In a derived class, if a virtual member function of a base 12071 // class subobject has more than one final overrider the 12072 // program is ill-formed. 12073 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12074 << (const NamedDecl *)M->first << Record; 12075 Diag(M->first->getLocation(), 12076 diag::note_overridden_virtual_function); 12077 for (OverridingMethods::overriding_iterator 12078 OM = SO->second.begin(), 12079 OMEnd = SO->second.end(); 12080 OM != OMEnd; ++OM) 12081 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12082 << (const NamedDecl *)M->first << OM->Method->getParent(); 12083 12084 Record->setInvalidDecl(); 12085 } 12086 } 12087 CXXRecord->completeDefinition(&FinalOverriders); 12088 Completed = true; 12089 } 12090 } 12091 } 12092 } 12093 12094 if (!Completed) 12095 Record->completeDefinition(); 12096 12097 if (Record->hasAttrs()) 12098 CheckAlignasUnderalignment(Record); 12099 12100 // Check if the structure/union declaration is a type that can have zero 12101 // size in C. For C this is a language extension, for C++ it may cause 12102 // compatibility problems. 12103 bool CheckForZeroSize; 12104 if (!getLangOpts().CPlusPlus) { 12105 CheckForZeroSize = true; 12106 } else { 12107 // For C++ filter out types that cannot be referenced in C code. 12108 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12109 CheckForZeroSize = 12110 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12111 !CXXRecord->isDependentType() && 12112 CXXRecord->isCLike(); 12113 } 12114 if (CheckForZeroSize) { 12115 bool ZeroSize = true; 12116 bool IsEmpty = true; 12117 unsigned NonBitFields = 0; 12118 for (RecordDecl::field_iterator I = Record->field_begin(), 12119 E = Record->field_end(); 12120 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12121 IsEmpty = false; 12122 if (I->isUnnamedBitfield()) { 12123 if (I->getBitWidthValue(Context) > 0) 12124 ZeroSize = false; 12125 } else { 12126 ++NonBitFields; 12127 QualType FieldType = I->getType(); 12128 if (FieldType->isIncompleteType() || 12129 !Context.getTypeSizeInChars(FieldType).isZero()) 12130 ZeroSize = false; 12131 } 12132 } 12133 12134 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12135 // allowed in C++, but warn if its declaration is inside 12136 // extern "C" block. 12137 if (ZeroSize) { 12138 Diag(RecLoc, getLangOpts().CPlusPlus ? 12139 diag::warn_zero_size_struct_union_in_extern_c : 12140 diag::warn_zero_size_struct_union_compat) 12141 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12142 } 12143 12144 // Structs without named members are extension in C (C99 6.7.2.1p7), 12145 // but are accepted by GCC. 12146 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12147 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12148 diag::ext_no_named_members_in_struct_union) 12149 << Record->isUnion(); 12150 } 12151 } 12152 } else { 12153 ObjCIvarDecl **ClsFields = 12154 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12155 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12156 ID->setEndOfDefinitionLoc(RBrac); 12157 // Add ivar's to class's DeclContext. 12158 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12159 ClsFields[i]->setLexicalDeclContext(ID); 12160 ID->addDecl(ClsFields[i]); 12161 } 12162 // Must enforce the rule that ivars in the base classes may not be 12163 // duplicates. 12164 if (ID->getSuperClass()) 12165 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12166 } else if (ObjCImplementationDecl *IMPDecl = 12167 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12168 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12169 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12170 // Ivar declared in @implementation never belongs to the implementation. 12171 // Only it is in implementation's lexical context. 12172 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12173 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12174 IMPDecl->setIvarLBraceLoc(LBrac); 12175 IMPDecl->setIvarRBraceLoc(RBrac); 12176 } else if (ObjCCategoryDecl *CDecl = 12177 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12178 // case of ivars in class extension; all other cases have been 12179 // reported as errors elsewhere. 12180 // FIXME. Class extension does not have a LocEnd field. 12181 // CDecl->setLocEnd(RBrac); 12182 // Add ivar's to class extension's DeclContext. 12183 // Diagnose redeclaration of private ivars. 12184 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12185 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12186 if (IDecl) { 12187 if (const ObjCIvarDecl *ClsIvar = 12188 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12189 Diag(ClsFields[i]->getLocation(), 12190 diag::err_duplicate_ivar_declaration); 12191 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12192 continue; 12193 } 12194 for (ObjCInterfaceDecl::known_extensions_iterator 12195 Ext = IDecl->known_extensions_begin(), 12196 ExtEnd = IDecl->known_extensions_end(); 12197 Ext != ExtEnd; ++Ext) { 12198 if (const ObjCIvarDecl *ClsExtIvar 12199 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12200 Diag(ClsFields[i]->getLocation(), 12201 diag::err_duplicate_ivar_declaration); 12202 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12203 continue; 12204 } 12205 } 12206 } 12207 ClsFields[i]->setLexicalDeclContext(CDecl); 12208 CDecl->addDecl(ClsFields[i]); 12209 } 12210 CDecl->setIvarLBraceLoc(LBrac); 12211 CDecl->setIvarRBraceLoc(RBrac); 12212 } 12213 } 12214 12215 if (Attr) 12216 ProcessDeclAttributeList(S, Record, Attr); 12217 } 12218 12219 /// \brief Determine whether the given integral value is representable within 12220 /// the given type T. 12221 static bool isRepresentableIntegerValue(ASTContext &Context, 12222 llvm::APSInt &Value, 12223 QualType T) { 12224 assert(T->isIntegralType(Context) && "Integral type required!"); 12225 unsigned BitWidth = Context.getIntWidth(T); 12226 12227 if (Value.isUnsigned() || Value.isNonNegative()) { 12228 if (T->isSignedIntegerOrEnumerationType()) 12229 --BitWidth; 12230 return Value.getActiveBits() <= BitWidth; 12231 } 12232 return Value.getMinSignedBits() <= BitWidth; 12233 } 12234 12235 // \brief Given an integral type, return the next larger integral type 12236 // (or a NULL type of no such type exists). 12237 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12238 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12239 // enum checking below. 12240 assert(T->isIntegralType(Context) && "Integral type required!"); 12241 const unsigned NumTypes = 4; 12242 QualType SignedIntegralTypes[NumTypes] = { 12243 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12244 }; 12245 QualType UnsignedIntegralTypes[NumTypes] = { 12246 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12247 Context.UnsignedLongLongTy 12248 }; 12249 12250 unsigned BitWidth = Context.getTypeSize(T); 12251 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12252 : UnsignedIntegralTypes; 12253 for (unsigned I = 0; I != NumTypes; ++I) 12254 if (Context.getTypeSize(Types[I]) > BitWidth) 12255 return Types[I]; 12256 12257 return QualType(); 12258 } 12259 12260 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12261 EnumConstantDecl *LastEnumConst, 12262 SourceLocation IdLoc, 12263 IdentifierInfo *Id, 12264 Expr *Val) { 12265 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12266 llvm::APSInt EnumVal(IntWidth); 12267 QualType EltTy; 12268 12269 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12270 Val = 0; 12271 12272 if (Val) 12273 Val = DefaultLvalueConversion(Val).take(); 12274 12275 if (Val) { 12276 if (Enum->isDependentType() || Val->isTypeDependent()) 12277 EltTy = Context.DependentTy; 12278 else { 12279 SourceLocation ExpLoc; 12280 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12281 !getLangOpts().MicrosoftMode) { 12282 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12283 // constant-expression in the enumerator-definition shall be a converted 12284 // constant expression of the underlying type. 12285 EltTy = Enum->getIntegerType(); 12286 ExprResult Converted = 12287 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12288 CCEK_Enumerator); 12289 if (Converted.isInvalid()) 12290 Val = 0; 12291 else 12292 Val = Converted.take(); 12293 } else if (!Val->isValueDependent() && 12294 !(Val = VerifyIntegerConstantExpression(Val, 12295 &EnumVal).take())) { 12296 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12297 } else { 12298 if (Enum->isFixed()) { 12299 EltTy = Enum->getIntegerType(); 12300 12301 // In Obj-C and Microsoft mode, require the enumeration value to be 12302 // representable in the underlying type of the enumeration. In C++11, 12303 // we perform a non-narrowing conversion as part of converted constant 12304 // expression checking. 12305 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12306 if (getLangOpts().MicrosoftMode) { 12307 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12308 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12309 } else 12310 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12311 } else 12312 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12313 } else if (getLangOpts().CPlusPlus) { 12314 // C++11 [dcl.enum]p5: 12315 // If the underlying type is not fixed, the type of each enumerator 12316 // is the type of its initializing value: 12317 // - If an initializer is specified for an enumerator, the 12318 // initializing value has the same type as the expression. 12319 EltTy = Val->getType(); 12320 } else { 12321 // C99 6.7.2.2p2: 12322 // The expression that defines the value of an enumeration constant 12323 // shall be an integer constant expression that has a value 12324 // representable as an int. 12325 12326 // Complain if the value is not representable in an int. 12327 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12328 Diag(IdLoc, diag::ext_enum_value_not_int) 12329 << EnumVal.toString(10) << Val->getSourceRange() 12330 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12331 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12332 // Force the type of the expression to 'int'. 12333 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12334 } 12335 EltTy = Val->getType(); 12336 } 12337 } 12338 } 12339 } 12340 12341 if (!Val) { 12342 if (Enum->isDependentType()) 12343 EltTy = Context.DependentTy; 12344 else if (!LastEnumConst) { 12345 // C++0x [dcl.enum]p5: 12346 // If the underlying type is not fixed, the type of each enumerator 12347 // is the type of its initializing value: 12348 // - If no initializer is specified for the first enumerator, the 12349 // initializing value has an unspecified integral type. 12350 // 12351 // GCC uses 'int' for its unspecified integral type, as does 12352 // C99 6.7.2.2p3. 12353 if (Enum->isFixed()) { 12354 EltTy = Enum->getIntegerType(); 12355 } 12356 else { 12357 EltTy = Context.IntTy; 12358 } 12359 } else { 12360 // Assign the last value + 1. 12361 EnumVal = LastEnumConst->getInitVal(); 12362 ++EnumVal; 12363 EltTy = LastEnumConst->getType(); 12364 12365 // Check for overflow on increment. 12366 if (EnumVal < LastEnumConst->getInitVal()) { 12367 // C++0x [dcl.enum]p5: 12368 // If the underlying type is not fixed, the type of each enumerator 12369 // is the type of its initializing value: 12370 // 12371 // - Otherwise the type of the initializing value is the same as 12372 // the type of the initializing value of the preceding enumerator 12373 // unless the incremented value is not representable in that type, 12374 // in which case the type is an unspecified integral type 12375 // sufficient to contain the incremented value. If no such type 12376 // exists, the program is ill-formed. 12377 QualType T = getNextLargerIntegralType(Context, EltTy); 12378 if (T.isNull() || Enum->isFixed()) { 12379 // There is no integral type larger enough to represent this 12380 // value. Complain, then allow the value to wrap around. 12381 EnumVal = LastEnumConst->getInitVal(); 12382 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12383 ++EnumVal; 12384 if (Enum->isFixed()) 12385 // When the underlying type is fixed, this is ill-formed. 12386 Diag(IdLoc, diag::err_enumerator_wrapped) 12387 << EnumVal.toString(10) 12388 << EltTy; 12389 else 12390 Diag(IdLoc, diag::warn_enumerator_too_large) 12391 << EnumVal.toString(10); 12392 } else { 12393 EltTy = T; 12394 } 12395 12396 // Retrieve the last enumerator's value, extent that type to the 12397 // type that is supposed to be large enough to represent the incremented 12398 // value, then increment. 12399 EnumVal = LastEnumConst->getInitVal(); 12400 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12401 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12402 ++EnumVal; 12403 12404 // If we're not in C++, diagnose the overflow of enumerator values, 12405 // which in C99 means that the enumerator value is not representable in 12406 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12407 // permits enumerator values that are representable in some larger 12408 // integral type. 12409 if (!getLangOpts().CPlusPlus && !T.isNull()) 12410 Diag(IdLoc, diag::warn_enum_value_overflow); 12411 } else if (!getLangOpts().CPlusPlus && 12412 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12413 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12414 Diag(IdLoc, diag::ext_enum_value_not_int) 12415 << EnumVal.toString(10) << 1; 12416 } 12417 } 12418 } 12419 12420 if (!EltTy->isDependentType()) { 12421 // Make the enumerator value match the signedness and size of the 12422 // enumerator's type. 12423 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12424 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12425 } 12426 12427 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12428 Val, EnumVal); 12429 } 12430 12431 12432 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12433 SourceLocation IdLoc, IdentifierInfo *Id, 12434 AttributeList *Attr, 12435 SourceLocation EqualLoc, Expr *Val) { 12436 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12437 EnumConstantDecl *LastEnumConst = 12438 cast_or_null<EnumConstantDecl>(lastEnumConst); 12439 12440 // The scope passed in may not be a decl scope. Zip up the scope tree until 12441 // we find one that is. 12442 S = getNonFieldDeclScope(S); 12443 12444 // Verify that there isn't already something declared with this name in this 12445 // scope. 12446 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12447 ForRedeclaration); 12448 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12449 // Maybe we will complain about the shadowed template parameter. 12450 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12451 // Just pretend that we didn't see the previous declaration. 12452 PrevDecl = 0; 12453 } 12454 12455 if (PrevDecl) { 12456 // When in C++, we may get a TagDecl with the same name; in this case the 12457 // enum constant will 'hide' the tag. 12458 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12459 "Received TagDecl when not in C++!"); 12460 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12461 if (isa<EnumConstantDecl>(PrevDecl)) 12462 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12463 else 12464 Diag(IdLoc, diag::err_redefinition) << Id; 12465 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12466 return 0; 12467 } 12468 } 12469 12470 // C++ [class.mem]p15: 12471 // If T is the name of a class, then each of the following shall have a name 12472 // different from T: 12473 // - every enumerator of every member of class T that is an unscoped 12474 // enumerated type 12475 if (CXXRecordDecl *Record 12476 = dyn_cast<CXXRecordDecl>( 12477 TheEnumDecl->getDeclContext()->getRedeclContext())) 12478 if (!TheEnumDecl->isScoped() && 12479 Record->getIdentifier() && Record->getIdentifier() == Id) 12480 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12481 12482 EnumConstantDecl *New = 12483 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12484 12485 if (New) { 12486 // Process attributes. 12487 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12488 12489 // Register this decl in the current scope stack. 12490 New->setAccess(TheEnumDecl->getAccess()); 12491 PushOnScopeChains(New, S); 12492 } 12493 12494 ActOnDocumentableDecl(New); 12495 12496 return New; 12497 } 12498 12499 // Returns true when the enum initial expression does not trigger the 12500 // duplicate enum warning. A few common cases are exempted as follows: 12501 // Element2 = Element1 12502 // Element2 = Element1 + 1 12503 // Element2 = Element1 - 1 12504 // Where Element2 and Element1 are from the same enum. 12505 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12506 Expr *InitExpr = ECD->getInitExpr(); 12507 if (!InitExpr) 12508 return true; 12509 InitExpr = InitExpr->IgnoreImpCasts(); 12510 12511 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12512 if (!BO->isAdditiveOp()) 12513 return true; 12514 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12515 if (!IL) 12516 return true; 12517 if (IL->getValue() != 1) 12518 return true; 12519 12520 InitExpr = BO->getLHS(); 12521 } 12522 12523 // This checks if the elements are from the same enum. 12524 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12525 if (!DRE) 12526 return true; 12527 12528 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12529 if (!EnumConstant) 12530 return true; 12531 12532 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12533 Enum) 12534 return true; 12535 12536 return false; 12537 } 12538 12539 struct DupKey { 12540 int64_t val; 12541 bool isTombstoneOrEmptyKey; 12542 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12543 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12544 }; 12545 12546 static DupKey GetDupKey(const llvm::APSInt& Val) { 12547 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12548 false); 12549 } 12550 12551 struct DenseMapInfoDupKey { 12552 static DupKey getEmptyKey() { return DupKey(0, true); } 12553 static DupKey getTombstoneKey() { return DupKey(1, true); } 12554 static unsigned getHashValue(const DupKey Key) { 12555 return (unsigned)(Key.val * 37); 12556 } 12557 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12558 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12559 LHS.val == RHS.val; 12560 } 12561 }; 12562 12563 // Emits a warning when an element is implicitly set a value that 12564 // a previous element has already been set to. 12565 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12566 EnumDecl *Enum, 12567 QualType EnumType) { 12568 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12569 Enum->getLocation()) == 12570 DiagnosticsEngine::Ignored) 12571 return; 12572 // Avoid anonymous enums 12573 if (!Enum->getIdentifier()) 12574 return; 12575 12576 // Only check for small enums. 12577 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12578 return; 12579 12580 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12581 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12582 12583 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12584 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12585 ValueToVectorMap; 12586 12587 DuplicatesVector DupVector; 12588 ValueToVectorMap EnumMap; 12589 12590 // Populate the EnumMap with all values represented by enum constants without 12591 // an initialier. 12592 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12593 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12594 12595 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12596 // this constant. Skip this enum since it may be ill-formed. 12597 if (!ECD) { 12598 return; 12599 } 12600 12601 if (ECD->getInitExpr()) 12602 continue; 12603 12604 DupKey Key = GetDupKey(ECD->getInitVal()); 12605 DeclOrVector &Entry = EnumMap[Key]; 12606 12607 // First time encountering this value. 12608 if (Entry.isNull()) 12609 Entry = ECD; 12610 } 12611 12612 // Create vectors for any values that has duplicates. 12613 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12614 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12615 if (!ValidDuplicateEnum(ECD, Enum)) 12616 continue; 12617 12618 DupKey Key = GetDupKey(ECD->getInitVal()); 12619 12620 DeclOrVector& Entry = EnumMap[Key]; 12621 if (Entry.isNull()) 12622 continue; 12623 12624 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12625 // Ensure constants are different. 12626 if (D == ECD) 12627 continue; 12628 12629 // Create new vector and push values onto it. 12630 ECDVector *Vec = new ECDVector(); 12631 Vec->push_back(D); 12632 Vec->push_back(ECD); 12633 12634 // Update entry to point to the duplicates vector. 12635 Entry = Vec; 12636 12637 // Store the vector somewhere we can consult later for quick emission of 12638 // diagnostics. 12639 DupVector.push_back(Vec); 12640 continue; 12641 } 12642 12643 ECDVector *Vec = Entry.get<ECDVector*>(); 12644 // Make sure constants are not added more than once. 12645 if (*Vec->begin() == ECD) 12646 continue; 12647 12648 Vec->push_back(ECD); 12649 } 12650 12651 // Emit diagnostics. 12652 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12653 DupVectorEnd = DupVector.end(); 12654 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12655 ECDVector *Vec = *DupVectorIter; 12656 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12657 12658 // Emit warning for one enum constant. 12659 ECDVector::iterator I = Vec->begin(); 12660 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12661 << (*I)->getName() << (*I)->getInitVal().toString(10) 12662 << (*I)->getSourceRange(); 12663 ++I; 12664 12665 // Emit one note for each of the remaining enum constants with 12666 // the same value. 12667 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12668 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12669 << (*I)->getName() << (*I)->getInitVal().toString(10) 12670 << (*I)->getSourceRange(); 12671 delete Vec; 12672 } 12673 } 12674 12675 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12676 SourceLocation RBraceLoc, Decl *EnumDeclX, 12677 ArrayRef<Decl *> Elements, 12678 Scope *S, AttributeList *Attr) { 12679 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12680 QualType EnumType = Context.getTypeDeclType(Enum); 12681 12682 if (Attr) 12683 ProcessDeclAttributeList(S, Enum, Attr); 12684 12685 if (Enum->isDependentType()) { 12686 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12687 EnumConstantDecl *ECD = 12688 cast_or_null<EnumConstantDecl>(Elements[i]); 12689 if (!ECD) continue; 12690 12691 ECD->setType(EnumType); 12692 } 12693 12694 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12695 return; 12696 } 12697 12698 // TODO: If the result value doesn't fit in an int, it must be a long or long 12699 // long value. ISO C does not support this, but GCC does as an extension, 12700 // emit a warning. 12701 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12702 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12703 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12704 12705 // Verify that all the values are okay, compute the size of the values, and 12706 // reverse the list. 12707 unsigned NumNegativeBits = 0; 12708 unsigned NumPositiveBits = 0; 12709 12710 // Keep track of whether all elements have type int. 12711 bool AllElementsInt = true; 12712 12713 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12714 EnumConstantDecl *ECD = 12715 cast_or_null<EnumConstantDecl>(Elements[i]); 12716 if (!ECD) continue; // Already issued a diagnostic. 12717 12718 const llvm::APSInt &InitVal = ECD->getInitVal(); 12719 12720 // Keep track of the size of positive and negative values. 12721 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12722 NumPositiveBits = std::max(NumPositiveBits, 12723 (unsigned)InitVal.getActiveBits()); 12724 else 12725 NumNegativeBits = std::max(NumNegativeBits, 12726 (unsigned)InitVal.getMinSignedBits()); 12727 12728 // Keep track of whether every enum element has type int (very commmon). 12729 if (AllElementsInt) 12730 AllElementsInt = ECD->getType() == Context.IntTy; 12731 } 12732 12733 // Figure out the type that should be used for this enum. 12734 QualType BestType; 12735 unsigned BestWidth; 12736 12737 // C++0x N3000 [conv.prom]p3: 12738 // An rvalue of an unscoped enumeration type whose underlying 12739 // type is not fixed can be converted to an rvalue of the first 12740 // of the following types that can represent all the values of 12741 // the enumeration: int, unsigned int, long int, unsigned long 12742 // int, long long int, or unsigned long long int. 12743 // C99 6.4.4.3p2: 12744 // An identifier declared as an enumeration constant has type int. 12745 // The C99 rule is modified by a gcc extension 12746 QualType BestPromotionType; 12747 12748 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 12749 // -fshort-enums is the equivalent to specifying the packed attribute on all 12750 // enum definitions. 12751 if (LangOpts.ShortEnums) 12752 Packed = true; 12753 12754 if (Enum->isFixed()) { 12755 BestType = Enum->getIntegerType(); 12756 if (BestType->isPromotableIntegerType()) 12757 BestPromotionType = Context.getPromotedIntegerType(BestType); 12758 else 12759 BestPromotionType = BestType; 12760 // We don't need to set BestWidth, because BestType is going to be the type 12761 // of the enumerators, but we do anyway because otherwise some compilers 12762 // warn that it might be used uninitialized. 12763 BestWidth = CharWidth; 12764 } 12765 else if (NumNegativeBits) { 12766 // If there is a negative value, figure out the smallest integer type (of 12767 // int/long/longlong) that fits. 12768 // If it's packed, check also if it fits a char or a short. 12769 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12770 BestType = Context.SignedCharTy; 12771 BestWidth = CharWidth; 12772 } else if (Packed && NumNegativeBits <= ShortWidth && 12773 NumPositiveBits < ShortWidth) { 12774 BestType = Context.ShortTy; 12775 BestWidth = ShortWidth; 12776 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12777 BestType = Context.IntTy; 12778 BestWidth = IntWidth; 12779 } else { 12780 BestWidth = Context.getTargetInfo().getLongWidth(); 12781 12782 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12783 BestType = Context.LongTy; 12784 } else { 12785 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12786 12787 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12788 Diag(Enum->getLocation(), diag::warn_enum_too_large); 12789 BestType = Context.LongLongTy; 12790 } 12791 } 12792 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12793 } else { 12794 // If there is no negative value, figure out the smallest type that fits 12795 // all of the enumerator values. 12796 // If it's packed, check also if it fits a char or a short. 12797 if (Packed && NumPositiveBits <= CharWidth) { 12798 BestType = Context.UnsignedCharTy; 12799 BestPromotionType = Context.IntTy; 12800 BestWidth = CharWidth; 12801 } else if (Packed && NumPositiveBits <= ShortWidth) { 12802 BestType = Context.UnsignedShortTy; 12803 BestPromotionType = Context.IntTy; 12804 BestWidth = ShortWidth; 12805 } else if (NumPositiveBits <= IntWidth) { 12806 BestType = Context.UnsignedIntTy; 12807 BestWidth = IntWidth; 12808 BestPromotionType 12809 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12810 ? Context.UnsignedIntTy : Context.IntTy; 12811 } else if (NumPositiveBits <= 12812 (BestWidth = Context.getTargetInfo().getLongWidth())) { 12813 BestType = Context.UnsignedLongTy; 12814 BestPromotionType 12815 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12816 ? Context.UnsignedLongTy : Context.LongTy; 12817 } else { 12818 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12819 assert(NumPositiveBits <= BestWidth && 12820 "How could an initializer get larger than ULL?"); 12821 BestType = Context.UnsignedLongLongTy; 12822 BestPromotionType 12823 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12824 ? Context.UnsignedLongLongTy : Context.LongLongTy; 12825 } 12826 } 12827 12828 // Loop over all of the enumerator constants, changing their types to match 12829 // the type of the enum if needed. 12830 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12831 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12832 if (!ECD) continue; // Already issued a diagnostic. 12833 12834 // Standard C says the enumerators have int type, but we allow, as an 12835 // extension, the enumerators to be larger than int size. If each 12836 // enumerator value fits in an int, type it as an int, otherwise type it the 12837 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 12838 // that X has type 'int', not 'unsigned'. 12839 12840 // Determine whether the value fits into an int. 12841 llvm::APSInt InitVal = ECD->getInitVal(); 12842 12843 // If it fits into an integer type, force it. Otherwise force it to match 12844 // the enum decl type. 12845 QualType NewTy; 12846 unsigned NewWidth; 12847 bool NewSign; 12848 if (!getLangOpts().CPlusPlus && 12849 !Enum->isFixed() && 12850 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 12851 NewTy = Context.IntTy; 12852 NewWidth = IntWidth; 12853 NewSign = true; 12854 } else if (ECD->getType() == BestType) { 12855 // Already the right type! 12856 if (getLangOpts().CPlusPlus) 12857 // C++ [dcl.enum]p4: Following the closing brace of an 12858 // enum-specifier, each enumerator has the type of its 12859 // enumeration. 12860 ECD->setType(EnumType); 12861 continue; 12862 } else { 12863 NewTy = BestType; 12864 NewWidth = BestWidth; 12865 NewSign = BestType->isSignedIntegerOrEnumerationType(); 12866 } 12867 12868 // Adjust the APSInt value. 12869 InitVal = InitVal.extOrTrunc(NewWidth); 12870 InitVal.setIsSigned(NewSign); 12871 ECD->setInitVal(InitVal); 12872 12873 // Adjust the Expr initializer and type. 12874 if (ECD->getInitExpr() && 12875 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 12876 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 12877 CK_IntegralCast, 12878 ECD->getInitExpr(), 12879 /*base paths*/ 0, 12880 VK_RValue)); 12881 if (getLangOpts().CPlusPlus) 12882 // C++ [dcl.enum]p4: Following the closing brace of an 12883 // enum-specifier, each enumerator has the type of its 12884 // enumeration. 12885 ECD->setType(EnumType); 12886 else 12887 ECD->setType(NewTy); 12888 } 12889 12890 Enum->completeDefinition(BestType, BestPromotionType, 12891 NumPositiveBits, NumNegativeBits); 12892 12893 // If we're declaring a function, ensure this decl isn't forgotten about - 12894 // it needs to go into the function scope. 12895 if (InFunctionDeclarator) 12896 DeclsInPrototypeScope.push_back(Enum); 12897 12898 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 12899 12900 // Now that the enum type is defined, ensure it's not been underaligned. 12901 if (Enum->hasAttrs()) 12902 CheckAlignasUnderalignment(Enum); 12903 } 12904 12905 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 12906 SourceLocation StartLoc, 12907 SourceLocation EndLoc) { 12908 StringLiteral *AsmString = cast<StringLiteral>(expr); 12909 12910 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 12911 AsmString, StartLoc, 12912 EndLoc); 12913 CurContext->addDecl(New); 12914 return New; 12915 } 12916 12917 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 12918 SourceLocation ImportLoc, 12919 ModuleIdPath Path) { 12920 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 12921 Module::AllVisible, 12922 /*IsIncludeDirective=*/false); 12923 if (!Mod) 12924 return true; 12925 12926 SmallVector<SourceLocation, 2> IdentifierLocs; 12927 Module *ModCheck = Mod; 12928 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 12929 // If we've run out of module parents, just drop the remaining identifiers. 12930 // We need the length to be consistent. 12931 if (!ModCheck) 12932 break; 12933 ModCheck = ModCheck->Parent; 12934 12935 IdentifierLocs.push_back(Path[I].second); 12936 } 12937 12938 ImportDecl *Import = ImportDecl::Create(Context, 12939 Context.getTranslationUnitDecl(), 12940 AtLoc.isValid()? AtLoc : ImportLoc, 12941 Mod, IdentifierLocs); 12942 Context.getTranslationUnitDecl()->addDecl(Import); 12943 return Import; 12944 } 12945 12946 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 12947 // FIXME: Should we synthesize an ImportDecl here? 12948 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 12949 /*Complain=*/true); 12950 } 12951 12952 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 12953 // Create the implicit import declaration. 12954 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 12955 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 12956 Loc, Mod, Loc); 12957 TU->addDecl(ImportD); 12958 Consumer.HandleImplicitImportDecl(ImportD); 12959 12960 // Make the module visible. 12961 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 12962 /*Complain=*/false); 12963 } 12964 12965 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 12966 IdentifierInfo* AliasName, 12967 SourceLocation PragmaLoc, 12968 SourceLocation NameLoc, 12969 SourceLocation AliasNameLoc) { 12970 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 12971 LookupOrdinaryName); 12972 AsmLabelAttr *Attr = 12973 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 12974 12975 if (PrevDecl) 12976 PrevDecl->addAttr(Attr); 12977 else 12978 (void)ExtnameUndeclaredIdentifiers.insert( 12979 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 12980 } 12981 12982 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 12983 SourceLocation PragmaLoc, 12984 SourceLocation NameLoc) { 12985 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 12986 12987 if (PrevDecl) { 12988 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 12989 } else { 12990 (void)WeakUndeclaredIdentifiers.insert( 12991 std::pair<IdentifierInfo*,WeakInfo> 12992 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 12993 } 12994 } 12995 12996 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 12997 IdentifierInfo* AliasName, 12998 SourceLocation PragmaLoc, 12999 SourceLocation NameLoc, 13000 SourceLocation AliasNameLoc) { 13001 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13002 LookupOrdinaryName); 13003 WeakInfo W = WeakInfo(Name, NameLoc); 13004 13005 if (PrevDecl) { 13006 if (!PrevDecl->hasAttr<AliasAttr>()) 13007 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13008 DeclApplyPragmaWeak(TUScope, ND, W); 13009 } else { 13010 (void)WeakUndeclaredIdentifiers.insert( 13011 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13012 } 13013 } 13014 13015 Decl *Sema::getObjCDeclContext() const { 13016 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13017 } 13018 13019 AvailabilityResult Sema::getCurContextAvailability() const { 13020 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13021 // If we are within an Objective-C method, we should consult 13022 // both the availability of the method as well as the 13023 // enclosing class. If the class is (say) deprecated, 13024 // the entire method is considered deprecated from the 13025 // purpose of checking if the current context is deprecated. 13026 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13027 AvailabilityResult R = MD->getAvailability(); 13028 if (R != AR_Available) 13029 return R; 13030 D = MD->getClassInterface(); 13031 } 13032 // If we are within an Objective-c @implementation, it 13033 // gets the same availability context as the @interface. 13034 else if (const ObjCImplementationDecl *ID = 13035 dyn_cast<ObjCImplementationDecl>(D)) { 13036 D = ID->getClassInterface(); 13037 } 13038 return D->getAvailability(); 13039 } 13040