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 bool AllowTemplates=false) 67 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 68 AllowClassTemplates(AllowTemplates) { 69 WantExpressionKeywords = false; 70 WantCXXNamedCasts = false; 71 WantRemainingKeywords = false; 72 } 73 74 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 75 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 76 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 77 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 78 return (IsType || AllowedTemplate) && 79 (AllowInvalidDecl || !ND->isInvalidDecl()); 80 } 81 return !WantClassName && candidate.isKeyword(); 82 } 83 84 private: 85 bool AllowInvalidDecl; 86 bool WantClassName; 87 bool AllowClassTemplates; 88 }; 89 90 } 91 92 /// \brief Determine whether the token kind starts a simple-type-specifier. 93 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 94 switch (Kind) { 95 // FIXME: Take into account the current language when deciding whether a 96 // token kind is a valid type specifier 97 case tok::kw_short: 98 case tok::kw_long: 99 case tok::kw___int64: 100 case tok::kw___int128: 101 case tok::kw_signed: 102 case tok::kw_unsigned: 103 case tok::kw_void: 104 case tok::kw_char: 105 case tok::kw_int: 106 case tok::kw_half: 107 case tok::kw_float: 108 case tok::kw_double: 109 case tok::kw_wchar_t: 110 case tok::kw_bool: 111 case tok::kw___underlying_type: 112 return true; 113 114 case tok::annot_typename: 115 case tok::kw_char16_t: 116 case tok::kw_char32_t: 117 case tok::kw_typeof: 118 case tok::annot_decltype: 119 case tok::kw_decltype: 120 return getLangOpts().CPlusPlus; 121 122 default: 123 break; 124 } 125 126 return false; 127 } 128 129 /// \brief If the identifier refers to a type name within this scope, 130 /// return the declaration of that type. 131 /// 132 /// This routine performs ordinary name lookup of the identifier II 133 /// within the given scope, with optional C++ scope specifier SS, to 134 /// determine whether the name refers to a type. If so, returns an 135 /// opaque pointer (actually a QualType) corresponding to that 136 /// type. Otherwise, returns NULL. 137 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 138 Scope *S, CXXScopeSpec *SS, 139 bool isClassName, bool HasTrailingDot, 140 ParsedType ObjectTypePtr, 141 bool IsCtorOrDtorName, 142 bool WantNontrivialTypeSourceInfo, 143 IdentifierInfo **CorrectedII) { 144 // Determine where we will perform name lookup. 145 DeclContext *LookupCtx = 0; 146 if (ObjectTypePtr) { 147 QualType ObjectType = ObjectTypePtr.get(); 148 if (ObjectType->isRecordType()) 149 LookupCtx = computeDeclContext(ObjectType); 150 } else if (SS && SS->isNotEmpty()) { 151 LookupCtx = computeDeclContext(*SS, false); 152 153 if (!LookupCtx) { 154 if (isDependentScopeSpecifier(*SS)) { 155 // C++ [temp.res]p3: 156 // A qualified-id that refers to a type and in which the 157 // nested-name-specifier depends on a template-parameter (14.6.2) 158 // shall be prefixed by the keyword typename to indicate that the 159 // qualified-id denotes a type, forming an 160 // elaborated-type-specifier (7.1.5.3). 161 // 162 // We therefore do not perform any name lookup if the result would 163 // refer to a member of an unknown specialization. 164 if (!isClassName && !IsCtorOrDtorName) 165 return ParsedType(); 166 167 // We know from the grammar that this name refers to a type, 168 // so build a dependent node to describe the type. 169 if (WantNontrivialTypeSourceInfo) 170 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 171 172 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 173 QualType T = 174 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 175 II, NameLoc); 176 177 return ParsedType::make(T); 178 } 179 180 return ParsedType(); 181 } 182 183 if (!LookupCtx->isDependentContext() && 184 RequireCompleteDeclContext(*SS, LookupCtx)) 185 return ParsedType(); 186 } 187 188 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 189 // lookup for class-names. 190 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 191 LookupOrdinaryName; 192 LookupResult Result(*this, &II, NameLoc, Kind); 193 if (LookupCtx) { 194 // Perform "qualified" name lookup into the declaration context we 195 // computed, which is either the type of the base of a member access 196 // expression or the declaration context associated with a prior 197 // nested-name-specifier. 198 LookupQualifiedName(Result, LookupCtx); 199 200 if (ObjectTypePtr && Result.empty()) { 201 // C++ [basic.lookup.classref]p3: 202 // If the unqualified-id is ~type-name, the type-name is looked up 203 // in the context of the entire postfix-expression. If the type T of 204 // the object expression is of a class type C, the type-name is also 205 // looked up in the scope of class C. At least one of the lookups shall 206 // find a name that refers to (possibly cv-qualified) T. 207 LookupName(Result, S); 208 } 209 } else { 210 // Perform unqualified name lookup. 211 LookupName(Result, S); 212 } 213 214 NamedDecl *IIDecl = 0; 215 switch (Result.getResultKind()) { 216 case LookupResult::NotFound: 217 case LookupResult::NotFoundInCurrentInstantiation: 218 if (CorrectedII) { 219 TypeNameValidatorCCC Validator(true, isClassName); 220 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 221 Kind, S, SS, Validator); 222 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 223 TemplateTy Template; 224 bool MemberOfUnknownSpecialization; 225 UnqualifiedId TemplateName; 226 TemplateName.setIdentifier(NewII, NameLoc); 227 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 228 CXXScopeSpec NewSS, *NewSSPtr = SS; 229 if (SS && NNS) { 230 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 231 NewSSPtr = &NewSS; 232 } 233 if (Correction && (NNS || NewII != &II) && 234 // Ignore a correction to a template type as the to-be-corrected 235 // identifier is not a template (typo correction for template names 236 // is handled elsewhere). 237 !(getLangOpts().CPlusPlus && NewSSPtr && 238 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 239 false, Template, MemberOfUnknownSpecialization))) { 240 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 241 isClassName, HasTrailingDot, ObjectTypePtr, 242 IsCtorOrDtorName, 243 WantNontrivialTypeSourceInfo); 244 if (Ty) { 245 diagnoseTypo(Correction, 246 PDiag(diag::err_unknown_type_or_class_name_suggest) 247 << Result.getLookupName() << isClassName); 248 if (SS && NNS) 249 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 250 *CorrectedII = NewII; 251 return Ty; 252 } 253 } 254 } 255 // If typo correction failed or was not performed, fall through 256 case LookupResult::FoundOverloaded: 257 case LookupResult::FoundUnresolvedValue: 258 Result.suppressDiagnostics(); 259 return ParsedType(); 260 261 case LookupResult::Ambiguous: 262 // Recover from type-hiding ambiguities by hiding the type. We'll 263 // do the lookup again when looking for an object, and we can 264 // diagnose the error then. If we don't do this, then the error 265 // about hiding the type will be immediately followed by an error 266 // that only makes sense if the identifier was treated like a type. 267 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 268 Result.suppressDiagnostics(); 269 return ParsedType(); 270 } 271 272 // Look to see if we have a type anywhere in the list of results. 273 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 274 Res != ResEnd; ++Res) { 275 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 276 if (!IIDecl || 277 (*Res)->getLocation().getRawEncoding() < 278 IIDecl->getLocation().getRawEncoding()) 279 IIDecl = *Res; 280 } 281 } 282 283 if (!IIDecl) { 284 // None of the entities we found is a type, so there is no way 285 // to even assume that the result is a type. In this case, don't 286 // complain about the ambiguity. The parser will either try to 287 // perform this lookup again (e.g., as an object name), which 288 // will produce the ambiguity, or will complain that it expected 289 // a type name. 290 Result.suppressDiagnostics(); 291 return ParsedType(); 292 } 293 294 // We found a type within the ambiguous lookup; diagnose the 295 // ambiguity and then return that type. This might be the right 296 // answer, or it might not be, but it suppresses any attempt to 297 // perform the name lookup again. 298 break; 299 300 case LookupResult::Found: 301 IIDecl = Result.getFoundDecl(); 302 break; 303 } 304 305 assert(IIDecl && "Didn't find decl"); 306 307 QualType T; 308 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 309 DiagnoseUseOfDecl(IIDecl, NameLoc); 310 311 if (T.isNull()) 312 T = Context.getTypeDeclType(TD); 313 314 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 315 // constructor or destructor name (in such a case, the scope specifier 316 // will be attached to the enclosing Expr or Decl node). 317 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 318 if (WantNontrivialTypeSourceInfo) { 319 // Construct a type with type-source information. 320 TypeLocBuilder Builder; 321 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 322 323 T = getElaboratedType(ETK_None, *SS, T); 324 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 325 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 326 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 327 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 328 } else { 329 T = getElaboratedType(ETK_None, *SS, T); 330 } 331 } 332 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 333 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 334 if (!HasTrailingDot) 335 T = Context.getObjCInterfaceType(IDecl); 336 } 337 338 if (T.isNull()) { 339 // If it's not plausibly a type, suppress diagnostics. 340 Result.suppressDiagnostics(); 341 return ParsedType(); 342 } 343 return ParsedType::make(T); 344 } 345 346 /// isTagName() - This method is called *for error recovery purposes only* 347 /// to determine if the specified name is a valid tag name ("struct foo"). If 348 /// so, this returns the TST for the tag corresponding to it (TST_enum, 349 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 350 /// cases in C where the user forgot to specify the tag. 351 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 352 // Do a tag name lookup in this scope. 353 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 354 LookupName(R, S, false); 355 R.suppressDiagnostics(); 356 if (R.getResultKind() == LookupResult::Found) 357 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 358 switch (TD->getTagKind()) { 359 case TTK_Struct: return DeclSpec::TST_struct; 360 case TTK_Interface: return DeclSpec::TST_interface; 361 case TTK_Union: return DeclSpec::TST_union; 362 case TTK_Class: return DeclSpec::TST_class; 363 case TTK_Enum: return DeclSpec::TST_enum; 364 } 365 } 366 367 return DeclSpec::TST_unspecified; 368 } 369 370 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 371 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 372 /// then downgrade the missing typename error to a warning. 373 /// This is needed for MSVC compatibility; Example: 374 /// @code 375 /// template<class T> class A { 376 /// public: 377 /// typedef int TYPE; 378 /// }; 379 /// template<class T> class B : public A<T> { 380 /// public: 381 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 382 /// }; 383 /// @endcode 384 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 385 if (CurContext->isRecord()) { 386 const Type *Ty = SS->getScopeRep()->getAsType(); 387 388 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 389 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 390 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 391 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 392 return true; 393 return S->isFunctionPrototypeScope(); 394 } 395 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 396 } 397 398 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 399 SourceLocation IILoc, 400 Scope *S, 401 CXXScopeSpec *SS, 402 ParsedType &SuggestedType, 403 bool AllowClassTemplates) { 404 // We don't have anything to suggest (yet). 405 SuggestedType = ParsedType(); 406 407 // There may have been a typo in the name of the type. Look up typo 408 // results, in case we have something that we can suggest. 409 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 410 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 411 LookupOrdinaryName, S, SS, 412 Validator)) { 413 if (Corrected.isKeyword()) { 414 // We corrected to a keyword. 415 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 416 II = Corrected.getCorrectionAsIdentifierInfo(); 417 } else { 418 // We found a similarly-named type or interface; suggest that. 419 if (!SS || !SS->isSet()) { 420 diagnoseTypo(Corrected, 421 PDiag(diag::err_unknown_typename_suggest) << II); 422 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 423 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 424 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 425 II->getName().equals(CorrectedStr); 426 diagnoseTypo(Corrected, 427 PDiag(diag::err_unknown_nested_typename_suggest) 428 << II << DC << DroppedSpecifier << SS->getRange()); 429 } else { 430 llvm_unreachable("could not have corrected a typo here"); 431 } 432 433 CXXScopeSpec tmpSS; 434 if (Corrected.getCorrectionSpecifier()) 435 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 436 SourceRange(IILoc)); 437 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 438 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 439 false, ParsedType(), 440 /*IsCtorOrDtorName=*/false, 441 /*NonTrivialTypeSourceInfo=*/true); 442 } 443 return true; 444 } 445 446 if (getLangOpts().CPlusPlus) { 447 // See if II is a class template that the user forgot to pass arguments to. 448 UnqualifiedId Name; 449 Name.setIdentifier(II, IILoc); 450 CXXScopeSpec EmptySS; 451 TemplateTy TemplateResult; 452 bool MemberOfUnknownSpecialization; 453 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 454 Name, ParsedType(), true, TemplateResult, 455 MemberOfUnknownSpecialization) == TNK_Type_template) { 456 TemplateName TplName = TemplateResult.get(); 457 Diag(IILoc, diag::err_template_missing_args) << TplName; 458 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 459 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 460 << TplDecl->getTemplateParameters()->getSourceRange(); 461 } 462 return true; 463 } 464 } 465 466 // FIXME: Should we move the logic that tries to recover from a missing tag 467 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 468 469 if (!SS || (!SS->isSet() && !SS->isInvalid())) 470 Diag(IILoc, diag::err_unknown_typename) << II; 471 else if (DeclContext *DC = computeDeclContext(*SS, false)) 472 Diag(IILoc, diag::err_typename_nested_not_found) 473 << II << DC << SS->getRange(); 474 else if (isDependentScopeSpecifier(*SS)) { 475 unsigned DiagID = diag::err_typename_missing; 476 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 477 DiagID = diag::warn_typename_missing; 478 479 Diag(SS->getRange().getBegin(), DiagID) 480 << SS->getScopeRep() << II->getName() 481 << SourceRange(SS->getRange().getBegin(), IILoc) 482 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 483 SuggestedType = ActOnTypenameType(S, SourceLocation(), 484 *SS, *II, IILoc).get(); 485 } else { 486 assert(SS && SS->isInvalid() && 487 "Invalid scope specifier has already been diagnosed"); 488 } 489 490 return true; 491 } 492 493 /// \brief Determine whether the given result set contains either a type name 494 /// or 495 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 496 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 497 NextToken.is(tok::less); 498 499 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 500 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 501 return true; 502 503 if (CheckTemplate && isa<TemplateDecl>(*I)) 504 return true; 505 } 506 507 return false; 508 } 509 510 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 511 Scope *S, CXXScopeSpec &SS, 512 IdentifierInfo *&Name, 513 SourceLocation NameLoc) { 514 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 515 SemaRef.LookupParsedName(R, S, &SS); 516 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 517 const char *TagName = 0; 518 const char *FixItTagName = 0; 519 switch (Tag->getTagKind()) { 520 case TTK_Class: 521 TagName = "class"; 522 FixItTagName = "class "; 523 break; 524 525 case TTK_Enum: 526 TagName = "enum"; 527 FixItTagName = "enum "; 528 break; 529 530 case TTK_Struct: 531 TagName = "struct"; 532 FixItTagName = "struct "; 533 break; 534 535 case TTK_Interface: 536 TagName = "__interface"; 537 FixItTagName = "__interface "; 538 break; 539 540 case TTK_Union: 541 TagName = "union"; 542 FixItTagName = "union "; 543 break; 544 } 545 546 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 547 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 548 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 549 550 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 551 I != IEnd; ++I) 552 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 553 << Name << TagName; 554 555 // Replace lookup results with just the tag decl. 556 Result.clear(Sema::LookupTagName); 557 SemaRef.LookupParsedName(Result, S, &SS); 558 return true; 559 } 560 561 return false; 562 } 563 564 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 565 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 566 QualType T, SourceLocation NameLoc) { 567 ASTContext &Context = S.Context; 568 569 TypeLocBuilder Builder; 570 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 571 572 T = S.getElaboratedType(ETK_None, SS, T); 573 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 574 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 575 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 576 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 577 } 578 579 Sema::NameClassification Sema::ClassifyName(Scope *S, 580 CXXScopeSpec &SS, 581 IdentifierInfo *&Name, 582 SourceLocation NameLoc, 583 const Token &NextToken, 584 bool IsAddressOfOperand, 585 CorrectionCandidateCallback *CCC) { 586 DeclarationNameInfo NameInfo(Name, NameLoc); 587 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 588 589 if (NextToken.is(tok::coloncolon)) { 590 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 591 QualType(), false, SS, 0, false); 592 593 } 594 595 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 596 LookupParsedName(Result, S, &SS, !CurMethod); 597 598 // Perform lookup for Objective-C instance variables (including automatically 599 // synthesized instance variables), if we're in an Objective-C method. 600 // FIXME: This lookup really, really needs to be folded in to the normal 601 // unqualified lookup mechanism. 602 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 603 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 604 if (E.get() || E.isInvalid()) 605 return E; 606 } 607 608 bool SecondTry = false; 609 bool IsFilteredTemplateName = false; 610 611 Corrected: 612 switch (Result.getResultKind()) { 613 case LookupResult::NotFound: 614 // If an unqualified-id is followed by a '(', then we have a function 615 // call. 616 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 617 // In C++, this is an ADL-only call. 618 // FIXME: Reference? 619 if (getLangOpts().CPlusPlus) 620 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 621 622 // C90 6.3.2.2: 623 // If the expression that precedes the parenthesized argument list in a 624 // function call consists solely of an identifier, and if no 625 // declaration is visible for this identifier, the identifier is 626 // implicitly declared exactly as if, in the innermost block containing 627 // the function call, the declaration 628 // 629 // extern int identifier (); 630 // 631 // appeared. 632 // 633 // We also allow this in C99 as an extension. 634 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 635 Result.addDecl(D); 636 Result.resolveKind(); 637 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 638 } 639 } 640 641 // In C, we first see whether there is a tag type by the same name, in 642 // which case it's likely that the user just forget to write "enum", 643 // "struct", or "union". 644 if (!getLangOpts().CPlusPlus && !SecondTry && 645 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 646 break; 647 } 648 649 // Perform typo correction to determine if there is another name that is 650 // close to this name. 651 if (!SecondTry && CCC) { 652 SecondTry = true; 653 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 654 Result.getLookupKind(), S, 655 &SS, *CCC)) { 656 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 657 unsigned QualifiedDiag = diag::err_no_member_suggest; 658 659 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 660 NamedDecl *UnderlyingFirstDecl 661 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 662 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 663 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 664 UnqualifiedDiag = diag::err_no_template_suggest; 665 QualifiedDiag = diag::err_no_member_template_suggest; 666 } else if (UnderlyingFirstDecl && 667 (isa<TypeDecl>(UnderlyingFirstDecl) || 668 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 669 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 670 UnqualifiedDiag = diag::err_unknown_typename_suggest; 671 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 672 } 673 674 if (SS.isEmpty()) { 675 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 676 } else {// FIXME: is this even reachable? Test it. 677 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 678 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 679 Name->getName().equals(CorrectedStr); 680 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 681 << Name << computeDeclContext(SS, false) 682 << DroppedSpecifier << SS.getRange()); 683 } 684 685 // Update the name, so that the caller has the new name. 686 Name = Corrected.getCorrectionAsIdentifierInfo(); 687 688 // Typo correction corrected to a keyword. 689 if (Corrected.isKeyword()) 690 return Name; 691 692 // Also update the LookupResult... 693 // FIXME: This should probably go away at some point 694 Result.clear(); 695 Result.setLookupName(Corrected.getCorrection()); 696 if (FirstDecl) 697 Result.addDecl(FirstDecl); 698 699 // If we found an Objective-C instance variable, let 700 // LookupInObjCMethod build the appropriate expression to 701 // reference the ivar. 702 // FIXME: This is a gross hack. 703 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 704 Result.clear(); 705 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 706 return E; 707 } 708 709 goto Corrected; 710 } 711 } 712 713 // We failed to correct; just fall through and let the parser deal with it. 714 Result.suppressDiagnostics(); 715 return NameClassification::Unknown(); 716 717 case LookupResult::NotFoundInCurrentInstantiation: { 718 // We performed name lookup into the current instantiation, and there were 719 // dependent bases, so we treat this result the same way as any other 720 // dependent nested-name-specifier. 721 722 // C++ [temp.res]p2: 723 // A name used in a template declaration or definition and that is 724 // dependent on a template-parameter is assumed not to name a type 725 // unless the applicable name lookup finds a type name or the name is 726 // qualified by the keyword typename. 727 // 728 // FIXME: If the next token is '<', we might want to ask the parser to 729 // perform some heroics to see if we actually have a 730 // template-argument-list, which would indicate a missing 'template' 731 // keyword here. 732 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 733 NameInfo, IsAddressOfOperand, 734 /*TemplateArgs=*/0); 735 } 736 737 case LookupResult::Found: 738 case LookupResult::FoundOverloaded: 739 case LookupResult::FoundUnresolvedValue: 740 break; 741 742 case LookupResult::Ambiguous: 743 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 744 hasAnyAcceptableTemplateNames(Result)) { 745 // C++ [temp.local]p3: 746 // A lookup that finds an injected-class-name (10.2) can result in an 747 // ambiguity in certain cases (for example, if it is found in more than 748 // one base class). If all of the injected-class-names that are found 749 // refer to specializations of the same class template, and if the name 750 // is followed by a template-argument-list, the reference refers to the 751 // class template itself and not a specialization thereof, and is not 752 // ambiguous. 753 // 754 // This filtering can make an ambiguous result into an unambiguous one, 755 // so try again after filtering out template names. 756 FilterAcceptableTemplateNames(Result); 757 if (!Result.isAmbiguous()) { 758 IsFilteredTemplateName = true; 759 break; 760 } 761 } 762 763 // Diagnose the ambiguity and return an error. 764 return NameClassification::Error(); 765 } 766 767 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 768 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 769 // C++ [temp.names]p3: 770 // After name lookup (3.4) finds that a name is a template-name or that 771 // an operator-function-id or a literal- operator-id refers to a set of 772 // overloaded functions any member of which is a function template if 773 // this is followed by a <, the < is always taken as the delimiter of a 774 // template-argument-list and never as the less-than operator. 775 if (!IsFilteredTemplateName) 776 FilterAcceptableTemplateNames(Result); 777 778 if (!Result.empty()) { 779 bool IsFunctionTemplate; 780 bool IsVarTemplate; 781 TemplateName Template; 782 if (Result.end() - Result.begin() > 1) { 783 IsFunctionTemplate = true; 784 Template = Context.getOverloadedTemplateName(Result.begin(), 785 Result.end()); 786 } else { 787 TemplateDecl *TD 788 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 789 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 790 IsVarTemplate = isa<VarTemplateDecl>(TD); 791 792 if (SS.isSet() && !SS.isInvalid()) 793 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 794 /*TemplateKeyword=*/false, 795 TD); 796 else 797 Template = TemplateName(TD); 798 } 799 800 if (IsFunctionTemplate) { 801 // Function templates always go through overload resolution, at which 802 // point we'll perform the various checks (e.g., accessibility) we need 803 // to based on which function we selected. 804 Result.suppressDiagnostics(); 805 806 return NameClassification::FunctionTemplate(Template); 807 } 808 809 return IsVarTemplate ? NameClassification::VarTemplate(Template) 810 : NameClassification::TypeTemplate(Template); 811 } 812 } 813 814 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 815 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 816 DiagnoseUseOfDecl(Type, NameLoc); 817 QualType T = Context.getTypeDeclType(Type); 818 if (SS.isNotEmpty()) 819 return buildNestedType(*this, SS, T, NameLoc); 820 return ParsedType::make(T); 821 } 822 823 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 824 if (!Class) { 825 // FIXME: It's unfortunate that we don't have a Type node for handling this. 826 if (ObjCCompatibleAliasDecl *Alias 827 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 828 Class = Alias->getClassInterface(); 829 } 830 831 if (Class) { 832 DiagnoseUseOfDecl(Class, NameLoc); 833 834 if (NextToken.is(tok::period)) { 835 // Interface. <something> is parsed as a property reference expression. 836 // Just return "unknown" as a fall-through for now. 837 Result.suppressDiagnostics(); 838 return NameClassification::Unknown(); 839 } 840 841 QualType T = Context.getObjCInterfaceType(Class); 842 return ParsedType::make(T); 843 } 844 845 // We can have a type template here if we're classifying a template argument. 846 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 847 return NameClassification::TypeTemplate( 848 TemplateName(cast<TemplateDecl>(FirstDecl))); 849 850 // Check for a tag type hidden by a non-type decl in a few cases where it 851 // seems likely a type is wanted instead of the non-type that was found. 852 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 853 if ((NextToken.is(tok::identifier) || 854 (NextIsOp && 855 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 856 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 857 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 858 DiagnoseUseOfDecl(Type, NameLoc); 859 QualType T = Context.getTypeDeclType(Type); 860 if (SS.isNotEmpty()) 861 return buildNestedType(*this, SS, T, NameLoc); 862 return ParsedType::make(T); 863 } 864 865 if (FirstDecl->isCXXClassMember()) 866 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 867 868 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 869 return BuildDeclarationNameExpr(SS, Result, ADL); 870 } 871 872 // Determines the context to return to after temporarily entering a 873 // context. This depends in an unnecessarily complicated way on the 874 // exact ordering of callbacks from the parser. 875 DeclContext *Sema::getContainingDC(DeclContext *DC) { 876 877 // Functions defined inline within classes aren't parsed until we've 878 // finished parsing the top-level class, so the top-level class is 879 // the context we'll need to return to. 880 // A Lambda call operator whose parent is a class must not be treated 881 // as an inline member function. A Lambda can be used legally 882 // either as an in-class member initializer or a default argument. These 883 // are parsed once the class has been marked complete and so the containing 884 // context would be the nested class (when the lambda is defined in one); 885 // If the class is not complete, then the lambda is being used in an 886 // ill-formed fashion (such as to specify the width of a bit-field, or 887 // in an array-bound) - in which case we still want to return the 888 // lexically containing DC (which could be a nested class). 889 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 890 DC = DC->getLexicalParent(); 891 892 // A function not defined within a class will always return to its 893 // lexical context. 894 if (!isa<CXXRecordDecl>(DC)) 895 return DC; 896 897 // A C++ inline method/friend is parsed *after* the topmost class 898 // it was declared in is fully parsed ("complete"); the topmost 899 // class is the context we need to return to. 900 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 901 DC = RD; 902 903 // Return the declaration context of the topmost class the inline method is 904 // declared in. 905 return DC; 906 } 907 908 return DC->getLexicalParent(); 909 } 910 911 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 912 assert(getContainingDC(DC) == CurContext && 913 "The next DeclContext should be lexically contained in the current one."); 914 CurContext = DC; 915 S->setEntity(DC); 916 } 917 918 void Sema::PopDeclContext() { 919 assert(CurContext && "DeclContext imbalance!"); 920 921 CurContext = getContainingDC(CurContext); 922 assert(CurContext && "Popped translation unit!"); 923 } 924 925 /// EnterDeclaratorContext - Used when we must lookup names in the context 926 /// of a declarator's nested name specifier. 927 /// 928 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 929 // C++0x [basic.lookup.unqual]p13: 930 // A name used in the definition of a static data member of class 931 // X (after the qualified-id of the static member) is looked up as 932 // if the name was used in a member function of X. 933 // C++0x [basic.lookup.unqual]p14: 934 // If a variable member of a namespace is defined outside of the 935 // scope of its namespace then any name used in the definition of 936 // the variable member (after the declarator-id) is looked up as 937 // if the definition of the variable member occurred in its 938 // namespace. 939 // Both of these imply that we should push a scope whose context 940 // is the semantic context of the declaration. We can't use 941 // PushDeclContext here because that context is not necessarily 942 // lexically contained in the current context. Fortunately, 943 // the containing scope should have the appropriate information. 944 945 assert(!S->getEntity() && "scope already has entity"); 946 947 #ifndef NDEBUG 948 Scope *Ancestor = S->getParent(); 949 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 950 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 951 #endif 952 953 CurContext = DC; 954 S->setEntity(DC); 955 } 956 957 void Sema::ExitDeclaratorContext(Scope *S) { 958 assert(S->getEntity() == CurContext && "Context imbalance!"); 959 960 // Switch back to the lexical context. The safety of this is 961 // enforced by an assert in EnterDeclaratorContext. 962 Scope *Ancestor = S->getParent(); 963 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 964 CurContext = Ancestor->getEntity(); 965 966 // We don't need to do anything with the scope, which is going to 967 // disappear. 968 } 969 970 971 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 972 // We assume that the caller has already called 973 // ActOnReenterTemplateScope so getTemplatedDecl() works. 974 FunctionDecl *FD = D->getAsFunction(); 975 if (!FD) 976 return; 977 978 // Same implementation as PushDeclContext, but enters the context 979 // from the lexical parent, rather than the top-level class. 980 assert(CurContext == FD->getLexicalParent() && 981 "The next DeclContext should be lexically contained in the current one."); 982 CurContext = FD; 983 S->setEntity(CurContext); 984 985 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 986 ParmVarDecl *Param = FD->getParamDecl(P); 987 // If the parameter has an identifier, then add it to the scope 988 if (Param->getIdentifier()) { 989 S->AddDecl(Param); 990 IdResolver.AddDecl(Param); 991 } 992 } 993 } 994 995 996 void Sema::ActOnExitFunctionContext() { 997 // Same implementation as PopDeclContext, but returns to the lexical parent, 998 // rather than the top-level class. 999 assert(CurContext && "DeclContext imbalance!"); 1000 CurContext = CurContext->getLexicalParent(); 1001 assert(CurContext && "Popped translation unit!"); 1002 } 1003 1004 1005 /// \brief Determine whether we allow overloading of the function 1006 /// PrevDecl with another declaration. 1007 /// 1008 /// This routine determines whether overloading is possible, not 1009 /// whether some new function is actually an overload. It will return 1010 /// true in C++ (where we can always provide overloads) or, as an 1011 /// extension, in C when the previous function is already an 1012 /// overloaded function declaration or has the "overloadable" 1013 /// attribute. 1014 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1015 ASTContext &Context) { 1016 if (Context.getLangOpts().CPlusPlus) 1017 return true; 1018 1019 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1020 return true; 1021 1022 return (Previous.getResultKind() == LookupResult::Found 1023 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1024 } 1025 1026 /// Add this decl to the scope shadowed decl chains. 1027 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1028 // Move up the scope chain until we find the nearest enclosing 1029 // non-transparent context. The declaration will be introduced into this 1030 // scope. 1031 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1032 S = S->getParent(); 1033 1034 // Add scoped declarations into their context, so that they can be 1035 // found later. Declarations without a context won't be inserted 1036 // into any context. 1037 if (AddToContext) 1038 CurContext->addDecl(D); 1039 1040 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1041 // are function-local declarations. 1042 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1043 !D->getDeclContext()->getRedeclContext()->Equals( 1044 D->getLexicalDeclContext()->getRedeclContext()) && 1045 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1046 return; 1047 1048 // Template instantiations should also not be pushed into scope. 1049 if (isa<FunctionDecl>(D) && 1050 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1051 return; 1052 1053 // If this replaces anything in the current scope, 1054 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1055 IEnd = IdResolver.end(); 1056 for (; I != IEnd; ++I) { 1057 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1058 S->RemoveDecl(*I); 1059 IdResolver.RemoveDecl(*I); 1060 1061 // Should only need to replace one decl. 1062 break; 1063 } 1064 } 1065 1066 S->AddDecl(D); 1067 1068 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1069 // Implicitly-generated labels may end up getting generated in an order that 1070 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1071 // the label at the appropriate place in the identifier chain. 1072 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1073 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1074 if (IDC == CurContext) { 1075 if (!S->isDeclScope(*I)) 1076 continue; 1077 } else if (IDC->Encloses(CurContext)) 1078 break; 1079 } 1080 1081 IdResolver.InsertDeclAfter(I, D); 1082 } else { 1083 IdResolver.AddDecl(D); 1084 } 1085 } 1086 1087 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1088 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1089 TUScope->AddDecl(D); 1090 } 1091 1092 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1093 bool AllowInlineNamespace) { 1094 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1095 } 1096 1097 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1098 DeclContext *TargetDC = DC->getPrimaryContext(); 1099 do { 1100 if (DeclContext *ScopeDC = S->getEntity()) 1101 if (ScopeDC->getPrimaryContext() == TargetDC) 1102 return S; 1103 } while ((S = S->getParent())); 1104 1105 return 0; 1106 } 1107 1108 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1109 DeclContext*, 1110 ASTContext&); 1111 1112 /// Filters out lookup results that don't fall within the given scope 1113 /// as determined by isDeclInScope. 1114 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1115 bool ConsiderLinkage, 1116 bool AllowInlineNamespace) { 1117 LookupResult::Filter F = R.makeFilter(); 1118 while (F.hasNext()) { 1119 NamedDecl *D = F.next(); 1120 1121 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1122 continue; 1123 1124 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1125 continue; 1126 1127 F.erase(); 1128 } 1129 1130 F.done(); 1131 } 1132 1133 static bool isUsingDecl(NamedDecl *D) { 1134 return isa<UsingShadowDecl>(D) || 1135 isa<UnresolvedUsingTypenameDecl>(D) || 1136 isa<UnresolvedUsingValueDecl>(D); 1137 } 1138 1139 /// Removes using shadow declarations from the lookup results. 1140 static void RemoveUsingDecls(LookupResult &R) { 1141 LookupResult::Filter F = R.makeFilter(); 1142 while (F.hasNext()) 1143 if (isUsingDecl(F.next())) 1144 F.erase(); 1145 1146 F.done(); 1147 } 1148 1149 /// \brief Check for this common pattern: 1150 /// @code 1151 /// class S { 1152 /// S(const S&); // DO NOT IMPLEMENT 1153 /// void operator=(const S&); // DO NOT IMPLEMENT 1154 /// }; 1155 /// @endcode 1156 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1157 // FIXME: Should check for private access too but access is set after we get 1158 // the decl here. 1159 if (D->doesThisDeclarationHaveABody()) 1160 return false; 1161 1162 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1163 return CD->isCopyConstructor(); 1164 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1165 return Method->isCopyAssignmentOperator(); 1166 return false; 1167 } 1168 1169 // We need this to handle 1170 // 1171 // typedef struct { 1172 // void *foo() { return 0; } 1173 // } A; 1174 // 1175 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1176 // for example. If 'A', foo will have external linkage. If we have '*A', 1177 // foo will have no linkage. Since we can't know until we get to the end 1178 // of the typedef, this function finds out if D might have non-external linkage. 1179 // Callers should verify at the end of the TU if it D has external linkage or 1180 // not. 1181 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1182 const DeclContext *DC = D->getDeclContext(); 1183 while (!DC->isTranslationUnit()) { 1184 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1185 if (!RD->hasNameForLinkage()) 1186 return true; 1187 } 1188 DC = DC->getParent(); 1189 } 1190 1191 return !D->isExternallyVisible(); 1192 } 1193 1194 // FIXME: This needs to be refactored; some other isInMainFile users want 1195 // these semantics. 1196 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1197 if (S.TUKind != TU_Complete) 1198 return false; 1199 return S.SourceMgr.isInMainFile(Loc); 1200 } 1201 1202 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1203 assert(D); 1204 1205 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1206 return false; 1207 1208 // Ignore class templates. 1209 if (D->getDeclContext()->isDependentContext() || 1210 D->getLexicalDeclContext()->isDependentContext()) 1211 return false; 1212 1213 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1214 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1215 return false; 1216 1217 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1218 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1219 return false; 1220 } else { 1221 // 'static inline' functions are defined in headers; don't warn. 1222 if (FD->isInlineSpecified() && 1223 !isMainFileLoc(*this, FD->getLocation())) 1224 return false; 1225 } 1226 1227 if (FD->doesThisDeclarationHaveABody() && 1228 Context.DeclMustBeEmitted(FD)) 1229 return false; 1230 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1231 // Constants and utility variables are defined in headers with internal 1232 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1233 // like "inline".) 1234 if (!isMainFileLoc(*this, VD->getLocation())) 1235 return false; 1236 1237 if (Context.DeclMustBeEmitted(VD)) 1238 return false; 1239 1240 if (VD->isStaticDataMember() && 1241 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1242 return false; 1243 } else { 1244 return false; 1245 } 1246 1247 // Only warn for unused decls internal to the translation unit. 1248 return mightHaveNonExternalLinkage(D); 1249 } 1250 1251 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1252 if (!D) 1253 return; 1254 1255 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1256 const FunctionDecl *First = FD->getFirstDecl(); 1257 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1258 return; // First should already be in the vector. 1259 } 1260 1261 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1262 const VarDecl *First = VD->getFirstDecl(); 1263 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1264 return; // First should already be in the vector. 1265 } 1266 1267 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1268 UnusedFileScopedDecls.push_back(D); 1269 } 1270 1271 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1272 if (D->isInvalidDecl()) 1273 return false; 1274 1275 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1276 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1277 return false; 1278 1279 if (isa<LabelDecl>(D)) 1280 return true; 1281 1282 // White-list anything that isn't a local variable. 1283 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1284 !D->getDeclContext()->isFunctionOrMethod()) 1285 return false; 1286 1287 // Types of valid local variables should be complete, so this should succeed. 1288 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1289 1290 // White-list anything with an __attribute__((unused)) type. 1291 QualType Ty = VD->getType(); 1292 1293 // Only look at the outermost level of typedef. 1294 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1295 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1296 return false; 1297 } 1298 1299 // If we failed to complete the type for some reason, or if the type is 1300 // dependent, don't diagnose the variable. 1301 if (Ty->isIncompleteType() || Ty->isDependentType()) 1302 return false; 1303 1304 if (const TagType *TT = Ty->getAs<TagType>()) { 1305 const TagDecl *Tag = TT->getDecl(); 1306 if (Tag->hasAttr<UnusedAttr>()) 1307 return false; 1308 1309 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1310 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1311 return false; 1312 1313 if (const Expr *Init = VD->getInit()) { 1314 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1315 Init = Cleanups->getSubExpr(); 1316 const CXXConstructExpr *Construct = 1317 dyn_cast<CXXConstructExpr>(Init); 1318 if (Construct && !Construct->isElidable()) { 1319 CXXConstructorDecl *CD = Construct->getConstructor(); 1320 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1321 return false; 1322 } 1323 } 1324 } 1325 } 1326 1327 // TODO: __attribute__((unused)) templates? 1328 } 1329 1330 return true; 1331 } 1332 1333 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1334 FixItHint &Hint) { 1335 if (isa<LabelDecl>(D)) { 1336 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1337 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1338 if (AfterColon.isInvalid()) 1339 return; 1340 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1341 getCharRange(D->getLocStart(), AfterColon)); 1342 } 1343 return; 1344 } 1345 1346 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1347 /// unless they are marked attr(unused). 1348 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1349 FixItHint Hint; 1350 if (!ShouldDiagnoseUnusedDecl(D)) 1351 return; 1352 1353 GenerateFixForUnusedDecl(D, Context, Hint); 1354 1355 unsigned DiagID; 1356 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1357 DiagID = diag::warn_unused_exception_param; 1358 else if (isa<LabelDecl>(D)) 1359 DiagID = diag::warn_unused_label; 1360 else 1361 DiagID = diag::warn_unused_variable; 1362 1363 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1364 } 1365 1366 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1367 // Verify that we have no forward references left. If so, there was a goto 1368 // or address of a label taken, but no definition of it. Label fwd 1369 // definitions are indicated with a null substmt. 1370 if (L->getStmt() == 0) 1371 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1372 } 1373 1374 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1375 if (S->decl_empty()) return; 1376 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1377 "Scope shouldn't contain decls!"); 1378 1379 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1380 I != E; ++I) { 1381 Decl *TmpD = (*I); 1382 assert(TmpD && "This decl didn't get pushed??"); 1383 1384 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1385 NamedDecl *D = cast<NamedDecl>(TmpD); 1386 1387 if (!D->getDeclName()) continue; 1388 1389 // Diagnose unused variables in this scope. 1390 if (!S->hasUnrecoverableErrorOccurred()) 1391 DiagnoseUnusedDecl(D); 1392 1393 // If this was a forward reference to a label, verify it was defined. 1394 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1395 CheckPoppedLabel(LD, *this); 1396 1397 // Remove this name from our lexical scope. 1398 IdResolver.RemoveDecl(D); 1399 } 1400 } 1401 1402 /// \brief Look for an Objective-C class in the translation unit. 1403 /// 1404 /// \param Id The name of the Objective-C class we're looking for. If 1405 /// typo-correction fixes this name, the Id will be updated 1406 /// to the fixed name. 1407 /// 1408 /// \param IdLoc The location of the name in the translation unit. 1409 /// 1410 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1411 /// if there is no class with the given name. 1412 /// 1413 /// \returns The declaration of the named Objective-C class, or NULL if the 1414 /// class could not be found. 1415 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1416 SourceLocation IdLoc, 1417 bool DoTypoCorrection) { 1418 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1419 // creation from this context. 1420 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1421 1422 if (!IDecl && DoTypoCorrection) { 1423 // Perform typo correction at the given location, but only if we 1424 // find an Objective-C class name. 1425 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1426 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1427 LookupOrdinaryName, TUScope, NULL, 1428 Validator)) { 1429 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1430 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1431 Id = IDecl->getIdentifier(); 1432 } 1433 } 1434 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1435 // This routine must always return a class definition, if any. 1436 if (Def && Def->getDefinition()) 1437 Def = Def->getDefinition(); 1438 return Def; 1439 } 1440 1441 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1442 /// from S, where a non-field would be declared. This routine copes 1443 /// with the difference between C and C++ scoping rules in structs and 1444 /// unions. For example, the following code is well-formed in C but 1445 /// ill-formed in C++: 1446 /// @code 1447 /// struct S6 { 1448 /// enum { BAR } e; 1449 /// }; 1450 /// 1451 /// void test_S6() { 1452 /// struct S6 a; 1453 /// a.e = BAR; 1454 /// } 1455 /// @endcode 1456 /// For the declaration of BAR, this routine will return a different 1457 /// scope. The scope S will be the scope of the unnamed enumeration 1458 /// within S6. In C++, this routine will return the scope associated 1459 /// with S6, because the enumeration's scope is a transparent 1460 /// context but structures can contain non-field names. In C, this 1461 /// routine will return the translation unit scope, since the 1462 /// enumeration's scope is a transparent context and structures cannot 1463 /// contain non-field names. 1464 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1465 while (((S->getFlags() & Scope::DeclScope) == 0) || 1466 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1467 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1468 S = S->getParent(); 1469 return S; 1470 } 1471 1472 /// \brief Looks up the declaration of "struct objc_super" and 1473 /// saves it for later use in building builtin declaration of 1474 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1475 /// pre-existing declaration exists no action takes place. 1476 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1477 IdentifierInfo *II) { 1478 if (!II->isStr("objc_msgSendSuper")) 1479 return; 1480 ASTContext &Context = ThisSema.Context; 1481 1482 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1483 SourceLocation(), Sema::LookupTagName); 1484 ThisSema.LookupName(Result, S); 1485 if (Result.getResultKind() == LookupResult::Found) 1486 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1487 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1488 } 1489 1490 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1491 /// file scope. lazily create a decl for it. ForRedeclaration is true 1492 /// if we're creating this built-in in anticipation of redeclaring the 1493 /// built-in. 1494 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1495 Scope *S, bool ForRedeclaration, 1496 SourceLocation Loc) { 1497 LookupPredefedObjCSuperType(*this, S, II); 1498 1499 Builtin::ID BID = (Builtin::ID)bid; 1500 1501 ASTContext::GetBuiltinTypeError Error; 1502 QualType R = Context.GetBuiltinType(BID, Error); 1503 switch (Error) { 1504 case ASTContext::GE_None: 1505 // Okay 1506 break; 1507 1508 case ASTContext::GE_Missing_stdio: 1509 if (ForRedeclaration) 1510 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1511 << Context.BuiltinInfo.GetName(BID); 1512 return 0; 1513 1514 case ASTContext::GE_Missing_setjmp: 1515 if (ForRedeclaration) 1516 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1517 << Context.BuiltinInfo.GetName(BID); 1518 return 0; 1519 1520 case ASTContext::GE_Missing_ucontext: 1521 if (ForRedeclaration) 1522 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1523 << Context.BuiltinInfo.GetName(BID); 1524 return 0; 1525 } 1526 1527 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1528 Diag(Loc, diag::ext_implicit_lib_function_decl) 1529 << Context.BuiltinInfo.GetName(BID) 1530 << R; 1531 if (Context.BuiltinInfo.getHeaderName(BID) && 1532 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1533 != DiagnosticsEngine::Ignored) 1534 Diag(Loc, diag::note_please_include_header) 1535 << Context.BuiltinInfo.getHeaderName(BID) 1536 << Context.BuiltinInfo.GetName(BID); 1537 } 1538 1539 DeclContext *Parent = Context.getTranslationUnitDecl(); 1540 if (getLangOpts().CPlusPlus) { 1541 LinkageSpecDecl *CLinkageDecl = 1542 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1543 LinkageSpecDecl::lang_c, false); 1544 CLinkageDecl->setImplicit(); 1545 Parent->addDecl(CLinkageDecl); 1546 Parent = CLinkageDecl; 1547 } 1548 1549 FunctionDecl *New = FunctionDecl::Create(Context, 1550 Parent, 1551 Loc, Loc, II, R, /*TInfo=*/0, 1552 SC_Extern, 1553 false, 1554 /*hasPrototype=*/true); 1555 New->setImplicit(); 1556 1557 // Create Decl objects for each parameter, adding them to the 1558 // FunctionDecl. 1559 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1560 SmallVector<ParmVarDecl*, 16> Params; 1561 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1562 ParmVarDecl *parm = 1563 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1564 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0); 1565 parm->setScopeInfo(0, i); 1566 Params.push_back(parm); 1567 } 1568 New->setParams(Params); 1569 } 1570 1571 AddKnownFunctionAttributes(New); 1572 RegisterLocallyScopedExternCDecl(New, S); 1573 1574 // TUScope is the translation-unit scope to insert this function into. 1575 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1576 // relate Scopes to DeclContexts, and probably eliminate CurContext 1577 // entirely, but we're not there yet. 1578 DeclContext *SavedContext = CurContext; 1579 CurContext = Parent; 1580 PushOnScopeChains(New, TUScope); 1581 CurContext = SavedContext; 1582 return New; 1583 } 1584 1585 /// \brief Filter out any previous declarations that the given declaration 1586 /// should not consider because they are not permitted to conflict, e.g., 1587 /// because they come from hidden sub-modules and do not refer to the same 1588 /// entity. 1589 static void filterNonConflictingPreviousDecls(ASTContext &context, 1590 NamedDecl *decl, 1591 LookupResult &previous){ 1592 // This is only interesting when modules are enabled. 1593 if (!context.getLangOpts().Modules) 1594 return; 1595 1596 // Empty sets are uninteresting. 1597 if (previous.empty()) 1598 return; 1599 1600 LookupResult::Filter filter = previous.makeFilter(); 1601 while (filter.hasNext()) { 1602 NamedDecl *old = filter.next(); 1603 1604 // Non-hidden declarations are never ignored. 1605 if (!old->isHidden()) 1606 continue; 1607 1608 if (!old->isExternallyVisible()) 1609 filter.erase(); 1610 } 1611 1612 filter.done(); 1613 } 1614 1615 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1616 QualType OldType; 1617 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1618 OldType = OldTypedef->getUnderlyingType(); 1619 else 1620 OldType = Context.getTypeDeclType(Old); 1621 QualType NewType = New->getUnderlyingType(); 1622 1623 if (NewType->isVariablyModifiedType()) { 1624 // Must not redefine a typedef with a variably-modified type. 1625 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1626 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1627 << Kind << NewType; 1628 if (Old->getLocation().isValid()) 1629 Diag(Old->getLocation(), diag::note_previous_definition); 1630 New->setInvalidDecl(); 1631 return true; 1632 } 1633 1634 if (OldType != NewType && 1635 !OldType->isDependentType() && 1636 !NewType->isDependentType() && 1637 !Context.hasSameType(OldType, NewType)) { 1638 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1639 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1640 << Kind << NewType << OldType; 1641 if (Old->getLocation().isValid()) 1642 Diag(Old->getLocation(), diag::note_previous_definition); 1643 New->setInvalidDecl(); 1644 return true; 1645 } 1646 return false; 1647 } 1648 1649 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1650 /// same name and scope as a previous declaration 'Old'. Figure out 1651 /// how to resolve this situation, merging decls or emitting 1652 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1653 /// 1654 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1655 // If the new decl is known invalid already, don't bother doing any 1656 // merging checks. 1657 if (New->isInvalidDecl()) return; 1658 1659 // Allow multiple definitions for ObjC built-in typedefs. 1660 // FIXME: Verify the underlying types are equivalent! 1661 if (getLangOpts().ObjC1) { 1662 const IdentifierInfo *TypeID = New->getIdentifier(); 1663 switch (TypeID->getLength()) { 1664 default: break; 1665 case 2: 1666 { 1667 if (!TypeID->isStr("id")) 1668 break; 1669 QualType T = New->getUnderlyingType(); 1670 if (!T->isPointerType()) 1671 break; 1672 if (!T->isVoidPointerType()) { 1673 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1674 if (!PT->isStructureType()) 1675 break; 1676 } 1677 Context.setObjCIdRedefinitionType(T); 1678 // Install the built-in type for 'id', ignoring the current definition. 1679 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1680 return; 1681 } 1682 case 5: 1683 if (!TypeID->isStr("Class")) 1684 break; 1685 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1686 // Install the built-in type for 'Class', ignoring the current definition. 1687 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1688 return; 1689 case 3: 1690 if (!TypeID->isStr("SEL")) 1691 break; 1692 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1693 // Install the built-in type for 'SEL', ignoring the current definition. 1694 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1695 return; 1696 } 1697 // Fall through - the typedef name was not a builtin type. 1698 } 1699 1700 // Verify the old decl was also a type. 1701 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1702 if (!Old) { 1703 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1704 << New->getDeclName(); 1705 1706 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1707 if (OldD->getLocation().isValid()) 1708 Diag(OldD->getLocation(), diag::note_previous_definition); 1709 1710 return New->setInvalidDecl(); 1711 } 1712 1713 // If the old declaration is invalid, just give up here. 1714 if (Old->isInvalidDecl()) 1715 return New->setInvalidDecl(); 1716 1717 // If the typedef types are not identical, reject them in all languages and 1718 // with any extensions enabled. 1719 if (isIncompatibleTypedef(Old, New)) 1720 return; 1721 1722 // The types match. Link up the redeclaration chain and merge attributes if 1723 // the old declaration was a typedef. 1724 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1725 New->setPreviousDecl(Typedef); 1726 mergeDeclAttributes(New, Old); 1727 } 1728 1729 if (getLangOpts().MicrosoftExt) 1730 return; 1731 1732 if (getLangOpts().CPlusPlus) { 1733 // C++ [dcl.typedef]p2: 1734 // In a given non-class scope, a typedef specifier can be used to 1735 // redefine the name of any type declared in that scope to refer 1736 // to the type to which it already refers. 1737 if (!isa<CXXRecordDecl>(CurContext)) 1738 return; 1739 1740 // C++0x [dcl.typedef]p4: 1741 // In a given class scope, a typedef specifier can be used to redefine 1742 // any class-name declared in that scope that is not also a typedef-name 1743 // to refer to the type to which it already refers. 1744 // 1745 // This wording came in via DR424, which was a correction to the 1746 // wording in DR56, which accidentally banned code like: 1747 // 1748 // struct S { 1749 // typedef struct A { } A; 1750 // }; 1751 // 1752 // in the C++03 standard. We implement the C++0x semantics, which 1753 // allow the above but disallow 1754 // 1755 // struct S { 1756 // typedef int I; 1757 // typedef int I; 1758 // }; 1759 // 1760 // since that was the intent of DR56. 1761 if (!isa<TypedefNameDecl>(Old)) 1762 return; 1763 1764 Diag(New->getLocation(), diag::err_redefinition) 1765 << New->getDeclName(); 1766 Diag(Old->getLocation(), diag::note_previous_definition); 1767 return New->setInvalidDecl(); 1768 } 1769 1770 // Modules always permit redefinition of typedefs, as does C11. 1771 if (getLangOpts().Modules || getLangOpts().C11) 1772 return; 1773 1774 // If we have a redefinition of a typedef in C, emit a warning. This warning 1775 // is normally mapped to an error, but can be controlled with 1776 // -Wtypedef-redefinition. If either the original or the redefinition is 1777 // in a system header, don't emit this for compatibility with GCC. 1778 if (getDiagnostics().getSuppressSystemWarnings() && 1779 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1780 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1781 return; 1782 1783 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1784 << New->getDeclName(); 1785 Diag(Old->getLocation(), diag::note_previous_definition); 1786 return; 1787 } 1788 1789 /// DeclhasAttr - returns true if decl Declaration already has the target 1790 /// attribute. 1791 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1792 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1793 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1794 for (const auto *i : D->attrs()) 1795 if (i->getKind() == A->getKind()) { 1796 if (Ann) { 1797 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1798 return true; 1799 continue; 1800 } 1801 // FIXME: Don't hardcode this check 1802 if (OA && isa<OwnershipAttr>(i)) 1803 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 1804 return true; 1805 } 1806 1807 return false; 1808 } 1809 1810 static bool isAttributeTargetADefinition(Decl *D) { 1811 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1812 return VD->isThisDeclarationADefinition(); 1813 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1814 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1815 return true; 1816 } 1817 1818 /// Merge alignment attributes from \p Old to \p New, taking into account the 1819 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1820 /// 1821 /// \return \c true if any attributes were added to \p New. 1822 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1823 // Look for alignas attributes on Old, and pick out whichever attribute 1824 // specifies the strictest alignment requirement. 1825 AlignedAttr *OldAlignasAttr = 0; 1826 AlignedAttr *OldStrictestAlignAttr = 0; 1827 unsigned OldAlign = 0; 1828 for (specific_attr_iterator<AlignedAttr> 1829 I = Old->specific_attr_begin<AlignedAttr>(), 1830 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1831 // FIXME: We have no way of representing inherited dependent alignments 1832 // in a case like: 1833 // template<int A, int B> struct alignas(A) X; 1834 // template<int A, int B> struct alignas(B) X {}; 1835 // For now, we just ignore any alignas attributes which are not on the 1836 // definition in such a case. 1837 if (I->isAlignmentDependent()) 1838 return false; 1839 1840 if (I->isAlignas()) 1841 OldAlignasAttr = *I; 1842 1843 unsigned Align = I->getAlignment(S.Context); 1844 if (Align > OldAlign) { 1845 OldAlign = Align; 1846 OldStrictestAlignAttr = *I; 1847 } 1848 } 1849 1850 // Look for alignas attributes on New. 1851 AlignedAttr *NewAlignasAttr = 0; 1852 unsigned NewAlign = 0; 1853 for (specific_attr_iterator<AlignedAttr> 1854 I = New->specific_attr_begin<AlignedAttr>(), 1855 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1856 if (I->isAlignmentDependent()) 1857 return false; 1858 1859 if (I->isAlignas()) 1860 NewAlignasAttr = *I; 1861 1862 unsigned Align = I->getAlignment(S.Context); 1863 if (Align > NewAlign) 1864 NewAlign = Align; 1865 } 1866 1867 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1868 // Both declarations have 'alignas' attributes. We require them to match. 1869 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1870 // fall short. (If two declarations both have alignas, they must both match 1871 // every definition, and so must match each other if there is a definition.) 1872 1873 // If either declaration only contains 'alignas(0)' specifiers, then it 1874 // specifies the natural alignment for the type. 1875 if (OldAlign == 0 || NewAlign == 0) { 1876 QualType Ty; 1877 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1878 Ty = VD->getType(); 1879 else 1880 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1881 1882 if (OldAlign == 0) 1883 OldAlign = S.Context.getTypeAlign(Ty); 1884 if (NewAlign == 0) 1885 NewAlign = S.Context.getTypeAlign(Ty); 1886 } 1887 1888 if (OldAlign != NewAlign) { 1889 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1890 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1891 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1892 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1893 } 1894 } 1895 1896 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1897 // C++11 [dcl.align]p6: 1898 // if any declaration of an entity has an alignment-specifier, 1899 // every defining declaration of that entity shall specify an 1900 // equivalent alignment. 1901 // C11 6.7.5/7: 1902 // If the definition of an object does not have an alignment 1903 // specifier, any other declaration of that object shall also 1904 // have no alignment specifier. 1905 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1906 << OldAlignasAttr; 1907 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1908 << OldAlignasAttr; 1909 } 1910 1911 bool AnyAdded = false; 1912 1913 // Ensure we have an attribute representing the strictest alignment. 1914 if (OldAlign > NewAlign) { 1915 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1916 Clone->setInherited(true); 1917 New->addAttr(Clone); 1918 AnyAdded = true; 1919 } 1920 1921 // Ensure we have an alignas attribute if the old declaration had one. 1922 if (OldAlignasAttr && !NewAlignasAttr && 1923 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1924 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1925 Clone->setInherited(true); 1926 New->addAttr(Clone); 1927 AnyAdded = true; 1928 } 1929 1930 return AnyAdded; 1931 } 1932 1933 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1934 bool Override) { 1935 InheritableAttr *NewAttr = NULL; 1936 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1937 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1938 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1939 AA->getIntroduced(), AA->getDeprecated(), 1940 AA->getObsoleted(), AA->getUnavailable(), 1941 AA->getMessage(), Override, 1942 AttrSpellingListIndex); 1943 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1944 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1945 AttrSpellingListIndex); 1946 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1947 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1948 AttrSpellingListIndex); 1949 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1950 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1951 AttrSpellingListIndex); 1952 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1953 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1954 AttrSpellingListIndex); 1955 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1956 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1957 FA->getFormatIdx(), FA->getFirstArg(), 1958 AttrSpellingListIndex); 1959 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1960 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1961 AttrSpellingListIndex); 1962 else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr)) 1963 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 1964 AttrSpellingListIndex, 1965 IA->getSemanticSpelling()); 1966 else if (isa<AlignedAttr>(Attr)) 1967 // AlignedAttrs are handled separately, because we need to handle all 1968 // such attributes on a declaration at the same time. 1969 NewAttr = 0; 1970 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 1971 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1972 1973 if (NewAttr) { 1974 NewAttr->setInherited(true); 1975 D->addAttr(NewAttr); 1976 return true; 1977 } 1978 1979 return false; 1980 } 1981 1982 static const Decl *getDefinition(const Decl *D) { 1983 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1984 return TD->getDefinition(); 1985 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1986 const VarDecl *Def = VD->getDefinition(); 1987 if (Def) 1988 return Def; 1989 return VD->getActingDefinition(); 1990 } 1991 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1992 const FunctionDecl* Def; 1993 if (FD->isDefined(Def)) 1994 return Def; 1995 } 1996 return NULL; 1997 } 1998 1999 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2000 for (const auto *Attribute : D->attrs()) 2001 if (Attribute->getKind() == Kind) 2002 return true; 2003 return false; 2004 } 2005 2006 /// checkNewAttributesAfterDef - If we already have a definition, check that 2007 /// there are no new attributes in this declaration. 2008 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2009 if (!New->hasAttrs()) 2010 return; 2011 2012 const Decl *Def = getDefinition(Old); 2013 if (!Def || Def == New) 2014 return; 2015 2016 AttrVec &NewAttributes = New->getAttrs(); 2017 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2018 const Attr *NewAttribute = NewAttributes[I]; 2019 2020 if (isa<AliasAttr>(NewAttribute)) { 2021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2022 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2023 else { 2024 VarDecl *VD = cast<VarDecl>(New); 2025 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2026 VarDecl::TentativeDefinition 2027 ? diag::err_alias_after_tentative 2028 : diag::err_redefinition; 2029 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2030 S.Diag(Def->getLocation(), diag::note_previous_definition); 2031 VD->setInvalidDecl(); 2032 } 2033 ++I; 2034 continue; 2035 } 2036 2037 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2038 // Tentative definitions are only interesting for the alias check above. 2039 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2040 ++I; 2041 continue; 2042 } 2043 } 2044 2045 if (hasAttribute(Def, NewAttribute->getKind())) { 2046 ++I; 2047 continue; // regular attr merging will take care of validating this. 2048 } 2049 2050 if (isa<C11NoReturnAttr>(NewAttribute)) { 2051 // C's _Noreturn is allowed to be added to a function after it is defined. 2052 ++I; 2053 continue; 2054 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2055 if (AA->isAlignas()) { 2056 // C++11 [dcl.align]p6: 2057 // if any declaration of an entity has an alignment-specifier, 2058 // every defining declaration of that entity shall specify an 2059 // equivalent alignment. 2060 // C11 6.7.5/7: 2061 // If the definition of an object does not have an alignment 2062 // specifier, any other declaration of that object shall also 2063 // have no alignment specifier. 2064 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2065 << AA; 2066 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2067 << AA; 2068 NewAttributes.erase(NewAttributes.begin() + I); 2069 --E; 2070 continue; 2071 } 2072 } 2073 2074 S.Diag(NewAttribute->getLocation(), 2075 diag::warn_attribute_precede_definition); 2076 S.Diag(Def->getLocation(), diag::note_previous_definition); 2077 NewAttributes.erase(NewAttributes.begin() + I); 2078 --E; 2079 } 2080 } 2081 2082 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2083 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2084 AvailabilityMergeKind AMK) { 2085 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2086 UsedAttr *NewAttr = OldAttr->clone(Context); 2087 NewAttr->setInherited(true); 2088 New->addAttr(NewAttr); 2089 } 2090 2091 if (!Old->hasAttrs() && !New->hasAttrs()) 2092 return; 2093 2094 // attributes declared post-definition are currently ignored 2095 checkNewAttributesAfterDef(*this, New, Old); 2096 2097 if (!Old->hasAttrs()) 2098 return; 2099 2100 bool foundAny = New->hasAttrs(); 2101 2102 // Ensure that any moving of objects within the allocated map is done before 2103 // we process them. 2104 if (!foundAny) New->setAttrs(AttrVec()); 2105 2106 for (specific_attr_iterator<InheritableAttr> 2107 i = Old->specific_attr_begin<InheritableAttr>(), 2108 e = Old->specific_attr_end<InheritableAttr>(); 2109 i != e; ++i) { 2110 bool Override = false; 2111 // Ignore deprecated/unavailable/availability attributes if requested. 2112 if (isa<DeprecatedAttr>(*i) || 2113 isa<UnavailableAttr>(*i) || 2114 isa<AvailabilityAttr>(*i)) { 2115 switch (AMK) { 2116 case AMK_None: 2117 continue; 2118 2119 case AMK_Redeclaration: 2120 break; 2121 2122 case AMK_Override: 2123 Override = true; 2124 break; 2125 } 2126 } 2127 2128 // Already handled. 2129 if (isa<UsedAttr>(*i)) 2130 continue; 2131 2132 if (mergeDeclAttribute(*this, New, *i, Override)) 2133 foundAny = true; 2134 } 2135 2136 if (mergeAlignedAttrs(*this, New, Old)) 2137 foundAny = true; 2138 2139 if (!foundAny) New->dropAttrs(); 2140 } 2141 2142 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2143 /// to the new one. 2144 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2145 const ParmVarDecl *oldDecl, 2146 Sema &S) { 2147 // C++11 [dcl.attr.depend]p2: 2148 // The first declaration of a function shall specify the 2149 // carries_dependency attribute for its declarator-id if any declaration 2150 // of the function specifies the carries_dependency attribute. 2151 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2152 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2153 S.Diag(CDA->getLocation(), 2154 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2155 // Find the first declaration of the parameter. 2156 // FIXME: Should we build redeclaration chains for function parameters? 2157 const FunctionDecl *FirstFD = 2158 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2159 const ParmVarDecl *FirstVD = 2160 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2161 S.Diag(FirstVD->getLocation(), 2162 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2163 } 2164 2165 if (!oldDecl->hasAttrs()) 2166 return; 2167 2168 bool foundAny = newDecl->hasAttrs(); 2169 2170 // Ensure that any moving of objects within the allocated map is 2171 // done before we process them. 2172 if (!foundAny) newDecl->setAttrs(AttrVec()); 2173 2174 for (specific_attr_iterator<InheritableParamAttr> 2175 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2176 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2177 if (!DeclHasAttr(newDecl, *i)) { 2178 InheritableAttr *newAttr = 2179 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2180 newAttr->setInherited(true); 2181 newDecl->addAttr(newAttr); 2182 foundAny = true; 2183 } 2184 } 2185 2186 if (!foundAny) newDecl->dropAttrs(); 2187 } 2188 2189 namespace { 2190 2191 /// Used in MergeFunctionDecl to keep track of function parameters in 2192 /// C. 2193 struct GNUCompatibleParamWarning { 2194 ParmVarDecl *OldParm; 2195 ParmVarDecl *NewParm; 2196 QualType PromotedType; 2197 }; 2198 2199 } 2200 2201 /// getSpecialMember - get the special member enum for a method. 2202 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2203 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2204 if (Ctor->isDefaultConstructor()) 2205 return Sema::CXXDefaultConstructor; 2206 2207 if (Ctor->isCopyConstructor()) 2208 return Sema::CXXCopyConstructor; 2209 2210 if (Ctor->isMoveConstructor()) 2211 return Sema::CXXMoveConstructor; 2212 } else if (isa<CXXDestructorDecl>(MD)) { 2213 return Sema::CXXDestructor; 2214 } else if (MD->isCopyAssignmentOperator()) { 2215 return Sema::CXXCopyAssignment; 2216 } else if (MD->isMoveAssignmentOperator()) { 2217 return Sema::CXXMoveAssignment; 2218 } 2219 2220 return Sema::CXXInvalid; 2221 } 2222 2223 /// canRedefineFunction - checks if a function can be redefined. Currently, 2224 /// only extern inline functions can be redefined, and even then only in 2225 /// GNU89 mode. 2226 static bool canRedefineFunction(const FunctionDecl *FD, 2227 const LangOptions& LangOpts) { 2228 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2229 !LangOpts.CPlusPlus && 2230 FD->isInlineSpecified() && 2231 FD->getStorageClass() == SC_Extern); 2232 } 2233 2234 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2235 const AttributedType *AT = T->getAs<AttributedType>(); 2236 while (AT && !AT->isCallingConv()) 2237 AT = AT->getModifiedType()->getAs<AttributedType>(); 2238 return AT; 2239 } 2240 2241 template <typename T> 2242 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2243 const DeclContext *DC = Old->getDeclContext(); 2244 if (DC->isRecord()) 2245 return false; 2246 2247 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2248 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2249 return true; 2250 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2251 return true; 2252 return false; 2253 } 2254 2255 /// MergeFunctionDecl - We just parsed a function 'New' from 2256 /// declarator D which has the same name and scope as a previous 2257 /// declaration 'Old'. Figure out how to resolve this situation, 2258 /// merging decls or emitting diagnostics as appropriate. 2259 /// 2260 /// In C++, New and Old must be declarations that are not 2261 /// overloaded. Use IsOverload to determine whether New and Old are 2262 /// overloaded, and to select the Old declaration that New should be 2263 /// merged with. 2264 /// 2265 /// Returns true if there was an error, false otherwise. 2266 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2267 Scope *S, bool MergeTypeWithOld) { 2268 // Verify the old decl was also a function. 2269 FunctionDecl *Old = OldD->getAsFunction(); 2270 if (!Old) { 2271 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2272 if (New->getFriendObjectKind()) { 2273 Diag(New->getLocation(), diag::err_using_decl_friend); 2274 Diag(Shadow->getTargetDecl()->getLocation(), 2275 diag::note_using_decl_target); 2276 Diag(Shadow->getUsingDecl()->getLocation(), 2277 diag::note_using_decl) << 0; 2278 return true; 2279 } 2280 2281 // C++11 [namespace.udecl]p14: 2282 // If a function declaration in namespace scope or block scope has the 2283 // same name and the same parameter-type-list as a function introduced 2284 // by a using-declaration, and the declarations do not declare the same 2285 // function, the program is ill-formed. 2286 2287 // Check whether the two declarations might declare the same function. 2288 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2289 if (Old && 2290 !Old->getDeclContext()->getRedeclContext()->Equals( 2291 New->getDeclContext()->getRedeclContext()) && 2292 !(Old->isExternC() && New->isExternC())) 2293 Old = 0; 2294 2295 if (!Old) { 2296 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2297 Diag(Shadow->getTargetDecl()->getLocation(), 2298 diag::note_using_decl_target); 2299 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2300 return true; 2301 } 2302 OldD = Old; 2303 } else { 2304 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2305 << New->getDeclName(); 2306 Diag(OldD->getLocation(), diag::note_previous_definition); 2307 return true; 2308 } 2309 } 2310 2311 // If the old declaration is invalid, just give up here. 2312 if (Old->isInvalidDecl()) 2313 return true; 2314 2315 // Determine whether the previous declaration was a definition, 2316 // implicit declaration, or a declaration. 2317 diag::kind PrevDiag; 2318 SourceLocation OldLocation = Old->getLocation(); 2319 if (Old->isThisDeclarationADefinition()) 2320 PrevDiag = diag::note_previous_definition; 2321 else if (Old->isImplicit()) { 2322 PrevDiag = diag::note_previous_implicit_declaration; 2323 if (OldLocation.isInvalid()) 2324 OldLocation = New->getLocation(); 2325 } else 2326 PrevDiag = diag::note_previous_declaration; 2327 2328 // Don't complain about this if we're in GNU89 mode and the old function 2329 // is an extern inline function. 2330 // Don't complain about specializations. They are not supposed to have 2331 // storage classes. 2332 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2333 New->getStorageClass() == SC_Static && 2334 Old->hasExternalFormalLinkage() && 2335 !New->getTemplateSpecializationInfo() && 2336 !canRedefineFunction(Old, getLangOpts())) { 2337 if (getLangOpts().MicrosoftExt) { 2338 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2339 Diag(OldLocation, PrevDiag); 2340 } else { 2341 Diag(New->getLocation(), diag::err_static_non_static) << New; 2342 Diag(OldLocation, PrevDiag); 2343 return true; 2344 } 2345 } 2346 2347 2348 // If a function is first declared with a calling convention, but is later 2349 // declared or defined without one, all following decls assume the calling 2350 // convention of the first. 2351 // 2352 // It's OK if a function is first declared without a calling convention, 2353 // but is later declared or defined with the default calling convention. 2354 // 2355 // To test if either decl has an explicit calling convention, we look for 2356 // AttributedType sugar nodes on the type as written. If they are missing or 2357 // were canonicalized away, we assume the calling convention was implicit. 2358 // 2359 // Note also that we DO NOT return at this point, because we still have 2360 // other tests to run. 2361 QualType OldQType = Context.getCanonicalType(Old->getType()); 2362 QualType NewQType = Context.getCanonicalType(New->getType()); 2363 const FunctionType *OldType = cast<FunctionType>(OldQType); 2364 const FunctionType *NewType = cast<FunctionType>(NewQType); 2365 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2366 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2367 bool RequiresAdjustment = false; 2368 2369 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2370 FunctionDecl *First = Old->getFirstDecl(); 2371 const FunctionType *FT = 2372 First->getType().getCanonicalType()->castAs<FunctionType>(); 2373 FunctionType::ExtInfo FI = FT->getExtInfo(); 2374 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2375 if (!NewCCExplicit) { 2376 // Inherit the CC from the previous declaration if it was specified 2377 // there but not here. 2378 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2379 RequiresAdjustment = true; 2380 } else { 2381 // Calling conventions aren't compatible, so complain. 2382 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2383 Diag(New->getLocation(), diag::err_cconv_change) 2384 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2385 << !FirstCCExplicit 2386 << (!FirstCCExplicit ? "" : 2387 FunctionType::getNameForCallConv(FI.getCC())); 2388 2389 // Put the note on the first decl, since it is the one that matters. 2390 Diag(First->getLocation(), diag::note_previous_declaration); 2391 return true; 2392 } 2393 } 2394 2395 // FIXME: diagnose the other way around? 2396 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2397 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2398 RequiresAdjustment = true; 2399 } 2400 2401 // Merge regparm attribute. 2402 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2403 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2404 if (NewTypeInfo.getHasRegParm()) { 2405 Diag(New->getLocation(), diag::err_regparm_mismatch) 2406 << NewType->getRegParmType() 2407 << OldType->getRegParmType(); 2408 Diag(OldLocation, diag::note_previous_declaration); 2409 return true; 2410 } 2411 2412 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2413 RequiresAdjustment = true; 2414 } 2415 2416 // Merge ns_returns_retained attribute. 2417 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2418 if (NewTypeInfo.getProducesResult()) { 2419 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2420 Diag(OldLocation, diag::note_previous_declaration); 2421 return true; 2422 } 2423 2424 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2425 RequiresAdjustment = true; 2426 } 2427 2428 if (RequiresAdjustment) { 2429 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2430 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2431 New->setType(QualType(AdjustedType, 0)); 2432 NewQType = Context.getCanonicalType(New->getType()); 2433 NewType = cast<FunctionType>(NewQType); 2434 } 2435 2436 // If this redeclaration makes the function inline, we may need to add it to 2437 // UndefinedButUsed. 2438 if (!Old->isInlined() && New->isInlined() && 2439 !New->hasAttr<GNUInlineAttr>() && 2440 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2441 Old->isUsed(false) && 2442 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2443 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2444 SourceLocation())); 2445 2446 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2447 // about it. 2448 if (New->hasAttr<GNUInlineAttr>() && 2449 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2450 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2451 } 2452 2453 if (getLangOpts().CPlusPlus) { 2454 // (C++98 13.1p2): 2455 // Certain function declarations cannot be overloaded: 2456 // -- Function declarations that differ only in the return type 2457 // cannot be overloaded. 2458 2459 // Go back to the type source info to compare the declared return types, 2460 // per C++1y [dcl.type.auto]p13: 2461 // Redeclarations or specializations of a function or function template 2462 // with a declared return type that uses a placeholder type shall also 2463 // use that placeholder, not a deduced type. 2464 QualType OldDeclaredReturnType = 2465 (Old->getTypeSourceInfo() 2466 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2467 : OldType)->getReturnType(); 2468 QualType NewDeclaredReturnType = 2469 (New->getTypeSourceInfo() 2470 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2471 : NewType)->getReturnType(); 2472 QualType ResQT; 2473 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2474 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2475 New->isLocalExternDecl())) { 2476 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2477 OldDeclaredReturnType->isObjCObjectPointerType()) 2478 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2479 if (ResQT.isNull()) { 2480 if (New->isCXXClassMember() && New->isOutOfLine()) 2481 Diag(New->getLocation(), 2482 diag::err_member_def_does_not_match_ret_type) << New; 2483 else 2484 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2485 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2486 return true; 2487 } 2488 else 2489 NewQType = ResQT; 2490 } 2491 2492 QualType OldReturnType = OldType->getReturnType(); 2493 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2494 if (OldReturnType != NewReturnType) { 2495 // If this function has a deduced return type and has already been 2496 // defined, copy the deduced value from the old declaration. 2497 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2498 if (OldAT && OldAT->isDeduced()) { 2499 New->setType( 2500 SubstAutoType(New->getType(), 2501 OldAT->isDependentType() ? Context.DependentTy 2502 : OldAT->getDeducedType())); 2503 NewQType = Context.getCanonicalType( 2504 SubstAutoType(NewQType, 2505 OldAT->isDependentType() ? Context.DependentTy 2506 : OldAT->getDeducedType())); 2507 } 2508 } 2509 2510 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2511 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2512 if (OldMethod && NewMethod) { 2513 // Preserve triviality. 2514 NewMethod->setTrivial(OldMethod->isTrivial()); 2515 2516 // MSVC allows explicit template specialization at class scope: 2517 // 2 CXXMethodDecls referring to the same function will be injected. 2518 // We don't want a redeclaration error. 2519 bool IsClassScopeExplicitSpecialization = 2520 OldMethod->isFunctionTemplateSpecialization() && 2521 NewMethod->isFunctionTemplateSpecialization(); 2522 bool isFriend = NewMethod->getFriendObjectKind(); 2523 2524 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2525 !IsClassScopeExplicitSpecialization) { 2526 // -- Member function declarations with the same name and the 2527 // same parameter types cannot be overloaded if any of them 2528 // is a static member function declaration. 2529 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2530 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2531 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2532 return true; 2533 } 2534 2535 // C++ [class.mem]p1: 2536 // [...] A member shall not be declared twice in the 2537 // member-specification, except that a nested class or member 2538 // class template can be declared and then later defined. 2539 if (ActiveTemplateInstantiations.empty()) { 2540 unsigned NewDiag; 2541 if (isa<CXXConstructorDecl>(OldMethod)) 2542 NewDiag = diag::err_constructor_redeclared; 2543 else if (isa<CXXDestructorDecl>(NewMethod)) 2544 NewDiag = diag::err_destructor_redeclared; 2545 else if (isa<CXXConversionDecl>(NewMethod)) 2546 NewDiag = diag::err_conv_function_redeclared; 2547 else 2548 NewDiag = diag::err_member_redeclared; 2549 2550 Diag(New->getLocation(), NewDiag); 2551 } else { 2552 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2553 << New << New->getType(); 2554 } 2555 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2556 2557 // Complain if this is an explicit declaration of a special 2558 // member that was initially declared implicitly. 2559 // 2560 // As an exception, it's okay to befriend such methods in order 2561 // to permit the implicit constructor/destructor/operator calls. 2562 } else if (OldMethod->isImplicit()) { 2563 if (isFriend) { 2564 NewMethod->setImplicit(); 2565 } else { 2566 Diag(NewMethod->getLocation(), 2567 diag::err_definition_of_implicitly_declared_member) 2568 << New << getSpecialMember(OldMethod); 2569 return true; 2570 } 2571 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2572 Diag(NewMethod->getLocation(), 2573 diag::err_definition_of_explicitly_defaulted_member) 2574 << getSpecialMember(OldMethod); 2575 return true; 2576 } 2577 } 2578 2579 // C++11 [dcl.attr.noreturn]p1: 2580 // The first declaration of a function shall specify the noreturn 2581 // attribute if any declaration of that function specifies the noreturn 2582 // attribute. 2583 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2584 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2585 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2586 Diag(Old->getFirstDecl()->getLocation(), 2587 diag::note_noreturn_missing_first_decl); 2588 } 2589 2590 // C++11 [dcl.attr.depend]p2: 2591 // The first declaration of a function shall specify the 2592 // carries_dependency attribute for its declarator-id if any declaration 2593 // of the function specifies the carries_dependency attribute. 2594 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2595 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2596 Diag(CDA->getLocation(), 2597 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2598 Diag(Old->getFirstDecl()->getLocation(), 2599 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2600 } 2601 2602 // (C++98 8.3.5p3): 2603 // All declarations for a function shall agree exactly in both the 2604 // return type and the parameter-type-list. 2605 // We also want to respect all the extended bits except noreturn. 2606 2607 // noreturn should now match unless the old type info didn't have it. 2608 QualType OldQTypeForComparison = OldQType; 2609 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2610 assert(OldQType == QualType(OldType, 0)); 2611 const FunctionType *OldTypeForComparison 2612 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2613 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2614 assert(OldQTypeForComparison.isCanonical()); 2615 } 2616 2617 if (haveIncompatibleLanguageLinkages(Old, New)) { 2618 // As a special case, retain the language linkage from previous 2619 // declarations of a friend function as an extension. 2620 // 2621 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2622 // and is useful because there's otherwise no way to specify language 2623 // linkage within class scope. 2624 // 2625 // Check cautiously as the friend object kind isn't yet complete. 2626 if (New->getFriendObjectKind() != Decl::FOK_None) { 2627 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2628 Diag(OldLocation, PrevDiag); 2629 } else { 2630 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2631 Diag(OldLocation, PrevDiag); 2632 return true; 2633 } 2634 } 2635 2636 if (OldQTypeForComparison == NewQType) 2637 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2638 2639 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2640 New->isLocalExternDecl()) { 2641 // It's OK if we couldn't merge types for a local function declaraton 2642 // if either the old or new type is dependent. We'll merge the types 2643 // when we instantiate the function. 2644 return false; 2645 } 2646 2647 // Fall through for conflicting redeclarations and redefinitions. 2648 } 2649 2650 // C: Function types need to be compatible, not identical. This handles 2651 // duplicate function decls like "void f(int); void f(enum X);" properly. 2652 if (!getLangOpts().CPlusPlus && 2653 Context.typesAreCompatible(OldQType, NewQType)) { 2654 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2655 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2656 const FunctionProtoType *OldProto = 0; 2657 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2658 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2659 // The old declaration provided a function prototype, but the 2660 // new declaration does not. Merge in the prototype. 2661 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2662 SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(), 2663 OldProto->param_type_end()); 2664 NewQType = 2665 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2666 OldProto->getExtProtoInfo()); 2667 New->setType(NewQType); 2668 New->setHasInheritedPrototype(); 2669 2670 // Synthesize a parameter for each argument type. 2671 SmallVector<ParmVarDecl*, 16> Params; 2672 for (FunctionProtoType::param_type_iterator 2673 ParamType = OldProto->param_type_begin(), 2674 ParamEnd = OldProto->param_type_end(); 2675 ParamType != ParamEnd; ++ParamType) { 2676 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2677 SourceLocation(), 2678 SourceLocation(), 0, 2679 *ParamType, /*TInfo=*/0, 2680 SC_None, 2681 0); 2682 Param->setScopeInfo(0, Params.size()); 2683 Param->setImplicit(); 2684 Params.push_back(Param); 2685 } 2686 2687 New->setParams(Params); 2688 } 2689 2690 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2691 } 2692 2693 // GNU C permits a K&R definition to follow a prototype declaration 2694 // if the declared types of the parameters in the K&R definition 2695 // match the types in the prototype declaration, even when the 2696 // promoted types of the parameters from the K&R definition differ 2697 // from the types in the prototype. GCC then keeps the types from 2698 // the prototype. 2699 // 2700 // If a variadic prototype is followed by a non-variadic K&R definition, 2701 // the K&R definition becomes variadic. This is sort of an edge case, but 2702 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2703 // C99 6.9.1p8. 2704 if (!getLangOpts().CPlusPlus && 2705 Old->hasPrototype() && !New->hasPrototype() && 2706 New->getType()->getAs<FunctionProtoType>() && 2707 Old->getNumParams() == New->getNumParams()) { 2708 SmallVector<QualType, 16> ArgTypes; 2709 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2710 const FunctionProtoType *OldProto 2711 = Old->getType()->getAs<FunctionProtoType>(); 2712 const FunctionProtoType *NewProto 2713 = New->getType()->getAs<FunctionProtoType>(); 2714 2715 // Determine whether this is the GNU C extension. 2716 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2717 NewProto->getReturnType()); 2718 bool LooseCompatible = !MergedReturn.isNull(); 2719 for (unsigned Idx = 0, End = Old->getNumParams(); 2720 LooseCompatible && Idx != End; ++Idx) { 2721 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2722 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2723 if (Context.typesAreCompatible(OldParm->getType(), 2724 NewProto->getParamType(Idx))) { 2725 ArgTypes.push_back(NewParm->getType()); 2726 } else if (Context.typesAreCompatible(OldParm->getType(), 2727 NewParm->getType(), 2728 /*CompareUnqualified=*/true)) { 2729 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2730 NewProto->getParamType(Idx) }; 2731 Warnings.push_back(Warn); 2732 ArgTypes.push_back(NewParm->getType()); 2733 } else 2734 LooseCompatible = false; 2735 } 2736 2737 if (LooseCompatible) { 2738 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2739 Diag(Warnings[Warn].NewParm->getLocation(), 2740 diag::ext_param_promoted_not_compatible_with_prototype) 2741 << Warnings[Warn].PromotedType 2742 << Warnings[Warn].OldParm->getType(); 2743 if (Warnings[Warn].OldParm->getLocation().isValid()) 2744 Diag(Warnings[Warn].OldParm->getLocation(), 2745 diag::note_previous_declaration); 2746 } 2747 2748 if (MergeTypeWithOld) 2749 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2750 OldProto->getExtProtoInfo())); 2751 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2752 } 2753 2754 // Fall through to diagnose conflicting types. 2755 } 2756 2757 // A function that has already been declared has been redeclared or 2758 // defined with a different type; show an appropriate diagnostic. 2759 2760 // If the previous declaration was an implicitly-generated builtin 2761 // declaration, then at the very least we should use a specialized note. 2762 unsigned BuiltinID; 2763 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2764 // If it's actually a library-defined builtin function like 'malloc' 2765 // or 'printf', just warn about the incompatible redeclaration. 2766 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2767 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2768 Diag(OldLocation, diag::note_previous_builtin_declaration) 2769 << Old << Old->getType(); 2770 2771 // If this is a global redeclaration, just forget hereafter 2772 // about the "builtin-ness" of the function. 2773 // 2774 // Doing this for local extern declarations is problematic. If 2775 // the builtin declaration remains visible, a second invalid 2776 // local declaration will produce a hard error; if it doesn't 2777 // remain visible, a single bogus local redeclaration (which is 2778 // actually only a warning) could break all the downstream code. 2779 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2780 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2781 2782 return false; 2783 } 2784 2785 PrevDiag = diag::note_previous_builtin_declaration; 2786 } 2787 2788 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2789 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2790 return true; 2791 } 2792 2793 /// \brief Completes the merge of two function declarations that are 2794 /// known to be compatible. 2795 /// 2796 /// This routine handles the merging of attributes and other 2797 /// properties of function declarations from the old declaration to 2798 /// the new declaration, once we know that New is in fact a 2799 /// redeclaration of Old. 2800 /// 2801 /// \returns false 2802 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2803 Scope *S, bool MergeTypeWithOld) { 2804 // Merge the attributes 2805 mergeDeclAttributes(New, Old); 2806 2807 // Merge "pure" flag. 2808 if (Old->isPure()) 2809 New->setPure(); 2810 2811 // Merge "used" flag. 2812 if (Old->getMostRecentDecl()->isUsed(false)) 2813 New->setIsUsed(); 2814 2815 // Merge attributes from the parameters. These can mismatch with K&R 2816 // declarations. 2817 if (New->getNumParams() == Old->getNumParams()) 2818 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2819 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2820 *this); 2821 2822 if (getLangOpts().CPlusPlus) 2823 return MergeCXXFunctionDecl(New, Old, S); 2824 2825 // Merge the function types so the we get the composite types for the return 2826 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2827 // was visible. 2828 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2829 if (!Merged.isNull() && MergeTypeWithOld) 2830 New->setType(Merged); 2831 2832 return false; 2833 } 2834 2835 2836 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2837 ObjCMethodDecl *oldMethod) { 2838 2839 // Merge the attributes, including deprecated/unavailable 2840 AvailabilityMergeKind MergeKind = 2841 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2842 : AMK_Override; 2843 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2844 2845 // Merge attributes from the parameters. 2846 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2847 oe = oldMethod->param_end(); 2848 for (ObjCMethodDecl::param_iterator 2849 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2850 ni != ne && oi != oe; ++ni, ++oi) 2851 mergeParamDeclAttributes(*ni, *oi, *this); 2852 2853 CheckObjCMethodOverride(newMethod, oldMethod); 2854 } 2855 2856 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2857 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2858 /// emitting diagnostics as appropriate. 2859 /// 2860 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2861 /// to here in AddInitializerToDecl. We can't check them before the initializer 2862 /// is attached. 2863 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2864 bool MergeTypeWithOld) { 2865 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2866 return; 2867 2868 QualType MergedT; 2869 if (getLangOpts().CPlusPlus) { 2870 if (New->getType()->isUndeducedType()) { 2871 // We don't know what the new type is until the initializer is attached. 2872 return; 2873 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2874 // These could still be something that needs exception specs checked. 2875 return MergeVarDeclExceptionSpecs(New, Old); 2876 } 2877 // C++ [basic.link]p10: 2878 // [...] the types specified by all declarations referring to a given 2879 // object or function shall be identical, except that declarations for an 2880 // array object can specify array types that differ by the presence or 2881 // absence of a major array bound (8.3.4). 2882 else if (Old->getType()->isIncompleteArrayType() && 2883 New->getType()->isArrayType()) { 2884 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2885 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2886 if (Context.hasSameType(OldArray->getElementType(), 2887 NewArray->getElementType())) 2888 MergedT = New->getType(); 2889 } else if (Old->getType()->isArrayType() && 2890 New->getType()->isIncompleteArrayType()) { 2891 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2892 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2893 if (Context.hasSameType(OldArray->getElementType(), 2894 NewArray->getElementType())) 2895 MergedT = Old->getType(); 2896 } else if (New->getType()->isObjCObjectPointerType() && 2897 Old->getType()->isObjCObjectPointerType()) { 2898 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2899 Old->getType()); 2900 } 2901 } else { 2902 // C 6.2.7p2: 2903 // All declarations that refer to the same object or function shall have 2904 // compatible type. 2905 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2906 } 2907 if (MergedT.isNull()) { 2908 // It's OK if we couldn't merge types if either type is dependent, for a 2909 // block-scope variable. In other cases (static data members of class 2910 // templates, variable templates, ...), we require the types to be 2911 // equivalent. 2912 // FIXME: The C++ standard doesn't say anything about this. 2913 if ((New->getType()->isDependentType() || 2914 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2915 // If the old type was dependent, we can't merge with it, so the new type 2916 // becomes dependent for now. We'll reproduce the original type when we 2917 // instantiate the TypeSourceInfo for the variable. 2918 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2919 New->setType(Context.DependentTy); 2920 return; 2921 } 2922 2923 // FIXME: Even if this merging succeeds, some other non-visible declaration 2924 // of this variable might have an incompatible type. For instance: 2925 // 2926 // extern int arr[]; 2927 // void f() { extern int arr[2]; } 2928 // void g() { extern int arr[3]; } 2929 // 2930 // Neither C nor C++ requires a diagnostic for this, but we should still try 2931 // to diagnose it. 2932 Diag(New->getLocation(), diag::err_redefinition_different_type) 2933 << New->getDeclName() << New->getType() << Old->getType(); 2934 Diag(Old->getLocation(), diag::note_previous_definition); 2935 return New->setInvalidDecl(); 2936 } 2937 2938 // Don't actually update the type on the new declaration if the old 2939 // declaration was an extern declaration in a different scope. 2940 if (MergeTypeWithOld) 2941 New->setType(MergedT); 2942 } 2943 2944 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2945 LookupResult &Previous) { 2946 // C11 6.2.7p4: 2947 // For an identifier with internal or external linkage declared 2948 // in a scope in which a prior declaration of that identifier is 2949 // visible, if the prior declaration specifies internal or 2950 // external linkage, the type of the identifier at the later 2951 // declaration becomes the composite type. 2952 // 2953 // If the variable isn't visible, we do not merge with its type. 2954 if (Previous.isShadowed()) 2955 return false; 2956 2957 if (S.getLangOpts().CPlusPlus) { 2958 // C++11 [dcl.array]p3: 2959 // If there is a preceding declaration of the entity in the same 2960 // scope in which the bound was specified, an omitted array bound 2961 // is taken to be the same as in that earlier declaration. 2962 return NewVD->isPreviousDeclInSameBlockScope() || 2963 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2964 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2965 } else { 2966 // If the old declaration was function-local, don't merge with its 2967 // type unless we're in the same function. 2968 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2969 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2970 } 2971 } 2972 2973 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2974 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2975 /// situation, merging decls or emitting diagnostics as appropriate. 2976 /// 2977 /// Tentative definition rules (C99 6.9.2p2) are checked by 2978 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2979 /// definitions here, since the initializer hasn't been attached. 2980 /// 2981 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2982 // If the new decl is already invalid, don't do any other checking. 2983 if (New->isInvalidDecl()) 2984 return; 2985 2986 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 2987 2988 // Verify the old decl was also a variable or variable template. 2989 VarDecl *Old = 0; 2990 VarTemplateDecl *OldTemplate = 0; 2991 if (Previous.isSingleResult()) { 2992 if (NewTemplate) { 2993 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 2994 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0; 2995 } else 2996 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2997 } 2998 if (!Old) { 2999 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3000 << New->getDeclName(); 3001 Diag(Previous.getRepresentativeDecl()->getLocation(), 3002 diag::note_previous_definition); 3003 return New->setInvalidDecl(); 3004 } 3005 3006 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3007 return; 3008 3009 // Ensure the template parameters are compatible. 3010 if (NewTemplate && 3011 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3012 OldTemplate->getTemplateParameters(), 3013 /*Complain=*/true, TPL_TemplateMatch)) 3014 return; 3015 3016 // C++ [class.mem]p1: 3017 // A member shall not be declared twice in the member-specification [...] 3018 // 3019 // Here, we need only consider static data members. 3020 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3021 Diag(New->getLocation(), diag::err_duplicate_member) 3022 << New->getIdentifier(); 3023 Diag(Old->getLocation(), diag::note_previous_declaration); 3024 New->setInvalidDecl(); 3025 } 3026 3027 mergeDeclAttributes(New, Old); 3028 // Warn if an already-declared variable is made a weak_import in a subsequent 3029 // declaration 3030 if (New->hasAttr<WeakImportAttr>() && 3031 Old->getStorageClass() == SC_None && 3032 !Old->hasAttr<WeakImportAttr>()) { 3033 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3034 Diag(Old->getLocation(), diag::note_previous_definition); 3035 // Remove weak_import attribute on new declaration. 3036 New->dropAttr<WeakImportAttr>(); 3037 } 3038 3039 // Merge the types. 3040 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3041 3042 if (New->isInvalidDecl()) 3043 return; 3044 3045 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3046 if (New->getStorageClass() == SC_Static && 3047 !New->isStaticDataMember() && 3048 Old->hasExternalFormalLinkage()) { 3049 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3050 Diag(Old->getLocation(), diag::note_previous_definition); 3051 return New->setInvalidDecl(); 3052 } 3053 // C99 6.2.2p4: 3054 // For an identifier declared with the storage-class specifier 3055 // extern in a scope in which a prior declaration of that 3056 // identifier is visible,23) if the prior declaration specifies 3057 // internal or external linkage, the linkage of the identifier at 3058 // the later declaration is the same as the linkage specified at 3059 // the prior declaration. If no prior declaration is visible, or 3060 // if the prior declaration specifies no linkage, then the 3061 // identifier has external linkage. 3062 if (New->hasExternalStorage() && Old->hasLinkage()) 3063 /* Okay */; 3064 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3065 !New->isStaticDataMember() && 3066 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3067 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3068 Diag(Old->getLocation(), diag::note_previous_definition); 3069 return New->setInvalidDecl(); 3070 } 3071 3072 // Check if extern is followed by non-extern and vice-versa. 3073 if (New->hasExternalStorage() && 3074 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3075 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3076 Diag(Old->getLocation(), diag::note_previous_definition); 3077 return New->setInvalidDecl(); 3078 } 3079 if (Old->hasLinkage() && New->isLocalVarDecl() && 3080 !New->hasExternalStorage()) { 3081 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3082 Diag(Old->getLocation(), diag::note_previous_definition); 3083 return New->setInvalidDecl(); 3084 } 3085 3086 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3087 3088 // FIXME: The test for external storage here seems wrong? We still 3089 // need to check for mismatches. 3090 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3091 // Don't complain about out-of-line definitions of static members. 3092 !(Old->getLexicalDeclContext()->isRecord() && 3093 !New->getLexicalDeclContext()->isRecord())) { 3094 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3095 Diag(Old->getLocation(), diag::note_previous_definition); 3096 return New->setInvalidDecl(); 3097 } 3098 3099 if (New->getTLSKind() != Old->getTLSKind()) { 3100 if (!Old->getTLSKind()) { 3101 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3102 Diag(Old->getLocation(), diag::note_previous_declaration); 3103 } else if (!New->getTLSKind()) { 3104 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3105 Diag(Old->getLocation(), diag::note_previous_declaration); 3106 } else { 3107 // Do not allow redeclaration to change the variable between requiring 3108 // static and dynamic initialization. 3109 // FIXME: GCC allows this, but uses the TLS keyword on the first 3110 // declaration to determine the kind. Do we need to be compatible here? 3111 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3112 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3113 Diag(Old->getLocation(), diag::note_previous_declaration); 3114 } 3115 } 3116 3117 // C++ doesn't have tentative definitions, so go right ahead and check here. 3118 const VarDecl *Def; 3119 if (getLangOpts().CPlusPlus && 3120 New->isThisDeclarationADefinition() == VarDecl::Definition && 3121 (Def = Old->getDefinition())) { 3122 Diag(New->getLocation(), diag::err_redefinition) << New; 3123 Diag(Def->getLocation(), diag::note_previous_definition); 3124 New->setInvalidDecl(); 3125 return; 3126 } 3127 3128 if (haveIncompatibleLanguageLinkages(Old, New)) { 3129 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3130 Diag(Old->getLocation(), diag::note_previous_definition); 3131 New->setInvalidDecl(); 3132 return; 3133 } 3134 3135 // Merge "used" flag. 3136 if (Old->getMostRecentDecl()->isUsed(false)) 3137 New->setIsUsed(); 3138 3139 // Keep a chain of previous declarations. 3140 New->setPreviousDecl(Old); 3141 if (NewTemplate) 3142 NewTemplate->setPreviousDecl(OldTemplate); 3143 3144 // Inherit access appropriately. 3145 New->setAccess(Old->getAccess()); 3146 if (NewTemplate) 3147 NewTemplate->setAccess(New->getAccess()); 3148 } 3149 3150 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3151 /// no declarator (e.g. "struct foo;") is parsed. 3152 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3153 DeclSpec &DS) { 3154 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3155 } 3156 3157 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3158 if (!S.Context.getLangOpts().CPlusPlus) 3159 return; 3160 3161 if (isa<CXXRecordDecl>(Tag->getParent())) { 3162 // If this tag is the direct child of a class, number it if 3163 // it is anonymous. 3164 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3165 return; 3166 MangleNumberingContext &MCtx = 3167 S.Context.getManglingNumberContext(Tag->getParent()); 3168 S.Context.setManglingNumber( 3169 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3170 return; 3171 } 3172 3173 // If this tag isn't a direct child of a class, number it if it is local. 3174 Decl *ManglingContextDecl; 3175 if (MangleNumberingContext *MCtx = 3176 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3177 ManglingContextDecl)) { 3178 S.Context.setManglingNumber( 3179 Tag, 3180 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3181 } 3182 } 3183 3184 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3185 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3186 /// parameters to cope with template friend declarations. 3187 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3188 DeclSpec &DS, 3189 MultiTemplateParamsArg TemplateParams, 3190 bool IsExplicitInstantiation) { 3191 Decl *TagD = 0; 3192 TagDecl *Tag = 0; 3193 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3194 DS.getTypeSpecType() == DeclSpec::TST_struct || 3195 DS.getTypeSpecType() == DeclSpec::TST_interface || 3196 DS.getTypeSpecType() == DeclSpec::TST_union || 3197 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3198 TagD = DS.getRepAsDecl(); 3199 3200 if (!TagD) // We probably had an error 3201 return 0; 3202 3203 // Note that the above type specs guarantee that the 3204 // type rep is a Decl, whereas in many of the others 3205 // it's a Type. 3206 if (isa<TagDecl>(TagD)) 3207 Tag = cast<TagDecl>(TagD); 3208 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3209 Tag = CTD->getTemplatedDecl(); 3210 } 3211 3212 if (Tag) { 3213 HandleTagNumbering(*this, Tag, S); 3214 Tag->setFreeStanding(); 3215 if (Tag->isInvalidDecl()) 3216 return Tag; 3217 } 3218 3219 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3220 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3221 // or incomplete types shall not be restrict-qualified." 3222 if (TypeQuals & DeclSpec::TQ_restrict) 3223 Diag(DS.getRestrictSpecLoc(), 3224 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3225 << DS.getSourceRange(); 3226 } 3227 3228 if (DS.isConstexprSpecified()) { 3229 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3230 // and definitions of functions and variables. 3231 if (Tag) 3232 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3233 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3234 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3235 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3236 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3237 else 3238 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3239 // Don't emit warnings after this error. 3240 return TagD; 3241 } 3242 3243 DiagnoseFunctionSpecifiers(DS); 3244 3245 if (DS.isFriendSpecified()) { 3246 // If we're dealing with a decl but not a TagDecl, assume that 3247 // whatever routines created it handled the friendship aspect. 3248 if (TagD && !Tag) 3249 return 0; 3250 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3251 } 3252 3253 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3254 bool IsExplicitSpecialization = 3255 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3256 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3257 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3258 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3259 // nested-name-specifier unless it is an explicit instantiation 3260 // or an explicit specialization. 3261 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3262 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3263 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3264 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3265 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3266 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3267 << SS.getRange(); 3268 return 0; 3269 } 3270 3271 // Track whether this decl-specifier declares anything. 3272 bool DeclaresAnything = true; 3273 3274 // Handle anonymous struct definitions. 3275 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3276 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3277 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3278 if (getLangOpts().CPlusPlus || 3279 Record->getDeclContext()->isRecord()) 3280 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3281 3282 DeclaresAnything = false; 3283 } 3284 } 3285 3286 // Check for Microsoft C extension: anonymous struct member. 3287 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3288 CurContext->isRecord() && 3289 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3290 // Handle 2 kinds of anonymous struct: 3291 // struct STRUCT; 3292 // and 3293 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3294 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3295 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3296 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3297 DS.getRepAsType().get()->isStructureType())) { 3298 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3299 << DS.getSourceRange(); 3300 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3301 } 3302 } 3303 3304 // Skip all the checks below if we have a type error. 3305 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3306 (TagD && TagD->isInvalidDecl())) 3307 return TagD; 3308 3309 if (getLangOpts().CPlusPlus && 3310 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3311 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3312 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3313 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3314 DeclaresAnything = false; 3315 3316 if (!DS.isMissingDeclaratorOk()) { 3317 // Customize diagnostic for a typedef missing a name. 3318 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3319 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3320 << DS.getSourceRange(); 3321 else 3322 DeclaresAnything = false; 3323 } 3324 3325 if (DS.isModulePrivateSpecified() && 3326 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3327 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3328 << Tag->getTagKind() 3329 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3330 3331 ActOnDocumentableDecl(TagD); 3332 3333 // C 6.7/2: 3334 // A declaration [...] shall declare at least a declarator [...], a tag, 3335 // or the members of an enumeration. 3336 // C++ [dcl.dcl]p3: 3337 // [If there are no declarators], and except for the declaration of an 3338 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3339 // names into the program, or shall redeclare a name introduced by a 3340 // previous declaration. 3341 if (!DeclaresAnything) { 3342 // In C, we allow this as a (popular) extension / bug. Don't bother 3343 // producing further diagnostics for redundant qualifiers after this. 3344 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3345 return TagD; 3346 } 3347 3348 // C++ [dcl.stc]p1: 3349 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3350 // init-declarator-list of the declaration shall not be empty. 3351 // C++ [dcl.fct.spec]p1: 3352 // If a cv-qualifier appears in a decl-specifier-seq, the 3353 // init-declarator-list of the declaration shall not be empty. 3354 // 3355 // Spurious qualifiers here appear to be valid in C. 3356 unsigned DiagID = diag::warn_standalone_specifier; 3357 if (getLangOpts().CPlusPlus) 3358 DiagID = diag::ext_standalone_specifier; 3359 3360 // Note that a linkage-specification sets a storage class, but 3361 // 'extern "C" struct foo;' is actually valid and not theoretically 3362 // useless. 3363 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3364 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3365 Diag(DS.getStorageClassSpecLoc(), DiagID) 3366 << DeclSpec::getSpecifierName(SCS); 3367 3368 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3369 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3370 << DeclSpec::getSpecifierName(TSCS); 3371 if (DS.getTypeQualifiers()) { 3372 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3373 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3374 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3375 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3376 // Restrict is covered above. 3377 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3378 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3379 } 3380 3381 // Warn about ignored type attributes, for example: 3382 // __attribute__((aligned)) struct A; 3383 // Attributes should be placed after tag to apply to type declaration. 3384 if (!DS.getAttributes().empty()) { 3385 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3386 if (TypeSpecType == DeclSpec::TST_class || 3387 TypeSpecType == DeclSpec::TST_struct || 3388 TypeSpecType == DeclSpec::TST_interface || 3389 TypeSpecType == DeclSpec::TST_union || 3390 TypeSpecType == DeclSpec::TST_enum) { 3391 AttributeList* attrs = DS.getAttributes().getList(); 3392 while (attrs) { 3393 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3394 << attrs->getName() 3395 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3396 TypeSpecType == DeclSpec::TST_struct ? 1 : 3397 TypeSpecType == DeclSpec::TST_union ? 2 : 3398 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3399 attrs = attrs->getNext(); 3400 } 3401 } 3402 } 3403 3404 return TagD; 3405 } 3406 3407 /// We are trying to inject an anonymous member into the given scope; 3408 /// check if there's an existing declaration that can't be overloaded. 3409 /// 3410 /// \return true if this is a forbidden redeclaration 3411 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3412 Scope *S, 3413 DeclContext *Owner, 3414 DeclarationName Name, 3415 SourceLocation NameLoc, 3416 unsigned diagnostic) { 3417 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3418 Sema::ForRedeclaration); 3419 if (!SemaRef.LookupName(R, S)) return false; 3420 3421 if (R.getAsSingle<TagDecl>()) 3422 return false; 3423 3424 // Pick a representative declaration. 3425 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3426 assert(PrevDecl && "Expected a non-null Decl"); 3427 3428 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3429 return false; 3430 3431 SemaRef.Diag(NameLoc, diagnostic) << Name; 3432 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3433 3434 return true; 3435 } 3436 3437 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3438 /// anonymous struct or union AnonRecord into the owning context Owner 3439 /// and scope S. This routine will be invoked just after we realize 3440 /// that an unnamed union or struct is actually an anonymous union or 3441 /// struct, e.g., 3442 /// 3443 /// @code 3444 /// union { 3445 /// int i; 3446 /// float f; 3447 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3448 /// // f into the surrounding scope.x 3449 /// @endcode 3450 /// 3451 /// This routine is recursive, injecting the names of nested anonymous 3452 /// structs/unions into the owning context and scope as well. 3453 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3454 DeclContext *Owner, 3455 RecordDecl *AnonRecord, 3456 AccessSpecifier AS, 3457 SmallVectorImpl<NamedDecl *> &Chaining, 3458 bool MSAnonStruct) { 3459 unsigned diagKind 3460 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3461 : diag::err_anonymous_struct_member_redecl; 3462 3463 bool Invalid = false; 3464 3465 // Look every FieldDecl and IndirectFieldDecl with a name. 3466 for (auto *D : AnonRecord->decls()) { 3467 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3468 cast<NamedDecl>(D)->getDeclName()) { 3469 ValueDecl *VD = cast<ValueDecl>(D); 3470 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3471 VD->getLocation(), diagKind)) { 3472 // C++ [class.union]p2: 3473 // The names of the members of an anonymous union shall be 3474 // distinct from the names of any other entity in the 3475 // scope in which the anonymous union is declared. 3476 Invalid = true; 3477 } else { 3478 // C++ [class.union]p2: 3479 // For the purpose of name lookup, after the anonymous union 3480 // definition, the members of the anonymous union are 3481 // considered to have been defined in the scope in which the 3482 // anonymous union is declared. 3483 unsigned OldChainingSize = Chaining.size(); 3484 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3485 for (auto *PI : IF->chain()) 3486 Chaining.push_back(PI); 3487 else 3488 Chaining.push_back(VD); 3489 3490 assert(Chaining.size() >= 2); 3491 NamedDecl **NamedChain = 3492 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3493 for (unsigned i = 0; i < Chaining.size(); i++) 3494 NamedChain[i] = Chaining[i]; 3495 3496 IndirectFieldDecl* IndirectField = 3497 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3498 VD->getIdentifier(), VD->getType(), 3499 NamedChain, Chaining.size()); 3500 3501 IndirectField->setAccess(AS); 3502 IndirectField->setImplicit(); 3503 SemaRef.PushOnScopeChains(IndirectField, S); 3504 3505 // That includes picking up the appropriate access specifier. 3506 if (AS != AS_none) IndirectField->setAccess(AS); 3507 3508 Chaining.resize(OldChainingSize); 3509 } 3510 } 3511 } 3512 3513 return Invalid; 3514 } 3515 3516 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3517 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3518 /// illegal input values are mapped to SC_None. 3519 static StorageClass 3520 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3521 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3522 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3523 "Parser allowed 'typedef' as storage class VarDecl."); 3524 switch (StorageClassSpec) { 3525 case DeclSpec::SCS_unspecified: return SC_None; 3526 case DeclSpec::SCS_extern: 3527 if (DS.isExternInLinkageSpec()) 3528 return SC_None; 3529 return SC_Extern; 3530 case DeclSpec::SCS_static: return SC_Static; 3531 case DeclSpec::SCS_auto: return SC_Auto; 3532 case DeclSpec::SCS_register: return SC_Register; 3533 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3534 // Illegal SCSs map to None: error reporting is up to the caller. 3535 case DeclSpec::SCS_mutable: // Fall through. 3536 case DeclSpec::SCS_typedef: return SC_None; 3537 } 3538 llvm_unreachable("unknown storage class specifier"); 3539 } 3540 3541 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3542 assert(Record->hasInClassInitializer()); 3543 3544 for (const auto *I : Record->decls()) { 3545 const auto *FD = dyn_cast<FieldDecl>(I); 3546 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3547 FD = IFD->getAnonField(); 3548 if (FD && FD->hasInClassInitializer()) 3549 return FD->getLocation(); 3550 } 3551 3552 llvm_unreachable("couldn't find in-class initializer"); 3553 } 3554 3555 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3556 SourceLocation DefaultInitLoc) { 3557 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3558 return; 3559 3560 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3561 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3562 } 3563 3564 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3565 CXXRecordDecl *AnonUnion) { 3566 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3567 return; 3568 3569 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3570 } 3571 3572 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3573 /// anonymous structure or union. Anonymous unions are a C++ feature 3574 /// (C++ [class.union]) and a C11 feature; anonymous structures 3575 /// are a C11 feature and GNU C++ extension. 3576 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3577 AccessSpecifier AS, 3578 RecordDecl *Record, 3579 const PrintingPolicy &Policy) { 3580 DeclContext *Owner = Record->getDeclContext(); 3581 3582 // Diagnose whether this anonymous struct/union is an extension. 3583 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3584 Diag(Record->getLocation(), diag::ext_anonymous_union); 3585 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3586 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3587 else if (!Record->isUnion() && !getLangOpts().C11) 3588 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3589 3590 // C and C++ require different kinds of checks for anonymous 3591 // structs/unions. 3592 bool Invalid = false; 3593 if (getLangOpts().CPlusPlus) { 3594 const char* PrevSpec = 0; 3595 unsigned DiagID; 3596 if (Record->isUnion()) { 3597 // C++ [class.union]p6: 3598 // Anonymous unions declared in a named namespace or in the 3599 // global namespace shall be declared static. 3600 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3601 (isa<TranslationUnitDecl>(Owner) || 3602 (isa<NamespaceDecl>(Owner) && 3603 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3604 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3605 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3606 3607 // Recover by adding 'static'. 3608 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3609 PrevSpec, DiagID, Policy); 3610 } 3611 // C++ [class.union]p6: 3612 // A storage class is not allowed in a declaration of an 3613 // anonymous union in a class scope. 3614 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3615 isa<RecordDecl>(Owner)) { 3616 Diag(DS.getStorageClassSpecLoc(), 3617 diag::err_anonymous_union_with_storage_spec) 3618 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3619 3620 // Recover by removing the storage specifier. 3621 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3622 SourceLocation(), 3623 PrevSpec, DiagID, Context.getPrintingPolicy()); 3624 } 3625 } 3626 3627 // Ignore const/volatile/restrict qualifiers. 3628 if (DS.getTypeQualifiers()) { 3629 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3630 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3631 << Record->isUnion() << "const" 3632 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3633 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3634 Diag(DS.getVolatileSpecLoc(), 3635 diag::ext_anonymous_struct_union_qualified) 3636 << Record->isUnion() << "volatile" 3637 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3638 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3639 Diag(DS.getRestrictSpecLoc(), 3640 diag::ext_anonymous_struct_union_qualified) 3641 << Record->isUnion() << "restrict" 3642 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3643 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3644 Diag(DS.getAtomicSpecLoc(), 3645 diag::ext_anonymous_struct_union_qualified) 3646 << Record->isUnion() << "_Atomic" 3647 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3648 3649 DS.ClearTypeQualifiers(); 3650 } 3651 3652 // C++ [class.union]p2: 3653 // The member-specification of an anonymous union shall only 3654 // define non-static data members. [Note: nested types and 3655 // functions cannot be declared within an anonymous union. ] 3656 for (auto *Mem : Record->decls()) { 3657 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3658 // C++ [class.union]p3: 3659 // An anonymous union shall not have private or protected 3660 // members (clause 11). 3661 assert(FD->getAccess() != AS_none); 3662 if (FD->getAccess() != AS_public) { 3663 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3664 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3665 Invalid = true; 3666 } 3667 3668 // C++ [class.union]p1 3669 // An object of a class with a non-trivial constructor, a non-trivial 3670 // copy constructor, a non-trivial destructor, or a non-trivial copy 3671 // assignment operator cannot be a member of a union, nor can an 3672 // array of such objects. 3673 if (CheckNontrivialField(FD)) 3674 Invalid = true; 3675 } else if (Mem->isImplicit()) { 3676 // Any implicit members are fine. 3677 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3678 // This is a type that showed up in an 3679 // elaborated-type-specifier inside the anonymous struct or 3680 // union, but which actually declares a type outside of the 3681 // anonymous struct or union. It's okay. 3682 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3683 if (!MemRecord->isAnonymousStructOrUnion() && 3684 MemRecord->getDeclName()) { 3685 // Visual C++ allows type definition in anonymous struct or union. 3686 if (getLangOpts().MicrosoftExt) 3687 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3688 << (int)Record->isUnion(); 3689 else { 3690 // This is a nested type declaration. 3691 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3692 << (int)Record->isUnion(); 3693 Invalid = true; 3694 } 3695 } else { 3696 // This is an anonymous type definition within another anonymous type. 3697 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3698 // not part of standard C++. 3699 Diag(MemRecord->getLocation(), 3700 diag::ext_anonymous_record_with_anonymous_type) 3701 << (int)Record->isUnion(); 3702 } 3703 } else if (isa<AccessSpecDecl>(Mem)) { 3704 // Any access specifier is fine. 3705 } else { 3706 // We have something that isn't a non-static data 3707 // member. Complain about it. 3708 unsigned DK = diag::err_anonymous_record_bad_member; 3709 if (isa<TypeDecl>(Mem)) 3710 DK = diag::err_anonymous_record_with_type; 3711 else if (isa<FunctionDecl>(Mem)) 3712 DK = diag::err_anonymous_record_with_function; 3713 else if (isa<VarDecl>(Mem)) 3714 DK = diag::err_anonymous_record_with_static; 3715 3716 // Visual C++ allows type definition in anonymous struct or union. 3717 if (getLangOpts().MicrosoftExt && 3718 DK == diag::err_anonymous_record_with_type) 3719 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3720 << (int)Record->isUnion(); 3721 else { 3722 Diag(Mem->getLocation(), DK) 3723 << (int)Record->isUnion(); 3724 Invalid = true; 3725 } 3726 } 3727 } 3728 3729 // C++11 [class.union]p8 (DR1460): 3730 // At most one variant member of a union may have a 3731 // brace-or-equal-initializer. 3732 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3733 Owner->isRecord()) 3734 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3735 cast<CXXRecordDecl>(Record)); 3736 } 3737 3738 if (!Record->isUnion() && !Owner->isRecord()) { 3739 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3740 << (int)getLangOpts().CPlusPlus; 3741 Invalid = true; 3742 } 3743 3744 // Mock up a declarator. 3745 Declarator Dc(DS, Declarator::MemberContext); 3746 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3747 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3748 3749 // Create a declaration for this anonymous struct/union. 3750 NamedDecl *Anon = 0; 3751 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3752 Anon = FieldDecl::Create(Context, OwningClass, 3753 DS.getLocStart(), 3754 Record->getLocation(), 3755 /*IdentifierInfo=*/0, 3756 Context.getTypeDeclType(Record), 3757 TInfo, 3758 /*BitWidth=*/0, /*Mutable=*/false, 3759 /*InitStyle=*/ICIS_NoInit); 3760 Anon->setAccess(AS); 3761 if (getLangOpts().CPlusPlus) 3762 FieldCollector->Add(cast<FieldDecl>(Anon)); 3763 } else { 3764 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3765 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3766 if (SCSpec == DeclSpec::SCS_mutable) { 3767 // mutable can only appear on non-static class members, so it's always 3768 // an error here 3769 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3770 Invalid = true; 3771 SC = SC_None; 3772 } 3773 3774 Anon = VarDecl::Create(Context, Owner, 3775 DS.getLocStart(), 3776 Record->getLocation(), /*IdentifierInfo=*/0, 3777 Context.getTypeDeclType(Record), 3778 TInfo, SC); 3779 3780 // Default-initialize the implicit variable. This initialization will be 3781 // trivial in almost all cases, except if a union member has an in-class 3782 // initializer: 3783 // union { int n = 0; }; 3784 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3785 } 3786 Anon->setImplicit(); 3787 3788 // Mark this as an anonymous struct/union type. 3789 Record->setAnonymousStructOrUnion(true); 3790 3791 // Add the anonymous struct/union object to the current 3792 // context. We'll be referencing this object when we refer to one of 3793 // its members. 3794 Owner->addDecl(Anon); 3795 3796 // Inject the members of the anonymous struct/union into the owning 3797 // context and into the identifier resolver chain for name lookup 3798 // purposes. 3799 SmallVector<NamedDecl*, 2> Chain; 3800 Chain.push_back(Anon); 3801 3802 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3803 Chain, false)) 3804 Invalid = true; 3805 3806 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 3807 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 3808 Decl *ManglingContextDecl; 3809 if (MangleNumberingContext *MCtx = 3810 getCurrentMangleNumberContext(NewVD->getDeclContext(), 3811 ManglingContextDecl)) { 3812 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 3813 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 3814 } 3815 } 3816 } 3817 3818 if (Invalid) 3819 Anon->setInvalidDecl(); 3820 3821 return Anon; 3822 } 3823 3824 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3825 /// Microsoft C anonymous structure. 3826 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3827 /// Example: 3828 /// 3829 /// struct A { int a; }; 3830 /// struct B { struct A; int b; }; 3831 /// 3832 /// void foo() { 3833 /// B var; 3834 /// var.a = 3; 3835 /// } 3836 /// 3837 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3838 RecordDecl *Record) { 3839 3840 // If there is no Record, get the record via the typedef. 3841 if (!Record) 3842 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3843 3844 // Mock up a declarator. 3845 Declarator Dc(DS, Declarator::TypeNameContext); 3846 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3847 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3848 3849 // Create a declaration for this anonymous struct. 3850 NamedDecl* Anon = FieldDecl::Create(Context, 3851 cast<RecordDecl>(CurContext), 3852 DS.getLocStart(), 3853 DS.getLocStart(), 3854 /*IdentifierInfo=*/0, 3855 Context.getTypeDeclType(Record), 3856 TInfo, 3857 /*BitWidth=*/0, /*Mutable=*/false, 3858 /*InitStyle=*/ICIS_NoInit); 3859 Anon->setImplicit(); 3860 3861 // Add the anonymous struct object to the current context. 3862 CurContext->addDecl(Anon); 3863 3864 // Inject the members of the anonymous struct into the current 3865 // context and into the identifier resolver chain for name lookup 3866 // purposes. 3867 SmallVector<NamedDecl*, 2> Chain; 3868 Chain.push_back(Anon); 3869 3870 RecordDecl *RecordDef = Record->getDefinition(); 3871 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3872 RecordDef, AS_none, 3873 Chain, true)) 3874 Anon->setInvalidDecl(); 3875 3876 return Anon; 3877 } 3878 3879 /// GetNameForDeclarator - Determine the full declaration name for the 3880 /// given Declarator. 3881 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3882 return GetNameFromUnqualifiedId(D.getName()); 3883 } 3884 3885 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3886 DeclarationNameInfo 3887 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3888 DeclarationNameInfo NameInfo; 3889 NameInfo.setLoc(Name.StartLocation); 3890 3891 switch (Name.getKind()) { 3892 3893 case UnqualifiedId::IK_ImplicitSelfParam: 3894 case UnqualifiedId::IK_Identifier: 3895 NameInfo.setName(Name.Identifier); 3896 NameInfo.setLoc(Name.StartLocation); 3897 return NameInfo; 3898 3899 case UnqualifiedId::IK_OperatorFunctionId: 3900 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3901 Name.OperatorFunctionId.Operator)); 3902 NameInfo.setLoc(Name.StartLocation); 3903 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3904 = Name.OperatorFunctionId.SymbolLocations[0]; 3905 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3906 = Name.EndLocation.getRawEncoding(); 3907 return NameInfo; 3908 3909 case UnqualifiedId::IK_LiteralOperatorId: 3910 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3911 Name.Identifier)); 3912 NameInfo.setLoc(Name.StartLocation); 3913 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3914 return NameInfo; 3915 3916 case UnqualifiedId::IK_ConversionFunctionId: { 3917 TypeSourceInfo *TInfo; 3918 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3919 if (Ty.isNull()) 3920 return DeclarationNameInfo(); 3921 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3922 Context.getCanonicalType(Ty))); 3923 NameInfo.setLoc(Name.StartLocation); 3924 NameInfo.setNamedTypeInfo(TInfo); 3925 return NameInfo; 3926 } 3927 3928 case UnqualifiedId::IK_ConstructorName: { 3929 TypeSourceInfo *TInfo; 3930 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3931 if (Ty.isNull()) 3932 return DeclarationNameInfo(); 3933 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3934 Context.getCanonicalType(Ty))); 3935 NameInfo.setLoc(Name.StartLocation); 3936 NameInfo.setNamedTypeInfo(TInfo); 3937 return NameInfo; 3938 } 3939 3940 case UnqualifiedId::IK_ConstructorTemplateId: { 3941 // In well-formed code, we can only have a constructor 3942 // template-id that refers to the current context, so go there 3943 // to find the actual type being constructed. 3944 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3945 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3946 return DeclarationNameInfo(); 3947 3948 // Determine the type of the class being constructed. 3949 QualType CurClassType = Context.getTypeDeclType(CurClass); 3950 3951 // FIXME: Check two things: that the template-id names the same type as 3952 // CurClassType, and that the template-id does not occur when the name 3953 // was qualified. 3954 3955 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3956 Context.getCanonicalType(CurClassType))); 3957 NameInfo.setLoc(Name.StartLocation); 3958 // FIXME: should we retrieve TypeSourceInfo? 3959 NameInfo.setNamedTypeInfo(0); 3960 return NameInfo; 3961 } 3962 3963 case UnqualifiedId::IK_DestructorName: { 3964 TypeSourceInfo *TInfo; 3965 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3966 if (Ty.isNull()) 3967 return DeclarationNameInfo(); 3968 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3969 Context.getCanonicalType(Ty))); 3970 NameInfo.setLoc(Name.StartLocation); 3971 NameInfo.setNamedTypeInfo(TInfo); 3972 return NameInfo; 3973 } 3974 3975 case UnqualifiedId::IK_TemplateId: { 3976 TemplateName TName = Name.TemplateId->Template.get(); 3977 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3978 return Context.getNameForTemplate(TName, TNameLoc); 3979 } 3980 3981 } // switch (Name.getKind()) 3982 3983 llvm_unreachable("Unknown name kind"); 3984 } 3985 3986 static QualType getCoreType(QualType Ty) { 3987 do { 3988 if (Ty->isPointerType() || Ty->isReferenceType()) 3989 Ty = Ty->getPointeeType(); 3990 else if (Ty->isArrayType()) 3991 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3992 else 3993 return Ty.withoutLocalFastQualifiers(); 3994 } while (true); 3995 } 3996 3997 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3998 /// and Definition have "nearly" matching parameters. This heuristic is 3999 /// used to improve diagnostics in the case where an out-of-line function 4000 /// definition doesn't match any declaration within the class or namespace. 4001 /// Also sets Params to the list of indices to the parameters that differ 4002 /// between the declaration and the definition. If hasSimilarParameters 4003 /// returns true and Params is empty, then all of the parameters match. 4004 static bool hasSimilarParameters(ASTContext &Context, 4005 FunctionDecl *Declaration, 4006 FunctionDecl *Definition, 4007 SmallVectorImpl<unsigned> &Params) { 4008 Params.clear(); 4009 if (Declaration->param_size() != Definition->param_size()) 4010 return false; 4011 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4012 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4013 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4014 4015 // The parameter types are identical 4016 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4017 continue; 4018 4019 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4020 QualType DefParamBaseTy = getCoreType(DefParamTy); 4021 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4022 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4023 4024 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4025 (DeclTyName && DeclTyName == DefTyName)) 4026 Params.push_back(Idx); 4027 else // The two parameters aren't even close 4028 return false; 4029 } 4030 4031 return true; 4032 } 4033 4034 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4035 /// declarator needs to be rebuilt in the current instantiation. 4036 /// Any bits of declarator which appear before the name are valid for 4037 /// consideration here. That's specifically the type in the decl spec 4038 /// and the base type in any member-pointer chunks. 4039 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4040 DeclarationName Name) { 4041 // The types we specifically need to rebuild are: 4042 // - typenames, typeofs, and decltypes 4043 // - types which will become injected class names 4044 // Of course, we also need to rebuild any type referencing such a 4045 // type. It's safest to just say "dependent", but we call out a 4046 // few cases here. 4047 4048 DeclSpec &DS = D.getMutableDeclSpec(); 4049 switch (DS.getTypeSpecType()) { 4050 case DeclSpec::TST_typename: 4051 case DeclSpec::TST_typeofType: 4052 case DeclSpec::TST_underlyingType: 4053 case DeclSpec::TST_atomic: { 4054 // Grab the type from the parser. 4055 TypeSourceInfo *TSI = 0; 4056 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4057 if (T.isNull() || !T->isDependentType()) break; 4058 4059 // Make sure there's a type source info. This isn't really much 4060 // of a waste; most dependent types should have type source info 4061 // attached already. 4062 if (!TSI) 4063 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4064 4065 // Rebuild the type in the current instantiation. 4066 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4067 if (!TSI) return true; 4068 4069 // Store the new type back in the decl spec. 4070 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4071 DS.UpdateTypeRep(LocType); 4072 break; 4073 } 4074 4075 case DeclSpec::TST_decltype: 4076 case DeclSpec::TST_typeofExpr: { 4077 Expr *E = DS.getRepAsExpr(); 4078 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4079 if (Result.isInvalid()) return true; 4080 DS.UpdateExprRep(Result.get()); 4081 break; 4082 } 4083 4084 default: 4085 // Nothing to do for these decl specs. 4086 break; 4087 } 4088 4089 // It doesn't matter what order we do this in. 4090 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4091 DeclaratorChunk &Chunk = D.getTypeObject(I); 4092 4093 // The only type information in the declarator which can come 4094 // before the declaration name is the base type of a member 4095 // pointer. 4096 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4097 continue; 4098 4099 // Rebuild the scope specifier in-place. 4100 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4101 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4102 return true; 4103 } 4104 4105 return false; 4106 } 4107 4108 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4109 D.setFunctionDefinitionKind(FDK_Declaration); 4110 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4111 4112 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4113 Dcl && Dcl->getDeclContext()->isFileContext()) 4114 Dcl->setTopLevelDeclInObjCContainer(); 4115 4116 return Dcl; 4117 } 4118 4119 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4120 /// If T is the name of a class, then each of the following shall have a 4121 /// name different from T: 4122 /// - every static data member of class T; 4123 /// - every member function of class T 4124 /// - every member of class T that is itself a type; 4125 /// \returns true if the declaration name violates these rules. 4126 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4127 DeclarationNameInfo NameInfo) { 4128 DeclarationName Name = NameInfo.getName(); 4129 4130 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4131 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4132 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4133 return true; 4134 } 4135 4136 return false; 4137 } 4138 4139 /// \brief Diagnose a declaration whose declarator-id has the given 4140 /// nested-name-specifier. 4141 /// 4142 /// \param SS The nested-name-specifier of the declarator-id. 4143 /// 4144 /// \param DC The declaration context to which the nested-name-specifier 4145 /// resolves. 4146 /// 4147 /// \param Name The name of the entity being declared. 4148 /// 4149 /// \param Loc The location of the name of the entity being declared. 4150 /// 4151 /// \returns true if we cannot safely recover from this error, false otherwise. 4152 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4153 DeclarationName Name, 4154 SourceLocation Loc) { 4155 DeclContext *Cur = CurContext; 4156 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4157 Cur = Cur->getParent(); 4158 4159 // If the user provided a superfluous scope specifier that refers back to the 4160 // class in which the entity is already declared, diagnose and ignore it. 4161 // 4162 // class X { 4163 // void X::f(); 4164 // }; 4165 // 4166 // Note, it was once ill-formed to give redundant qualification in all 4167 // contexts, but that rule was removed by DR482. 4168 if (Cur->Equals(DC)) { 4169 if (Cur->isRecord()) { 4170 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4171 : diag::err_member_extra_qualification) 4172 << Name << FixItHint::CreateRemoval(SS.getRange()); 4173 SS.clear(); 4174 } else { 4175 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4176 } 4177 return false; 4178 } 4179 4180 // Check whether the qualifying scope encloses the scope of the original 4181 // declaration. 4182 if (!Cur->Encloses(DC)) { 4183 if (Cur->isRecord()) 4184 Diag(Loc, diag::err_member_qualification) 4185 << Name << SS.getRange(); 4186 else if (isa<TranslationUnitDecl>(DC)) 4187 Diag(Loc, diag::err_invalid_declarator_global_scope) 4188 << Name << SS.getRange(); 4189 else if (isa<FunctionDecl>(Cur)) 4190 Diag(Loc, diag::err_invalid_declarator_in_function) 4191 << Name << SS.getRange(); 4192 else if (isa<BlockDecl>(Cur)) 4193 Diag(Loc, diag::err_invalid_declarator_in_block) 4194 << Name << SS.getRange(); 4195 else 4196 Diag(Loc, diag::err_invalid_declarator_scope) 4197 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4198 4199 return true; 4200 } 4201 4202 if (Cur->isRecord()) { 4203 // Cannot qualify members within a class. 4204 Diag(Loc, diag::err_member_qualification) 4205 << Name << SS.getRange(); 4206 SS.clear(); 4207 4208 // C++ constructors and destructors with incorrect scopes can break 4209 // our AST invariants by having the wrong underlying types. If 4210 // that's the case, then drop this declaration entirely. 4211 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4212 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4213 !Context.hasSameType(Name.getCXXNameType(), 4214 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4215 return true; 4216 4217 return false; 4218 } 4219 4220 // C++11 [dcl.meaning]p1: 4221 // [...] "The nested-name-specifier of the qualified declarator-id shall 4222 // not begin with a decltype-specifer" 4223 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4224 while (SpecLoc.getPrefix()) 4225 SpecLoc = SpecLoc.getPrefix(); 4226 if (dyn_cast_or_null<DecltypeType>( 4227 SpecLoc.getNestedNameSpecifier()->getAsType())) 4228 Diag(Loc, diag::err_decltype_in_declarator) 4229 << SpecLoc.getTypeLoc().getSourceRange(); 4230 4231 return false; 4232 } 4233 4234 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4235 MultiTemplateParamsArg TemplateParamLists) { 4236 // TODO: consider using NameInfo for diagnostic. 4237 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4238 DeclarationName Name = NameInfo.getName(); 4239 4240 // All of these full declarators require an identifier. If it doesn't have 4241 // one, the ParsedFreeStandingDeclSpec action should be used. 4242 if (!Name) { 4243 if (!D.isInvalidType()) // Reject this if we think it is valid. 4244 Diag(D.getDeclSpec().getLocStart(), 4245 diag::err_declarator_need_ident) 4246 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4247 return 0; 4248 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4249 return 0; 4250 4251 // The scope passed in may not be a decl scope. Zip up the scope tree until 4252 // we find one that is. 4253 while ((S->getFlags() & Scope::DeclScope) == 0 || 4254 (S->getFlags() & Scope::TemplateParamScope) != 0) 4255 S = S->getParent(); 4256 4257 DeclContext *DC = CurContext; 4258 if (D.getCXXScopeSpec().isInvalid()) 4259 D.setInvalidType(); 4260 else if (D.getCXXScopeSpec().isSet()) { 4261 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4262 UPPC_DeclarationQualifier)) 4263 return 0; 4264 4265 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4266 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4267 if (!DC || isa<EnumDecl>(DC)) { 4268 // If we could not compute the declaration context, it's because the 4269 // declaration context is dependent but does not refer to a class, 4270 // class template, or class template partial specialization. Complain 4271 // and return early, to avoid the coming semantic disaster. 4272 Diag(D.getIdentifierLoc(), 4273 diag::err_template_qualified_declarator_no_match) 4274 << D.getCXXScopeSpec().getScopeRep() 4275 << D.getCXXScopeSpec().getRange(); 4276 return 0; 4277 } 4278 bool IsDependentContext = DC->isDependentContext(); 4279 4280 if (!IsDependentContext && 4281 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4282 return 0; 4283 4284 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4285 Diag(D.getIdentifierLoc(), 4286 diag::err_member_def_undefined_record) 4287 << Name << DC << D.getCXXScopeSpec().getRange(); 4288 D.setInvalidType(); 4289 } else if (!D.getDeclSpec().isFriendSpecified()) { 4290 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4291 Name, D.getIdentifierLoc())) { 4292 if (DC->isRecord()) 4293 return 0; 4294 4295 D.setInvalidType(); 4296 } 4297 } 4298 4299 // Check whether we need to rebuild the type of the given 4300 // declaration in the current instantiation. 4301 if (EnteringContext && IsDependentContext && 4302 TemplateParamLists.size() != 0) { 4303 ContextRAII SavedContext(*this, DC); 4304 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4305 D.setInvalidType(); 4306 } 4307 } 4308 4309 if (DiagnoseClassNameShadow(DC, NameInfo)) 4310 // If this is a typedef, we'll end up spewing multiple diagnostics. 4311 // Just return early; it's safer. 4312 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4313 return 0; 4314 4315 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4316 QualType R = TInfo->getType(); 4317 4318 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4319 UPPC_DeclarationType)) 4320 D.setInvalidType(); 4321 4322 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4323 ForRedeclaration); 4324 4325 // See if this is a redefinition of a variable in the same scope. 4326 if (!D.getCXXScopeSpec().isSet()) { 4327 bool IsLinkageLookup = false; 4328 bool CreateBuiltins = false; 4329 4330 // If the declaration we're planning to build will be a function 4331 // or object with linkage, then look for another declaration with 4332 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4333 // 4334 // If the declaration we're planning to build will be declared with 4335 // external linkage in the translation unit, create any builtin with 4336 // the same name. 4337 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4338 /* Do nothing*/; 4339 else if (CurContext->isFunctionOrMethod() && 4340 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4341 R->isFunctionType())) { 4342 IsLinkageLookup = true; 4343 CreateBuiltins = 4344 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4345 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4346 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4347 CreateBuiltins = true; 4348 4349 if (IsLinkageLookup) 4350 Previous.clear(LookupRedeclarationWithLinkage); 4351 4352 LookupName(Previous, S, CreateBuiltins); 4353 } else { // Something like "int foo::x;" 4354 LookupQualifiedName(Previous, DC); 4355 4356 // C++ [dcl.meaning]p1: 4357 // When the declarator-id is qualified, the declaration shall refer to a 4358 // previously declared member of the class or namespace to which the 4359 // qualifier refers (or, in the case of a namespace, of an element of the 4360 // inline namespace set of that namespace (7.3.1)) or to a specialization 4361 // thereof; [...] 4362 // 4363 // Note that we already checked the context above, and that we do not have 4364 // enough information to make sure that Previous contains the declaration 4365 // we want to match. For example, given: 4366 // 4367 // class X { 4368 // void f(); 4369 // void f(float); 4370 // }; 4371 // 4372 // void X::f(int) { } // ill-formed 4373 // 4374 // In this case, Previous will point to the overload set 4375 // containing the two f's declared in X, but neither of them 4376 // matches. 4377 4378 // C++ [dcl.meaning]p1: 4379 // [...] the member shall not merely have been introduced by a 4380 // using-declaration in the scope of the class or namespace nominated by 4381 // the nested-name-specifier of the declarator-id. 4382 RemoveUsingDecls(Previous); 4383 } 4384 4385 if (Previous.isSingleResult() && 4386 Previous.getFoundDecl()->isTemplateParameter()) { 4387 // Maybe we will complain about the shadowed template parameter. 4388 if (!D.isInvalidType()) 4389 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4390 Previous.getFoundDecl()); 4391 4392 // Just pretend that we didn't see the previous declaration. 4393 Previous.clear(); 4394 } 4395 4396 // In C++, the previous declaration we find might be a tag type 4397 // (class or enum). In this case, the new declaration will hide the 4398 // tag type. Note that this does does not apply if we're declaring a 4399 // typedef (C++ [dcl.typedef]p4). 4400 if (Previous.isSingleTagDecl() && 4401 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4402 Previous.clear(); 4403 4404 // Check that there are no default arguments other than in the parameters 4405 // of a function declaration (C++ only). 4406 if (getLangOpts().CPlusPlus) 4407 CheckExtraCXXDefaultArguments(D); 4408 4409 NamedDecl *New; 4410 4411 bool AddToScope = true; 4412 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4413 if (TemplateParamLists.size()) { 4414 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4415 return 0; 4416 } 4417 4418 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4419 } else if (R->isFunctionType()) { 4420 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4421 TemplateParamLists, 4422 AddToScope); 4423 } else { 4424 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4425 AddToScope); 4426 } 4427 4428 if (New == 0) 4429 return 0; 4430 4431 // If this has an identifier and is not an invalid redeclaration or 4432 // function template specialization, add it to the scope stack. 4433 if (New->getDeclName() && AddToScope && 4434 !(D.isRedeclaration() && New->isInvalidDecl())) { 4435 // Only make a locally-scoped extern declaration visible if it is the first 4436 // declaration of this entity. Qualified lookup for such an entity should 4437 // only find this declaration if there is no visible declaration of it. 4438 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4439 PushOnScopeChains(New, S, AddToContext); 4440 if (!AddToContext) 4441 CurContext->addHiddenDecl(New); 4442 } 4443 4444 return New; 4445 } 4446 4447 /// Helper method to turn variable array types into constant array 4448 /// types in certain situations which would otherwise be errors (for 4449 /// GCC compatibility). 4450 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4451 ASTContext &Context, 4452 bool &SizeIsNegative, 4453 llvm::APSInt &Oversized) { 4454 // This method tries to turn a variable array into a constant 4455 // array even when the size isn't an ICE. This is necessary 4456 // for compatibility with code that depends on gcc's buggy 4457 // constant expression folding, like struct {char x[(int)(char*)2];} 4458 SizeIsNegative = false; 4459 Oversized = 0; 4460 4461 if (T->isDependentType()) 4462 return QualType(); 4463 4464 QualifierCollector Qs; 4465 const Type *Ty = Qs.strip(T); 4466 4467 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4468 QualType Pointee = PTy->getPointeeType(); 4469 QualType FixedType = 4470 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4471 Oversized); 4472 if (FixedType.isNull()) return FixedType; 4473 FixedType = Context.getPointerType(FixedType); 4474 return Qs.apply(Context, FixedType); 4475 } 4476 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4477 QualType Inner = PTy->getInnerType(); 4478 QualType FixedType = 4479 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4480 Oversized); 4481 if (FixedType.isNull()) return FixedType; 4482 FixedType = Context.getParenType(FixedType); 4483 return Qs.apply(Context, FixedType); 4484 } 4485 4486 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4487 if (!VLATy) 4488 return QualType(); 4489 // FIXME: We should probably handle this case 4490 if (VLATy->getElementType()->isVariablyModifiedType()) 4491 return QualType(); 4492 4493 llvm::APSInt Res; 4494 if (!VLATy->getSizeExpr() || 4495 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4496 return QualType(); 4497 4498 // Check whether the array size is negative. 4499 if (Res.isSigned() && Res.isNegative()) { 4500 SizeIsNegative = true; 4501 return QualType(); 4502 } 4503 4504 // Check whether the array is too large to be addressed. 4505 unsigned ActiveSizeBits 4506 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4507 Res); 4508 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4509 Oversized = Res; 4510 return QualType(); 4511 } 4512 4513 return Context.getConstantArrayType(VLATy->getElementType(), 4514 Res, ArrayType::Normal, 0); 4515 } 4516 4517 static void 4518 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4519 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4520 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4521 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4522 DstPTL.getPointeeLoc()); 4523 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4524 return; 4525 } 4526 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4527 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4528 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4529 DstPTL.getInnerLoc()); 4530 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4531 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4532 return; 4533 } 4534 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4535 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4536 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4537 TypeLoc DstElemTL = DstATL.getElementLoc(); 4538 DstElemTL.initializeFullCopy(SrcElemTL); 4539 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4540 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4541 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4542 } 4543 4544 /// Helper method to turn variable array types into constant array 4545 /// types in certain situations which would otherwise be errors (for 4546 /// GCC compatibility). 4547 static TypeSourceInfo* 4548 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4549 ASTContext &Context, 4550 bool &SizeIsNegative, 4551 llvm::APSInt &Oversized) { 4552 QualType FixedTy 4553 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4554 SizeIsNegative, Oversized); 4555 if (FixedTy.isNull()) 4556 return 0; 4557 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4558 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4559 FixedTInfo->getTypeLoc()); 4560 return FixedTInfo; 4561 } 4562 4563 /// \brief Register the given locally-scoped extern "C" declaration so 4564 /// that it can be found later for redeclarations. We include any extern "C" 4565 /// declaration that is not visible in the translation unit here, not just 4566 /// function-scope declarations. 4567 void 4568 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4569 if (!getLangOpts().CPlusPlus && 4570 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4571 // Don't need to track declarations in the TU in C. 4572 return; 4573 4574 // Note that we have a locally-scoped external with this name. 4575 // FIXME: There can be multiple such declarations if they are functions marked 4576 // __attribute__((overloadable)) declared in function scope in C. 4577 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4578 } 4579 4580 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4581 if (ExternalSource) { 4582 // Load locally-scoped external decls from the external source. 4583 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4584 SmallVector<NamedDecl *, 4> Decls; 4585 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4586 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4587 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4588 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4589 if (Pos == LocallyScopedExternCDecls.end()) 4590 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4591 } 4592 } 4593 4594 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4595 return D ? D->getMostRecentDecl() : 0; 4596 } 4597 4598 /// \brief Diagnose function specifiers on a declaration of an identifier that 4599 /// does not identify a function. 4600 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4601 // FIXME: We should probably indicate the identifier in question to avoid 4602 // confusion for constructs like "inline int a(), b;" 4603 if (DS.isInlineSpecified()) 4604 Diag(DS.getInlineSpecLoc(), 4605 diag::err_inline_non_function); 4606 4607 if (DS.isVirtualSpecified()) 4608 Diag(DS.getVirtualSpecLoc(), 4609 diag::err_virtual_non_function); 4610 4611 if (DS.isExplicitSpecified()) 4612 Diag(DS.getExplicitSpecLoc(), 4613 diag::err_explicit_non_function); 4614 4615 if (DS.isNoreturnSpecified()) 4616 Diag(DS.getNoreturnSpecLoc(), 4617 diag::err_noreturn_non_function); 4618 } 4619 4620 NamedDecl* 4621 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4622 TypeSourceInfo *TInfo, LookupResult &Previous) { 4623 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4624 if (D.getCXXScopeSpec().isSet()) { 4625 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4626 << D.getCXXScopeSpec().getRange(); 4627 D.setInvalidType(); 4628 // Pretend we didn't see the scope specifier. 4629 DC = CurContext; 4630 Previous.clear(); 4631 } 4632 4633 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4634 4635 if (D.getDeclSpec().isConstexprSpecified()) 4636 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4637 << 1; 4638 4639 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4640 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4641 << D.getName().getSourceRange(); 4642 return 0; 4643 } 4644 4645 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4646 if (!NewTD) return 0; 4647 4648 // Handle attributes prior to checking for duplicates in MergeVarDecl 4649 ProcessDeclAttributes(S, NewTD, D); 4650 4651 CheckTypedefForVariablyModifiedType(S, NewTD); 4652 4653 bool Redeclaration = D.isRedeclaration(); 4654 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4655 D.setRedeclaration(Redeclaration); 4656 return ND; 4657 } 4658 4659 void 4660 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4661 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4662 // then it shall have block scope. 4663 // Note that variably modified types must be fixed before merging the decl so 4664 // that redeclarations will match. 4665 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4666 QualType T = TInfo->getType(); 4667 if (T->isVariablyModifiedType()) { 4668 getCurFunction()->setHasBranchProtectedScope(); 4669 4670 if (S->getFnParent() == 0) { 4671 bool SizeIsNegative; 4672 llvm::APSInt Oversized; 4673 TypeSourceInfo *FixedTInfo = 4674 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4675 SizeIsNegative, 4676 Oversized); 4677 if (FixedTInfo) { 4678 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4679 NewTD->setTypeSourceInfo(FixedTInfo); 4680 } else { 4681 if (SizeIsNegative) 4682 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4683 else if (T->isVariableArrayType()) 4684 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4685 else if (Oversized.getBoolValue()) 4686 Diag(NewTD->getLocation(), diag::err_array_too_large) 4687 << Oversized.toString(10); 4688 else 4689 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4690 NewTD->setInvalidDecl(); 4691 } 4692 } 4693 } 4694 } 4695 4696 4697 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4698 /// declares a typedef-name, either using the 'typedef' type specifier or via 4699 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4700 NamedDecl* 4701 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4702 LookupResult &Previous, bool &Redeclaration) { 4703 // Merge the decl with the existing one if appropriate. If the decl is 4704 // in an outer scope, it isn't the same thing. 4705 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4706 /*AllowInlineNamespace*/false); 4707 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4708 if (!Previous.empty()) { 4709 Redeclaration = true; 4710 MergeTypedefNameDecl(NewTD, Previous); 4711 } 4712 4713 // If this is the C FILE type, notify the AST context. 4714 if (IdentifierInfo *II = NewTD->getIdentifier()) 4715 if (!NewTD->isInvalidDecl() && 4716 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4717 if (II->isStr("FILE")) 4718 Context.setFILEDecl(NewTD); 4719 else if (II->isStr("jmp_buf")) 4720 Context.setjmp_bufDecl(NewTD); 4721 else if (II->isStr("sigjmp_buf")) 4722 Context.setsigjmp_bufDecl(NewTD); 4723 else if (II->isStr("ucontext_t")) 4724 Context.setucontext_tDecl(NewTD); 4725 } 4726 4727 return NewTD; 4728 } 4729 4730 /// \brief Determines whether the given declaration is an out-of-scope 4731 /// previous declaration. 4732 /// 4733 /// This routine should be invoked when name lookup has found a 4734 /// previous declaration (PrevDecl) that is not in the scope where a 4735 /// new declaration by the same name is being introduced. If the new 4736 /// declaration occurs in a local scope, previous declarations with 4737 /// linkage may still be considered previous declarations (C99 4738 /// 6.2.2p4-5, C++ [basic.link]p6). 4739 /// 4740 /// \param PrevDecl the previous declaration found by name 4741 /// lookup 4742 /// 4743 /// \param DC the context in which the new declaration is being 4744 /// declared. 4745 /// 4746 /// \returns true if PrevDecl is an out-of-scope previous declaration 4747 /// for a new delcaration with the same name. 4748 static bool 4749 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4750 ASTContext &Context) { 4751 if (!PrevDecl) 4752 return false; 4753 4754 if (!PrevDecl->hasLinkage()) 4755 return false; 4756 4757 if (Context.getLangOpts().CPlusPlus) { 4758 // C++ [basic.link]p6: 4759 // If there is a visible declaration of an entity with linkage 4760 // having the same name and type, ignoring entities declared 4761 // outside the innermost enclosing namespace scope, the block 4762 // scope declaration declares that same entity and receives the 4763 // linkage of the previous declaration. 4764 DeclContext *OuterContext = DC->getRedeclContext(); 4765 if (!OuterContext->isFunctionOrMethod()) 4766 // This rule only applies to block-scope declarations. 4767 return false; 4768 4769 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4770 if (PrevOuterContext->isRecord()) 4771 // We found a member function: ignore it. 4772 return false; 4773 4774 // Find the innermost enclosing namespace for the new and 4775 // previous declarations. 4776 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4777 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4778 4779 // The previous declaration is in a different namespace, so it 4780 // isn't the same function. 4781 if (!OuterContext->Equals(PrevOuterContext)) 4782 return false; 4783 } 4784 4785 return true; 4786 } 4787 4788 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4789 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4790 if (!SS.isSet()) return; 4791 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4792 } 4793 4794 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4795 QualType type = decl->getType(); 4796 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4797 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4798 // Various kinds of declaration aren't allowed to be __autoreleasing. 4799 unsigned kind = -1U; 4800 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4801 if (var->hasAttr<BlocksAttr>()) 4802 kind = 0; // __block 4803 else if (!var->hasLocalStorage()) 4804 kind = 1; // global 4805 } else if (isa<ObjCIvarDecl>(decl)) { 4806 kind = 3; // ivar 4807 } else if (isa<FieldDecl>(decl)) { 4808 kind = 2; // field 4809 } 4810 4811 if (kind != -1U) { 4812 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4813 << kind; 4814 } 4815 } else if (lifetime == Qualifiers::OCL_None) { 4816 // Try to infer lifetime. 4817 if (!type->isObjCLifetimeType()) 4818 return false; 4819 4820 lifetime = type->getObjCARCImplicitLifetime(); 4821 type = Context.getLifetimeQualifiedType(type, lifetime); 4822 decl->setType(type); 4823 } 4824 4825 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4826 // Thread-local variables cannot have lifetime. 4827 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4828 var->getTLSKind()) { 4829 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4830 << var->getType(); 4831 return true; 4832 } 4833 } 4834 4835 return false; 4836 } 4837 4838 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4839 // Ensure that an auto decl is deduced otherwise the checks below might cache 4840 // the wrong linkage. 4841 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4842 4843 // 'weak' only applies to declarations with external linkage. 4844 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4845 if (!ND.isExternallyVisible()) { 4846 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4847 ND.dropAttr<WeakAttr>(); 4848 } 4849 } 4850 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4851 if (ND.isExternallyVisible()) { 4852 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4853 ND.dropAttr<WeakRefAttr>(); 4854 } 4855 } 4856 4857 // 'selectany' only applies to externally visible varable declarations. 4858 // It does not apply to functions. 4859 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4860 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4861 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4862 ND.dropAttr<SelectAnyAttr>(); 4863 } 4864 } 4865 } 4866 4867 /// Given that we are within the definition of the given function, 4868 /// will that definition behave like C99's 'inline', where the 4869 /// definition is discarded except for optimization purposes? 4870 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4871 // Try to avoid calling GetGVALinkageForFunction. 4872 4873 // All cases of this require the 'inline' keyword. 4874 if (!FD->isInlined()) return false; 4875 4876 // This is only possible in C++ with the gnu_inline attribute. 4877 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4878 return false; 4879 4880 // Okay, go ahead and call the relatively-more-expensive function. 4881 4882 #ifndef NDEBUG 4883 // AST quite reasonably asserts that it's working on a function 4884 // definition. We don't really have a way to tell it that we're 4885 // currently defining the function, so just lie to it in +Asserts 4886 // builds. This is an awful hack. 4887 FD->setLazyBody(1); 4888 #endif 4889 4890 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4891 4892 #ifndef NDEBUG 4893 FD->setLazyBody(0); 4894 #endif 4895 4896 return isC99Inline; 4897 } 4898 4899 /// Determine whether a variable is extern "C" prior to attaching 4900 /// an initializer. We can't just call isExternC() here, because that 4901 /// will also compute and cache whether the declaration is externally 4902 /// visible, which might change when we attach the initializer. 4903 /// 4904 /// This can only be used if the declaration is known to not be a 4905 /// redeclaration of an internal linkage declaration. 4906 /// 4907 /// For instance: 4908 /// 4909 /// auto x = []{}; 4910 /// 4911 /// Attaching the initializer here makes this declaration not externally 4912 /// visible, because its type has internal linkage. 4913 /// 4914 /// FIXME: This is a hack. 4915 template<typename T> 4916 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4917 if (S.getLangOpts().CPlusPlus) { 4918 // In C++, the overloadable attribute negates the effects of extern "C". 4919 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4920 return false; 4921 } 4922 return D->isExternC(); 4923 } 4924 4925 static bool shouldConsiderLinkage(const VarDecl *VD) { 4926 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4927 if (DC->isFunctionOrMethod()) 4928 return VD->hasExternalStorage(); 4929 if (DC->isFileContext()) 4930 return true; 4931 if (DC->isRecord()) 4932 return false; 4933 llvm_unreachable("Unexpected context"); 4934 } 4935 4936 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4937 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4938 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4939 return true; 4940 if (DC->isRecord()) 4941 return false; 4942 llvm_unreachable("Unexpected context"); 4943 } 4944 4945 /// Adjust the \c DeclContext for a function or variable that might be a 4946 /// function-local external declaration. 4947 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 4948 if (!DC->isFunctionOrMethod()) 4949 return false; 4950 4951 // If this is a local extern function or variable declared within a function 4952 // template, don't add it into the enclosing namespace scope until it is 4953 // instantiated; it might have a dependent type right now. 4954 if (DC->isDependentContext()) 4955 return true; 4956 4957 // C++11 [basic.link]p7: 4958 // When a block scope declaration of an entity with linkage is not found to 4959 // refer to some other declaration, then that entity is a member of the 4960 // innermost enclosing namespace. 4961 // 4962 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 4963 // semantically-enclosing namespace, not a lexically-enclosing one. 4964 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 4965 DC = DC->getParent(); 4966 return true; 4967 } 4968 4969 NamedDecl * 4970 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4971 TypeSourceInfo *TInfo, LookupResult &Previous, 4972 MultiTemplateParamsArg TemplateParamLists, 4973 bool &AddToScope) { 4974 QualType R = TInfo->getType(); 4975 DeclarationName Name = GetNameForDeclarator(D).getName(); 4976 4977 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4978 VarDecl::StorageClass SC = 4979 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 4980 4981 DeclContext *OriginalDC = DC; 4982 bool IsLocalExternDecl = SC == SC_Extern && 4983 adjustContextForLocalExternDecl(DC); 4984 4985 if (getLangOpts().OpenCL) { 4986 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 4987 QualType NR = R; 4988 while (NR->isPointerType()) { 4989 if (NR->isFunctionPointerType()) { 4990 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 4991 D.setInvalidType(); 4992 break; 4993 } 4994 NR = NR->getPointeeType(); 4995 } 4996 4997 if (!getOpenCLOptions().cl_khr_fp16) { 4998 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4999 // half array type (unless the cl_khr_fp16 extension is enabled). 5000 if (Context.getBaseElementType(R)->isHalfType()) { 5001 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5002 D.setInvalidType(); 5003 } 5004 } 5005 } 5006 5007 if (SCSpec == DeclSpec::SCS_mutable) { 5008 // mutable can only appear on non-static class members, so it's always 5009 // an error here 5010 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5011 D.setInvalidType(); 5012 SC = SC_None; 5013 } 5014 5015 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5016 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5017 D.getDeclSpec().getStorageClassSpecLoc())) { 5018 // In C++11, the 'register' storage class specifier is deprecated. 5019 // Suppress the warning in system macros, it's used in macros in some 5020 // popular C system headers, such as in glibc's htonl() macro. 5021 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5022 diag::warn_deprecated_register) 5023 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5024 } 5025 5026 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5027 if (!II) { 5028 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5029 << Name; 5030 return 0; 5031 } 5032 5033 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5034 5035 if (!DC->isRecord() && S->getFnParent() == 0) { 5036 // C99 6.9p2: The storage-class specifiers auto and register shall not 5037 // appear in the declaration specifiers in an external declaration. 5038 if (SC == SC_Auto || SC == SC_Register) { 5039 // If this is a register variable with an asm label specified, then this 5040 // is a GNU extension. 5041 if (SC == SC_Register && D.getAsmLabel()) 5042 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 5043 else 5044 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5045 D.setInvalidType(); 5046 } 5047 } 5048 5049 if (getLangOpts().OpenCL) { 5050 // Set up the special work-group-local storage class for variables in the 5051 // OpenCL __local address space. 5052 if (R.getAddressSpace() == LangAS::opencl_local) { 5053 SC = SC_OpenCLWorkGroupLocal; 5054 } 5055 5056 // OpenCL v1.2 s6.9.b p4: 5057 // The sampler type cannot be used with the __local and __global address 5058 // space qualifiers. 5059 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5060 R.getAddressSpace() == LangAS::opencl_global)) { 5061 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5062 } 5063 5064 // OpenCL 1.2 spec, p6.9 r: 5065 // The event type cannot be used to declare a program scope variable. 5066 // The event type cannot be used with the __local, __constant and __global 5067 // address space qualifiers. 5068 if (R->isEventT()) { 5069 if (S->getParent() == 0) { 5070 Diag(D.getLocStart(), diag::err_event_t_global_var); 5071 D.setInvalidType(); 5072 } 5073 5074 if (R.getAddressSpace()) { 5075 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5076 D.setInvalidType(); 5077 } 5078 } 5079 } 5080 5081 bool IsExplicitSpecialization = false; 5082 bool IsVariableTemplateSpecialization = false; 5083 bool IsPartialSpecialization = false; 5084 bool IsVariableTemplate = false; 5085 VarDecl *NewVD = 0; 5086 VarTemplateDecl *NewTemplate = 0; 5087 TemplateParameterList *TemplateParams = 0; 5088 if (!getLangOpts().CPlusPlus) { 5089 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5090 D.getIdentifierLoc(), II, 5091 R, TInfo, SC); 5092 5093 if (D.isInvalidType()) 5094 NewVD->setInvalidDecl(); 5095 } else { 5096 bool Invalid = false; 5097 5098 if (DC->isRecord() && !CurContext->isRecord()) { 5099 // This is an out-of-line definition of a static data member. 5100 switch (SC) { 5101 case SC_None: 5102 break; 5103 case SC_Static: 5104 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5105 diag::err_static_out_of_line) 5106 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5107 break; 5108 case SC_Auto: 5109 case SC_Register: 5110 case SC_Extern: 5111 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5112 // to names of variables declared in a block or to function parameters. 5113 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5114 // of class members 5115 5116 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5117 diag::err_storage_class_for_static_member) 5118 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5119 break; 5120 case SC_PrivateExtern: 5121 llvm_unreachable("C storage class in c++!"); 5122 case SC_OpenCLWorkGroupLocal: 5123 llvm_unreachable("OpenCL storage class in c++!"); 5124 } 5125 } 5126 5127 if (SC == SC_Static && CurContext->isRecord()) { 5128 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5129 if (RD->isLocalClass()) 5130 Diag(D.getIdentifierLoc(), 5131 diag::err_static_data_member_not_allowed_in_local_class) 5132 << Name << RD->getDeclName(); 5133 5134 // C++98 [class.union]p1: If a union contains a static data member, 5135 // the program is ill-formed. C++11 drops this restriction. 5136 if (RD->isUnion()) 5137 Diag(D.getIdentifierLoc(), 5138 getLangOpts().CPlusPlus11 5139 ? diag::warn_cxx98_compat_static_data_member_in_union 5140 : diag::ext_static_data_member_in_union) << Name; 5141 // We conservatively disallow static data members in anonymous structs. 5142 else if (!RD->getDeclName()) 5143 Diag(D.getIdentifierLoc(), 5144 diag::err_static_data_member_not_allowed_in_anon_struct) 5145 << Name << RD->isUnion(); 5146 } 5147 } 5148 5149 // Match up the template parameter lists with the scope specifier, then 5150 // determine whether we have a template or a template specialization. 5151 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5152 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5153 D.getCXXScopeSpec(), TemplateParamLists, 5154 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5155 5156 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId && 5157 !TemplateParams) { 5158 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5159 5160 // We have encountered something that the user meant to be a 5161 // specialization (because it has explicitly-specified template 5162 // arguments) but that was not introduced with a "template<>" (or had 5163 // too few of them). 5164 // FIXME: Differentiate between attempts for explicit instantiations 5165 // (starting with "template") and the rest. 5166 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5167 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5168 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5169 "template<> "); 5170 IsExplicitSpecialization = true; 5171 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(), 5172 SourceLocation(), 0, 0, 5173 SourceLocation()); 5174 } 5175 5176 if (TemplateParams) { 5177 if (!TemplateParams->size() && 5178 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5179 // There is an extraneous 'template<>' for this variable. Complain 5180 // about it, but allow the declaration of the variable. 5181 Diag(TemplateParams->getTemplateLoc(), 5182 diag::err_template_variable_noparams) 5183 << II 5184 << SourceRange(TemplateParams->getTemplateLoc(), 5185 TemplateParams->getRAngleLoc()); 5186 TemplateParams = 0; 5187 } else { 5188 // Only C++1y supports variable templates (N3651). 5189 Diag(D.getIdentifierLoc(), 5190 getLangOpts().CPlusPlus1y 5191 ? diag::warn_cxx11_compat_variable_template 5192 : diag::ext_variable_template); 5193 5194 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5195 // This is an explicit specialization or a partial specialization. 5196 // FIXME: Check that we can declare a specialization here. 5197 IsVariableTemplateSpecialization = true; 5198 IsPartialSpecialization = TemplateParams->size() > 0; 5199 } else { // if (TemplateParams->size() > 0) 5200 // This is a template declaration. 5201 IsVariableTemplate = true; 5202 5203 // Check that we can declare a template here. 5204 if (CheckTemplateDeclScope(S, TemplateParams)) 5205 return 0; 5206 } 5207 } 5208 } 5209 5210 if (IsVariableTemplateSpecialization) { 5211 SourceLocation TemplateKWLoc = 5212 TemplateParamLists.size() > 0 5213 ? TemplateParamLists[0]->getTemplateLoc() 5214 : SourceLocation(); 5215 DeclResult Res = ActOnVarTemplateSpecialization( 5216 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5217 IsPartialSpecialization); 5218 if (Res.isInvalid()) 5219 return 0; 5220 NewVD = cast<VarDecl>(Res.get()); 5221 AddToScope = false; 5222 } else 5223 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5224 D.getIdentifierLoc(), II, R, TInfo, SC); 5225 5226 // If this is supposed to be a variable template, create it as such. 5227 if (IsVariableTemplate) { 5228 NewTemplate = 5229 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5230 TemplateParams, NewVD); 5231 NewVD->setDescribedVarTemplate(NewTemplate); 5232 } 5233 5234 // If this decl has an auto type in need of deduction, make a note of the 5235 // Decl so we can diagnose uses of it in its own initializer. 5236 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5237 ParsingInitForAutoVars.insert(NewVD); 5238 5239 if (D.isInvalidType() || Invalid) { 5240 NewVD->setInvalidDecl(); 5241 if (NewTemplate) 5242 NewTemplate->setInvalidDecl(); 5243 } 5244 5245 SetNestedNameSpecifier(NewVD, D); 5246 5247 // If we have any template parameter lists that don't directly belong to 5248 // the variable (matching the scope specifier), store them. 5249 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5250 if (TemplateParamLists.size() > VDTemplateParamLists) 5251 NewVD->setTemplateParameterListsInfo( 5252 Context, TemplateParamLists.size() - VDTemplateParamLists, 5253 TemplateParamLists.data()); 5254 5255 if (D.getDeclSpec().isConstexprSpecified()) 5256 NewVD->setConstexpr(true); 5257 } 5258 5259 // Set the lexical context. If the declarator has a C++ scope specifier, the 5260 // lexical context will be different from the semantic context. 5261 NewVD->setLexicalDeclContext(CurContext); 5262 if (NewTemplate) 5263 NewTemplate->setLexicalDeclContext(CurContext); 5264 5265 if (IsLocalExternDecl) 5266 NewVD->setLocalExternDecl(); 5267 5268 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5269 if (NewVD->hasLocalStorage()) { 5270 // C++11 [dcl.stc]p4: 5271 // When thread_local is applied to a variable of block scope the 5272 // storage-class-specifier static is implied if it does not appear 5273 // explicitly. 5274 // Core issue: 'static' is not implied if the variable is declared 5275 // 'extern'. 5276 if (SCSpec == DeclSpec::SCS_unspecified && 5277 TSCS == DeclSpec::TSCS_thread_local && 5278 DC->isFunctionOrMethod()) 5279 NewVD->setTSCSpec(TSCS); 5280 else 5281 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5282 diag::err_thread_non_global) 5283 << DeclSpec::getSpecifierName(TSCS); 5284 } else if (!Context.getTargetInfo().isTLSSupported()) 5285 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5286 diag::err_thread_unsupported); 5287 else 5288 NewVD->setTSCSpec(TSCS); 5289 } 5290 5291 // C99 6.7.4p3 5292 // An inline definition of a function with external linkage shall 5293 // not contain a definition of a modifiable object with static or 5294 // thread storage duration... 5295 // We only apply this when the function is required to be defined 5296 // elsewhere, i.e. when the function is not 'extern inline'. Note 5297 // that a local variable with thread storage duration still has to 5298 // be marked 'static'. Also note that it's possible to get these 5299 // semantics in C++ using __attribute__((gnu_inline)). 5300 if (SC == SC_Static && S->getFnParent() != 0 && 5301 !NewVD->getType().isConstQualified()) { 5302 FunctionDecl *CurFD = getCurFunctionDecl(); 5303 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5304 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5305 diag::warn_static_local_in_extern_inline); 5306 MaybeSuggestAddingStaticToDecl(CurFD); 5307 } 5308 } 5309 5310 if (D.getDeclSpec().isModulePrivateSpecified()) { 5311 if (IsVariableTemplateSpecialization) 5312 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5313 << (IsPartialSpecialization ? 1 : 0) 5314 << FixItHint::CreateRemoval( 5315 D.getDeclSpec().getModulePrivateSpecLoc()); 5316 else if (IsExplicitSpecialization) 5317 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5318 << 2 5319 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5320 else if (NewVD->hasLocalStorage()) 5321 Diag(NewVD->getLocation(), diag::err_module_private_local) 5322 << 0 << NewVD->getDeclName() 5323 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5324 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5325 else { 5326 NewVD->setModulePrivate(); 5327 if (NewTemplate) 5328 NewTemplate->setModulePrivate(); 5329 } 5330 } 5331 5332 // Handle attributes prior to checking for duplicates in MergeVarDecl 5333 ProcessDeclAttributes(S, NewVD, D); 5334 5335 if (NewVD->hasAttrs()) 5336 CheckAlignasUnderalignment(NewVD); 5337 5338 if (getLangOpts().CUDA) { 5339 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5340 // storage [duration]." 5341 if (SC == SC_None && S->getFnParent() != 0 && 5342 (NewVD->hasAttr<CUDASharedAttr>() || 5343 NewVD->hasAttr<CUDAConstantAttr>())) { 5344 NewVD->setStorageClass(SC_Static); 5345 } 5346 } 5347 5348 // In auto-retain/release, infer strong retension for variables of 5349 // retainable type. 5350 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5351 NewVD->setInvalidDecl(); 5352 5353 // Handle GNU asm-label extension (encoded as an attribute). 5354 if (Expr *E = (Expr*)D.getAsmLabel()) { 5355 // The parser guarantees this is a string. 5356 StringLiteral *SE = cast<StringLiteral>(E); 5357 StringRef Label = SE->getString(); 5358 if (S->getFnParent() != 0) { 5359 switch (SC) { 5360 case SC_None: 5361 case SC_Auto: 5362 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5363 break; 5364 case SC_Register: 5365 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5366 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5367 break; 5368 case SC_Static: 5369 case SC_Extern: 5370 case SC_PrivateExtern: 5371 case SC_OpenCLWorkGroupLocal: 5372 break; 5373 } 5374 } 5375 5376 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5377 Context, Label, 0)); 5378 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5379 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5380 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5381 if (I != ExtnameUndeclaredIdentifiers.end()) { 5382 NewVD->addAttr(I->second); 5383 ExtnameUndeclaredIdentifiers.erase(I); 5384 } 5385 } 5386 5387 // Diagnose shadowed variables before filtering for scope. 5388 if (D.getCXXScopeSpec().isEmpty()) 5389 CheckShadow(S, NewVD, Previous); 5390 5391 // Don't consider existing declarations that are in a different 5392 // scope and are out-of-semantic-context declarations (if the new 5393 // declaration has linkage). 5394 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5395 D.getCXXScopeSpec().isNotEmpty() || 5396 IsExplicitSpecialization || 5397 IsVariableTemplateSpecialization); 5398 5399 // Check whether the previous declaration is in the same block scope. This 5400 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5401 if (getLangOpts().CPlusPlus && 5402 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5403 NewVD->setPreviousDeclInSameBlockScope( 5404 Previous.isSingleResult() && !Previous.isShadowed() && 5405 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5406 5407 if (!getLangOpts().CPlusPlus) { 5408 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5409 } else { 5410 // If this is an explicit specialization of a static data member, check it. 5411 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5412 CheckMemberSpecialization(NewVD, Previous)) 5413 NewVD->setInvalidDecl(); 5414 5415 // Merge the decl with the existing one if appropriate. 5416 if (!Previous.empty()) { 5417 if (Previous.isSingleResult() && 5418 isa<FieldDecl>(Previous.getFoundDecl()) && 5419 D.getCXXScopeSpec().isSet()) { 5420 // The user tried to define a non-static data member 5421 // out-of-line (C++ [dcl.meaning]p1). 5422 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5423 << D.getCXXScopeSpec().getRange(); 5424 Previous.clear(); 5425 NewVD->setInvalidDecl(); 5426 } 5427 } else if (D.getCXXScopeSpec().isSet()) { 5428 // No previous declaration in the qualifying scope. 5429 Diag(D.getIdentifierLoc(), diag::err_no_member) 5430 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5431 << D.getCXXScopeSpec().getRange(); 5432 NewVD->setInvalidDecl(); 5433 } 5434 5435 if (!IsVariableTemplateSpecialization) 5436 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5437 5438 if (NewTemplate) { 5439 VarTemplateDecl *PrevVarTemplate = 5440 NewVD->getPreviousDecl() 5441 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5442 : 0; 5443 5444 // Check the template parameter list of this declaration, possibly 5445 // merging in the template parameter list from the previous variable 5446 // template declaration. 5447 if (CheckTemplateParameterList( 5448 TemplateParams, 5449 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5450 : 0, 5451 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5452 DC->isDependentContext()) 5453 ? TPC_ClassTemplateMember 5454 : TPC_VarTemplate)) 5455 NewVD->setInvalidDecl(); 5456 5457 // If we are providing an explicit specialization of a static variable 5458 // template, make a note of that. 5459 if (PrevVarTemplate && 5460 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5461 PrevVarTemplate->setMemberSpecialization(); 5462 } 5463 } 5464 5465 ProcessPragmaWeak(S, NewVD); 5466 5467 // If this is the first declaration of an extern C variable, update 5468 // the map of such variables. 5469 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5470 isIncompleteDeclExternC(*this, NewVD)) 5471 RegisterLocallyScopedExternCDecl(NewVD, S); 5472 5473 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5474 Decl *ManglingContextDecl; 5475 if (MangleNumberingContext *MCtx = 5476 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5477 ManglingContextDecl)) { 5478 Context.setManglingNumber( 5479 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5480 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5481 } 5482 } 5483 5484 if (NewTemplate) { 5485 if (NewVD->isInvalidDecl()) 5486 NewTemplate->setInvalidDecl(); 5487 ActOnDocumentableDecl(NewTemplate); 5488 return NewTemplate; 5489 } 5490 5491 return NewVD; 5492 } 5493 5494 /// \brief Diagnose variable or built-in function shadowing. Implements 5495 /// -Wshadow. 5496 /// 5497 /// This method is called whenever a VarDecl is added to a "useful" 5498 /// scope. 5499 /// 5500 /// \param S the scope in which the shadowing name is being declared 5501 /// \param R the lookup of the name 5502 /// 5503 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5504 // Return if warning is ignored. 5505 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5506 DiagnosticsEngine::Ignored) 5507 return; 5508 5509 // Don't diagnose declarations at file scope. 5510 if (D->hasGlobalStorage()) 5511 return; 5512 5513 DeclContext *NewDC = D->getDeclContext(); 5514 5515 // Only diagnose if we're shadowing an unambiguous field or variable. 5516 if (R.getResultKind() != LookupResult::Found) 5517 return; 5518 5519 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5520 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5521 return; 5522 5523 // Fields are not shadowed by variables in C++ static methods. 5524 if (isa<FieldDecl>(ShadowedDecl)) 5525 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5526 if (MD->isStatic()) 5527 return; 5528 5529 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5530 if (shadowedVar->isExternC()) { 5531 // For shadowing external vars, make sure that we point to the global 5532 // declaration, not a locally scoped extern declaration. 5533 for (auto I : shadowedVar->redecls()) 5534 if (I->isFileVarDecl()) { 5535 ShadowedDecl = I; 5536 break; 5537 } 5538 } 5539 5540 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5541 5542 // Only warn about certain kinds of shadowing for class members. 5543 if (NewDC && NewDC->isRecord()) { 5544 // In particular, don't warn about shadowing non-class members. 5545 if (!OldDC->isRecord()) 5546 return; 5547 5548 // TODO: should we warn about static data members shadowing 5549 // static data members from base classes? 5550 5551 // TODO: don't diagnose for inaccessible shadowed members. 5552 // This is hard to do perfectly because we might friend the 5553 // shadowing context, but that's just a false negative. 5554 } 5555 5556 // Determine what kind of declaration we're shadowing. 5557 unsigned Kind; 5558 if (isa<RecordDecl>(OldDC)) { 5559 if (isa<FieldDecl>(ShadowedDecl)) 5560 Kind = 3; // field 5561 else 5562 Kind = 2; // static data member 5563 } else if (OldDC->isFileContext()) 5564 Kind = 1; // global 5565 else 5566 Kind = 0; // local 5567 5568 DeclarationName Name = R.getLookupName(); 5569 5570 // Emit warning and note. 5571 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5572 return; 5573 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5574 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5575 } 5576 5577 /// \brief Check -Wshadow without the advantage of a previous lookup. 5578 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5579 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5580 DiagnosticsEngine::Ignored) 5581 return; 5582 5583 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5584 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5585 LookupName(R, S); 5586 CheckShadow(S, D, R); 5587 } 5588 5589 /// Check for conflict between this global or extern "C" declaration and 5590 /// previous global or extern "C" declarations. This is only used in C++. 5591 template<typename T> 5592 static bool checkGlobalOrExternCConflict( 5593 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5594 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5595 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5596 5597 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5598 // The common case: this global doesn't conflict with any extern "C" 5599 // declaration. 5600 return false; 5601 } 5602 5603 if (Prev) { 5604 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5605 // Both the old and new declarations have C language linkage. This is a 5606 // redeclaration. 5607 Previous.clear(); 5608 Previous.addDecl(Prev); 5609 return true; 5610 } 5611 5612 // This is a global, non-extern "C" declaration, and there is a previous 5613 // non-global extern "C" declaration. Diagnose if this is a variable 5614 // declaration. 5615 if (!isa<VarDecl>(ND)) 5616 return false; 5617 } else { 5618 // The declaration is extern "C". Check for any declaration in the 5619 // translation unit which might conflict. 5620 if (IsGlobal) { 5621 // We have already performed the lookup into the translation unit. 5622 IsGlobal = false; 5623 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5624 I != E; ++I) { 5625 if (isa<VarDecl>(*I)) { 5626 Prev = *I; 5627 break; 5628 } 5629 } 5630 } else { 5631 DeclContext::lookup_result R = 5632 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5633 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5634 I != E; ++I) { 5635 if (isa<VarDecl>(*I)) { 5636 Prev = *I; 5637 break; 5638 } 5639 // FIXME: If we have any other entity with this name in global scope, 5640 // the declaration is ill-formed, but that is a defect: it breaks the 5641 // 'stat' hack, for instance. Only variables can have mangled name 5642 // clashes with extern "C" declarations, so only they deserve a 5643 // diagnostic. 5644 } 5645 } 5646 5647 if (!Prev) 5648 return false; 5649 } 5650 5651 // Use the first declaration's location to ensure we point at something which 5652 // is lexically inside an extern "C" linkage-spec. 5653 assert(Prev && "should have found a previous declaration to diagnose"); 5654 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5655 Prev = FD->getFirstDecl(); 5656 else 5657 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5658 5659 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5660 << IsGlobal << ND; 5661 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5662 << IsGlobal; 5663 return false; 5664 } 5665 5666 /// Apply special rules for handling extern "C" declarations. Returns \c true 5667 /// if we have found that this is a redeclaration of some prior entity. 5668 /// 5669 /// Per C++ [dcl.link]p6: 5670 /// Two declarations [for a function or variable] with C language linkage 5671 /// with the same name that appear in different scopes refer to the same 5672 /// [entity]. An entity with C language linkage shall not be declared with 5673 /// the same name as an entity in global scope. 5674 template<typename T> 5675 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5676 LookupResult &Previous) { 5677 if (!S.getLangOpts().CPlusPlus) { 5678 // In C, when declaring a global variable, look for a corresponding 'extern' 5679 // variable declared in function scope. We don't need this in C++, because 5680 // we find local extern decls in the surrounding file-scope DeclContext. 5681 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5682 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5683 Previous.clear(); 5684 Previous.addDecl(Prev); 5685 return true; 5686 } 5687 } 5688 return false; 5689 } 5690 5691 // A declaration in the translation unit can conflict with an extern "C" 5692 // declaration. 5693 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5694 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5695 5696 // An extern "C" declaration can conflict with a declaration in the 5697 // translation unit or can be a redeclaration of an extern "C" declaration 5698 // in another scope. 5699 if (isIncompleteDeclExternC(S,ND)) 5700 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5701 5702 // Neither global nor extern "C": nothing to do. 5703 return false; 5704 } 5705 5706 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5707 // If the decl is already known invalid, don't check it. 5708 if (NewVD->isInvalidDecl()) 5709 return; 5710 5711 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5712 QualType T = TInfo->getType(); 5713 5714 // Defer checking an 'auto' type until its initializer is attached. 5715 if (T->isUndeducedType()) 5716 return; 5717 5718 if (T->isObjCObjectType()) { 5719 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5720 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5721 T = Context.getObjCObjectPointerType(T); 5722 NewVD->setType(T); 5723 } 5724 5725 // Emit an error if an address space was applied to decl with local storage. 5726 // This includes arrays of objects with address space qualifiers, but not 5727 // automatic variables that point to other address spaces. 5728 // ISO/IEC TR 18037 S5.1.2 5729 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5730 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5731 NewVD->setInvalidDecl(); 5732 return; 5733 } 5734 5735 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5736 // __constant address space. 5737 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5738 && T.getAddressSpace() != LangAS::opencl_constant 5739 && !T->isSamplerT()){ 5740 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5741 NewVD->setInvalidDecl(); 5742 return; 5743 } 5744 5745 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5746 // scope. 5747 if ((getLangOpts().OpenCLVersion >= 120) 5748 && NewVD->isStaticLocal()) { 5749 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5750 NewVD->setInvalidDecl(); 5751 return; 5752 } 5753 5754 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5755 && !NewVD->hasAttr<BlocksAttr>()) { 5756 if (getLangOpts().getGC() != LangOptions::NonGC) 5757 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5758 else { 5759 assert(!getLangOpts().ObjCAutoRefCount); 5760 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5761 } 5762 } 5763 5764 bool isVM = T->isVariablyModifiedType(); 5765 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5766 NewVD->hasAttr<BlocksAttr>()) 5767 getCurFunction()->setHasBranchProtectedScope(); 5768 5769 if ((isVM && NewVD->hasLinkage()) || 5770 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5771 bool SizeIsNegative; 5772 llvm::APSInt Oversized; 5773 TypeSourceInfo *FixedTInfo = 5774 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5775 SizeIsNegative, Oversized); 5776 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5777 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5778 // FIXME: This won't give the correct result for 5779 // int a[10][n]; 5780 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5781 5782 if (NewVD->isFileVarDecl()) 5783 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5784 << SizeRange; 5785 else if (NewVD->isStaticLocal()) 5786 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5787 << SizeRange; 5788 else 5789 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5790 << SizeRange; 5791 NewVD->setInvalidDecl(); 5792 return; 5793 } 5794 5795 if (FixedTInfo == 0) { 5796 if (NewVD->isFileVarDecl()) 5797 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5798 else 5799 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5800 NewVD->setInvalidDecl(); 5801 return; 5802 } 5803 5804 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5805 NewVD->setType(FixedTInfo->getType()); 5806 NewVD->setTypeSourceInfo(FixedTInfo); 5807 } 5808 5809 if (T->isVoidType()) { 5810 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5811 // of objects and functions. 5812 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5813 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5814 << T; 5815 NewVD->setInvalidDecl(); 5816 return; 5817 } 5818 } 5819 5820 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5821 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5822 NewVD->setInvalidDecl(); 5823 return; 5824 } 5825 5826 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5827 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5828 NewVD->setInvalidDecl(); 5829 return; 5830 } 5831 5832 if (NewVD->isConstexpr() && !T->isDependentType() && 5833 RequireLiteralType(NewVD->getLocation(), T, 5834 diag::err_constexpr_var_non_literal)) { 5835 // Can't perform this check until the type is deduced. 5836 NewVD->setInvalidDecl(); 5837 return; 5838 } 5839 } 5840 5841 /// \brief Perform semantic checking on a newly-created variable 5842 /// declaration. 5843 /// 5844 /// This routine performs all of the type-checking required for a 5845 /// variable declaration once it has been built. It is used both to 5846 /// check variables after they have been parsed and their declarators 5847 /// have been translated into a declaration, and to check variables 5848 /// that have been instantiated from a template. 5849 /// 5850 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5851 /// 5852 /// Returns true if the variable declaration is a redeclaration. 5853 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5854 CheckVariableDeclarationType(NewVD); 5855 5856 // If the decl is already known invalid, don't check it. 5857 if (NewVD->isInvalidDecl()) 5858 return false; 5859 5860 // If we did not find anything by this name, look for a non-visible 5861 // extern "C" declaration with the same name. 5862 if (Previous.empty() && 5863 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5864 Previous.setShadowed(); 5865 5866 // Filter out any non-conflicting previous declarations. 5867 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5868 5869 if (!Previous.empty()) { 5870 MergeVarDecl(NewVD, Previous); 5871 return true; 5872 } 5873 return false; 5874 } 5875 5876 /// \brief Data used with FindOverriddenMethod 5877 struct FindOverriddenMethodData { 5878 Sema *S; 5879 CXXMethodDecl *Method; 5880 }; 5881 5882 /// \brief Member lookup function that determines whether a given C++ 5883 /// method overrides a method in a base class, to be used with 5884 /// CXXRecordDecl::lookupInBases(). 5885 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5886 CXXBasePath &Path, 5887 void *UserData) { 5888 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5889 5890 FindOverriddenMethodData *Data 5891 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5892 5893 DeclarationName Name = Data->Method->getDeclName(); 5894 5895 // FIXME: Do we care about other names here too? 5896 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5897 // We really want to find the base class destructor here. 5898 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5899 CanQualType CT = Data->S->Context.getCanonicalType(T); 5900 5901 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5902 } 5903 5904 for (Path.Decls = BaseRecord->lookup(Name); 5905 !Path.Decls.empty(); 5906 Path.Decls = Path.Decls.slice(1)) { 5907 NamedDecl *D = Path.Decls.front(); 5908 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5909 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5910 return true; 5911 } 5912 } 5913 5914 return false; 5915 } 5916 5917 namespace { 5918 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5919 } 5920 /// \brief Report an error regarding overriding, along with any relevant 5921 /// overriden methods. 5922 /// 5923 /// \param DiagID the primary error to report. 5924 /// \param MD the overriding method. 5925 /// \param OEK which overrides to include as notes. 5926 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5927 OverrideErrorKind OEK = OEK_All) { 5928 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5929 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5930 E = MD->end_overridden_methods(); 5931 I != E; ++I) { 5932 // This check (& the OEK parameter) could be replaced by a predicate, but 5933 // without lambdas that would be overkill. This is still nicer than writing 5934 // out the diag loop 3 times. 5935 if ((OEK == OEK_All) || 5936 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5937 (OEK == OEK_Deleted && (*I)->isDeleted())) 5938 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5939 } 5940 } 5941 5942 /// AddOverriddenMethods - See if a method overrides any in the base classes, 5943 /// and if so, check that it's a valid override and remember it. 5944 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5945 // Look for virtual methods in base classes that this method might override. 5946 CXXBasePaths Paths; 5947 FindOverriddenMethodData Data; 5948 Data.Method = MD; 5949 Data.S = this; 5950 bool hasDeletedOverridenMethods = false; 5951 bool hasNonDeletedOverridenMethods = false; 5952 bool AddedAny = false; 5953 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5954 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5955 E = Paths.found_decls_end(); I != E; ++I) { 5956 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5957 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5958 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5959 !CheckOverridingFunctionAttributes(MD, OldMD) && 5960 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5961 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5962 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5963 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5964 AddedAny = true; 5965 } 5966 } 5967 } 5968 } 5969 5970 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5971 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5972 } 5973 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5974 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5975 } 5976 5977 return AddedAny; 5978 } 5979 5980 namespace { 5981 // Struct for holding all of the extra arguments needed by 5982 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5983 struct ActOnFDArgs { 5984 Scope *S; 5985 Declarator &D; 5986 MultiTemplateParamsArg TemplateParamLists; 5987 bool AddToScope; 5988 }; 5989 } 5990 5991 namespace { 5992 5993 // Callback to only accept typo corrections that have a non-zero edit distance. 5994 // Also only accept corrections that have the same parent decl. 5995 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5996 public: 5997 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5998 CXXRecordDecl *Parent) 5999 : Context(Context), OriginalFD(TypoFD), 6000 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 6001 6002 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6003 if (candidate.getEditDistance() == 0) 6004 return false; 6005 6006 SmallVector<unsigned, 1> MismatchedParams; 6007 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6008 CDeclEnd = candidate.end(); 6009 CDecl != CDeclEnd; ++CDecl) { 6010 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6011 6012 if (FD && !FD->hasBody() && 6013 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6015 CXXRecordDecl *Parent = MD->getParent(); 6016 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6017 return true; 6018 } else if (!ExpectedParent) { 6019 return true; 6020 } 6021 } 6022 } 6023 6024 return false; 6025 } 6026 6027 private: 6028 ASTContext &Context; 6029 FunctionDecl *OriginalFD; 6030 CXXRecordDecl *ExpectedParent; 6031 }; 6032 6033 } 6034 6035 /// \brief Generate diagnostics for an invalid function redeclaration. 6036 /// 6037 /// This routine handles generating the diagnostic messages for an invalid 6038 /// function redeclaration, including finding possible similar declarations 6039 /// or performing typo correction if there are no previous declarations with 6040 /// the same name. 6041 /// 6042 /// Returns a NamedDecl iff typo correction was performed and substituting in 6043 /// the new declaration name does not cause new errors. 6044 static NamedDecl *DiagnoseInvalidRedeclaration( 6045 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6046 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6047 DeclarationName Name = NewFD->getDeclName(); 6048 DeclContext *NewDC = NewFD->getDeclContext(); 6049 SmallVector<unsigned, 1> MismatchedParams; 6050 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6051 TypoCorrection Correction; 6052 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6053 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6054 : diag::err_member_decl_does_not_match; 6055 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6056 IsLocalFriend ? Sema::LookupLocalFriendName 6057 : Sema::LookupOrdinaryName, 6058 Sema::ForRedeclaration); 6059 6060 NewFD->setInvalidDecl(); 6061 if (IsLocalFriend) 6062 SemaRef.LookupName(Prev, S); 6063 else 6064 SemaRef.LookupQualifiedName(Prev, NewDC); 6065 assert(!Prev.isAmbiguous() && 6066 "Cannot have an ambiguity in previous-declaration lookup"); 6067 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6068 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6069 MD ? MD->getParent() : 0); 6070 if (!Prev.empty()) { 6071 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6072 Func != FuncEnd; ++Func) { 6073 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6074 if (FD && 6075 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6076 // Add 1 to the index so that 0 can mean the mismatch didn't 6077 // involve a parameter 6078 unsigned ParamNum = 6079 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6080 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6081 } 6082 } 6083 // If the qualified name lookup yielded nothing, try typo correction 6084 } else if ((Correction = SemaRef.CorrectTypo( 6085 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6086 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6087 IsLocalFriend ? 0 : NewDC))) { 6088 // Set up everything for the call to ActOnFunctionDeclarator 6089 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6090 ExtraArgs.D.getIdentifierLoc()); 6091 Previous.clear(); 6092 Previous.setLookupName(Correction.getCorrection()); 6093 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6094 CDeclEnd = Correction.end(); 6095 CDecl != CDeclEnd; ++CDecl) { 6096 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6097 if (FD && !FD->hasBody() && 6098 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6099 Previous.addDecl(FD); 6100 } 6101 } 6102 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6103 6104 NamedDecl *Result; 6105 // Retry building the function declaration with the new previous 6106 // declarations, and with errors suppressed. 6107 { 6108 // Trap errors. 6109 Sema::SFINAETrap Trap(SemaRef); 6110 6111 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6112 // pieces need to verify the typo-corrected C++ declaration and hopefully 6113 // eliminate the need for the parameter pack ExtraArgs. 6114 Result = SemaRef.ActOnFunctionDeclarator( 6115 ExtraArgs.S, ExtraArgs.D, 6116 Correction.getCorrectionDecl()->getDeclContext(), 6117 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6118 ExtraArgs.AddToScope); 6119 6120 if (Trap.hasErrorOccurred()) 6121 Result = 0; 6122 } 6123 6124 if (Result) { 6125 // Determine which correction we picked. 6126 Decl *Canonical = Result->getCanonicalDecl(); 6127 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6128 I != E; ++I) 6129 if ((*I)->getCanonicalDecl() == Canonical) 6130 Correction.setCorrectionDecl(*I); 6131 6132 SemaRef.diagnoseTypo( 6133 Correction, 6134 SemaRef.PDiag(IsLocalFriend 6135 ? diag::err_no_matching_local_friend_suggest 6136 : diag::err_member_decl_does_not_match_suggest) 6137 << Name << NewDC << IsDefinition); 6138 return Result; 6139 } 6140 6141 // Pretend the typo correction never occurred 6142 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6143 ExtraArgs.D.getIdentifierLoc()); 6144 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6145 Previous.clear(); 6146 Previous.setLookupName(Name); 6147 } 6148 6149 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6150 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6151 6152 bool NewFDisConst = false; 6153 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6154 NewFDisConst = NewMD->isConst(); 6155 6156 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6157 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6158 NearMatch != NearMatchEnd; ++NearMatch) { 6159 FunctionDecl *FD = NearMatch->first; 6160 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6161 bool FDisConst = MD && MD->isConst(); 6162 bool IsMember = MD || !IsLocalFriend; 6163 6164 // FIXME: These notes are poorly worded for the local friend case. 6165 if (unsigned Idx = NearMatch->second) { 6166 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6167 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6168 if (Loc.isInvalid()) Loc = FD->getLocation(); 6169 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6170 : diag::note_local_decl_close_param_match) 6171 << Idx << FDParam->getType() 6172 << NewFD->getParamDecl(Idx - 1)->getType(); 6173 } else if (FDisConst != NewFDisConst) { 6174 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6175 << NewFDisConst << FD->getSourceRange().getEnd(); 6176 } else 6177 SemaRef.Diag(FD->getLocation(), 6178 IsMember ? diag::note_member_def_close_match 6179 : diag::note_local_decl_close_match); 6180 } 6181 return 0; 6182 } 6183 6184 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6185 Declarator &D) { 6186 switch (D.getDeclSpec().getStorageClassSpec()) { 6187 default: llvm_unreachable("Unknown storage class!"); 6188 case DeclSpec::SCS_auto: 6189 case DeclSpec::SCS_register: 6190 case DeclSpec::SCS_mutable: 6191 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6192 diag::err_typecheck_sclass_func); 6193 D.setInvalidType(); 6194 break; 6195 case DeclSpec::SCS_unspecified: break; 6196 case DeclSpec::SCS_extern: 6197 if (D.getDeclSpec().isExternInLinkageSpec()) 6198 return SC_None; 6199 return SC_Extern; 6200 case DeclSpec::SCS_static: { 6201 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6202 // C99 6.7.1p5: 6203 // The declaration of an identifier for a function that has 6204 // block scope shall have no explicit storage-class specifier 6205 // other than extern 6206 // See also (C++ [dcl.stc]p4). 6207 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6208 diag::err_static_block_func); 6209 break; 6210 } else 6211 return SC_Static; 6212 } 6213 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6214 } 6215 6216 // No explicit storage class has already been returned 6217 return SC_None; 6218 } 6219 6220 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6221 DeclContext *DC, QualType &R, 6222 TypeSourceInfo *TInfo, 6223 FunctionDecl::StorageClass SC, 6224 bool &IsVirtualOkay) { 6225 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6226 DeclarationName Name = NameInfo.getName(); 6227 6228 FunctionDecl *NewFD = 0; 6229 bool isInline = D.getDeclSpec().isInlineSpecified(); 6230 6231 if (!SemaRef.getLangOpts().CPlusPlus) { 6232 // Determine whether the function was written with a 6233 // prototype. This true when: 6234 // - there is a prototype in the declarator, or 6235 // - the type R of the function is some kind of typedef or other reference 6236 // to a type name (which eventually refers to a function type). 6237 bool HasPrototype = 6238 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6239 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6240 6241 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6242 D.getLocStart(), NameInfo, R, 6243 TInfo, SC, isInline, 6244 HasPrototype, false); 6245 if (D.isInvalidType()) 6246 NewFD->setInvalidDecl(); 6247 6248 // Set the lexical context. 6249 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6250 6251 return NewFD; 6252 } 6253 6254 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6255 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6256 6257 // Check that the return type is not an abstract class type. 6258 // For record types, this is done by the AbstractClassUsageDiagnoser once 6259 // the class has been completely parsed. 6260 if (!DC->isRecord() && 6261 SemaRef.RequireNonAbstractType( 6262 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6263 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6264 D.setInvalidType(); 6265 6266 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6267 // This is a C++ constructor declaration. 6268 assert(DC->isRecord() && 6269 "Constructors can only be declared in a member context"); 6270 6271 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6272 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6273 D.getLocStart(), NameInfo, 6274 R, TInfo, isExplicit, isInline, 6275 /*isImplicitlyDeclared=*/false, 6276 isConstexpr); 6277 6278 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6279 // This is a C++ destructor declaration. 6280 if (DC->isRecord()) { 6281 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6282 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6283 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6284 SemaRef.Context, Record, 6285 D.getLocStart(), 6286 NameInfo, R, TInfo, isInline, 6287 /*isImplicitlyDeclared=*/false); 6288 6289 // If the class is complete, then we now create the implicit exception 6290 // specification. If the class is incomplete or dependent, we can't do 6291 // it yet. 6292 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6293 Record->getDefinition() && !Record->isBeingDefined() && 6294 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6295 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6296 } 6297 6298 IsVirtualOkay = true; 6299 return NewDD; 6300 6301 } else { 6302 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6303 D.setInvalidType(); 6304 6305 // Create a FunctionDecl to satisfy the function definition parsing 6306 // code path. 6307 return FunctionDecl::Create(SemaRef.Context, DC, 6308 D.getLocStart(), 6309 D.getIdentifierLoc(), Name, R, TInfo, 6310 SC, isInline, 6311 /*hasPrototype=*/true, isConstexpr); 6312 } 6313 6314 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6315 if (!DC->isRecord()) { 6316 SemaRef.Diag(D.getIdentifierLoc(), 6317 diag::err_conv_function_not_member); 6318 return 0; 6319 } 6320 6321 SemaRef.CheckConversionDeclarator(D, R, SC); 6322 IsVirtualOkay = true; 6323 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6324 D.getLocStart(), NameInfo, 6325 R, TInfo, isInline, isExplicit, 6326 isConstexpr, SourceLocation()); 6327 6328 } else if (DC->isRecord()) { 6329 // If the name of the function is the same as the name of the record, 6330 // then this must be an invalid constructor that has a return type. 6331 // (The parser checks for a return type and makes the declarator a 6332 // constructor if it has no return type). 6333 if (Name.getAsIdentifierInfo() && 6334 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6335 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6336 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6337 << SourceRange(D.getIdentifierLoc()); 6338 return 0; 6339 } 6340 6341 // This is a C++ method declaration. 6342 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6343 cast<CXXRecordDecl>(DC), 6344 D.getLocStart(), NameInfo, R, 6345 TInfo, SC, isInline, 6346 isConstexpr, SourceLocation()); 6347 IsVirtualOkay = !Ret->isStatic(); 6348 return Ret; 6349 } else { 6350 // Determine whether the function was written with a 6351 // prototype. This true when: 6352 // - we're in C++ (where every function has a prototype), 6353 return FunctionDecl::Create(SemaRef.Context, DC, 6354 D.getLocStart(), 6355 NameInfo, R, TInfo, SC, isInline, 6356 true/*HasPrototype*/, isConstexpr); 6357 } 6358 } 6359 6360 enum OpenCLParamType { 6361 ValidKernelParam, 6362 PtrPtrKernelParam, 6363 PtrKernelParam, 6364 InvalidKernelParam, 6365 RecordKernelParam 6366 }; 6367 6368 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6369 if (PT->isPointerType()) { 6370 QualType PointeeType = PT->getPointeeType(); 6371 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam; 6372 } 6373 6374 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6375 // be used as builtin types. 6376 6377 if (PT->isImageType()) 6378 return PtrKernelParam; 6379 6380 if (PT->isBooleanType()) 6381 return InvalidKernelParam; 6382 6383 if (PT->isEventT()) 6384 return InvalidKernelParam; 6385 6386 if (PT->isHalfType()) 6387 return InvalidKernelParam; 6388 6389 if (PT->isRecordType()) 6390 return RecordKernelParam; 6391 6392 return ValidKernelParam; 6393 } 6394 6395 static void checkIsValidOpenCLKernelParameter( 6396 Sema &S, 6397 Declarator &D, 6398 ParmVarDecl *Param, 6399 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6400 QualType PT = Param->getType(); 6401 6402 // Cache the valid types we encounter to avoid rechecking structs that are 6403 // used again 6404 if (ValidTypes.count(PT.getTypePtr())) 6405 return; 6406 6407 switch (getOpenCLKernelParameterType(PT)) { 6408 case PtrPtrKernelParam: 6409 // OpenCL v1.2 s6.9.a: 6410 // A kernel function argument cannot be declared as a 6411 // pointer to a pointer type. 6412 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6413 D.setInvalidType(); 6414 return; 6415 6416 // OpenCL v1.2 s6.9.k: 6417 // Arguments to kernel functions in a program cannot be declared with the 6418 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6419 // uintptr_t or a struct and/or union that contain fields declared to be 6420 // one of these built-in scalar types. 6421 6422 case InvalidKernelParam: 6423 // OpenCL v1.2 s6.8 n: 6424 // A kernel function argument cannot be declared 6425 // of event_t type. 6426 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6427 D.setInvalidType(); 6428 return; 6429 6430 case PtrKernelParam: 6431 case ValidKernelParam: 6432 ValidTypes.insert(PT.getTypePtr()); 6433 return; 6434 6435 case RecordKernelParam: 6436 break; 6437 } 6438 6439 // Track nested structs we will inspect 6440 SmallVector<const Decl *, 4> VisitStack; 6441 6442 // Track where we are in the nested structs. Items will migrate from 6443 // VisitStack to HistoryStack as we do the DFS for bad field. 6444 SmallVector<const FieldDecl *, 4> HistoryStack; 6445 HistoryStack.push_back((const FieldDecl *) 0); 6446 6447 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6448 VisitStack.push_back(PD); 6449 6450 assert(VisitStack.back() && "First decl null?"); 6451 6452 do { 6453 const Decl *Next = VisitStack.pop_back_val(); 6454 if (!Next) { 6455 assert(!HistoryStack.empty()); 6456 // Found a marker, we have gone up a level 6457 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6458 ValidTypes.insert(Hist->getType().getTypePtr()); 6459 6460 continue; 6461 } 6462 6463 // Adds everything except the original parameter declaration (which is not a 6464 // field itself) to the history stack. 6465 const RecordDecl *RD; 6466 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6467 HistoryStack.push_back(Field); 6468 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6469 } else { 6470 RD = cast<RecordDecl>(Next); 6471 } 6472 6473 // Add a null marker so we know when we've gone back up a level 6474 VisitStack.push_back((const Decl *) 0); 6475 6476 for (const auto *FD : RD->fields()) { 6477 QualType QT = FD->getType(); 6478 6479 if (ValidTypes.count(QT.getTypePtr())) 6480 continue; 6481 6482 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6483 if (ParamType == ValidKernelParam) 6484 continue; 6485 6486 if (ParamType == RecordKernelParam) { 6487 VisitStack.push_back(FD); 6488 continue; 6489 } 6490 6491 // OpenCL v1.2 s6.9.p: 6492 // Arguments to kernel functions that are declared to be a struct or union 6493 // do not allow OpenCL objects to be passed as elements of the struct or 6494 // union. 6495 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) { 6496 S.Diag(Param->getLocation(), 6497 diag::err_record_with_pointers_kernel_param) 6498 << PT->isUnionType() 6499 << PT; 6500 } else { 6501 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6502 } 6503 6504 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6505 << PD->getDeclName(); 6506 6507 // We have an error, now let's go back up through history and show where 6508 // the offending field came from 6509 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6510 E = HistoryStack.end(); I != E; ++I) { 6511 const FieldDecl *OuterField = *I; 6512 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6513 << OuterField->getType(); 6514 } 6515 6516 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6517 << QT->isPointerType() 6518 << QT; 6519 D.setInvalidType(); 6520 return; 6521 } 6522 } while (!VisitStack.empty()); 6523 } 6524 6525 NamedDecl* 6526 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6527 TypeSourceInfo *TInfo, LookupResult &Previous, 6528 MultiTemplateParamsArg TemplateParamLists, 6529 bool &AddToScope) { 6530 QualType R = TInfo->getType(); 6531 6532 assert(R.getTypePtr()->isFunctionType()); 6533 6534 // TODO: consider using NameInfo for diagnostic. 6535 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6536 DeclarationName Name = NameInfo.getName(); 6537 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6538 6539 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6540 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6541 diag::err_invalid_thread) 6542 << DeclSpec::getSpecifierName(TSCS); 6543 6544 if (D.isFirstDeclarationOfMember()) 6545 adjustMemberFunctionCC(R, D.isStaticMember()); 6546 6547 bool isFriend = false; 6548 FunctionTemplateDecl *FunctionTemplate = 0; 6549 bool isExplicitSpecialization = false; 6550 bool isFunctionTemplateSpecialization = false; 6551 6552 bool isDependentClassScopeExplicitSpecialization = false; 6553 bool HasExplicitTemplateArgs = false; 6554 TemplateArgumentListInfo TemplateArgs; 6555 6556 bool isVirtualOkay = false; 6557 6558 DeclContext *OriginalDC = DC; 6559 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6560 6561 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6562 isVirtualOkay); 6563 if (!NewFD) return 0; 6564 6565 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6566 NewFD->setTopLevelDeclInObjCContainer(); 6567 6568 // Set the lexical context. If this is a function-scope declaration, or has a 6569 // C++ scope specifier, or is the object of a friend declaration, the lexical 6570 // context will be different from the semantic context. 6571 NewFD->setLexicalDeclContext(CurContext); 6572 6573 if (IsLocalExternDecl) 6574 NewFD->setLocalExternDecl(); 6575 6576 if (getLangOpts().CPlusPlus) { 6577 bool isInline = D.getDeclSpec().isInlineSpecified(); 6578 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6579 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6580 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6581 isFriend = D.getDeclSpec().isFriendSpecified(); 6582 if (isFriend && !isInline && D.isFunctionDefinition()) { 6583 // C++ [class.friend]p5 6584 // A function can be defined in a friend declaration of a 6585 // class . . . . Such a function is implicitly inline. 6586 NewFD->setImplicitlyInline(); 6587 } 6588 6589 // If this is a method defined in an __interface, and is not a constructor 6590 // or an overloaded operator, then set the pure flag (isVirtual will already 6591 // return true). 6592 if (const CXXRecordDecl *Parent = 6593 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6594 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6595 NewFD->setPure(true); 6596 } 6597 6598 SetNestedNameSpecifier(NewFD, D); 6599 isExplicitSpecialization = false; 6600 isFunctionTemplateSpecialization = false; 6601 if (D.isInvalidType()) 6602 NewFD->setInvalidDecl(); 6603 6604 // Match up the template parameter lists with the scope specifier, then 6605 // determine whether we have a template or a template specialization. 6606 bool Invalid = false; 6607 if (TemplateParameterList *TemplateParams = 6608 MatchTemplateParametersToScopeSpecifier( 6609 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6610 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6611 isExplicitSpecialization, Invalid)) { 6612 if (TemplateParams->size() > 0) { 6613 // This is a function template 6614 6615 // Check that we can declare a template here. 6616 if (CheckTemplateDeclScope(S, TemplateParams)) 6617 return 0; 6618 6619 // A destructor cannot be a template. 6620 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6621 Diag(NewFD->getLocation(), diag::err_destructor_template); 6622 return 0; 6623 } 6624 6625 // If we're adding a template to a dependent context, we may need to 6626 // rebuilding some of the types used within the template parameter list, 6627 // now that we know what the current instantiation is. 6628 if (DC->isDependentContext()) { 6629 ContextRAII SavedContext(*this, DC); 6630 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6631 Invalid = true; 6632 } 6633 6634 6635 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6636 NewFD->getLocation(), 6637 Name, TemplateParams, 6638 NewFD); 6639 FunctionTemplate->setLexicalDeclContext(CurContext); 6640 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6641 6642 // For source fidelity, store the other template param lists. 6643 if (TemplateParamLists.size() > 1) { 6644 NewFD->setTemplateParameterListsInfo(Context, 6645 TemplateParamLists.size() - 1, 6646 TemplateParamLists.data()); 6647 } 6648 } else { 6649 // This is a function template specialization. 6650 isFunctionTemplateSpecialization = true; 6651 // For source fidelity, store all the template param lists. 6652 NewFD->setTemplateParameterListsInfo(Context, 6653 TemplateParamLists.size(), 6654 TemplateParamLists.data()); 6655 6656 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6657 if (isFriend) { 6658 // We want to remove the "template<>", found here. 6659 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6660 6661 // If we remove the template<> and the name is not a 6662 // template-id, we're actually silently creating a problem: 6663 // the friend declaration will refer to an untemplated decl, 6664 // and clearly the user wants a template specialization. So 6665 // we need to insert '<>' after the name. 6666 SourceLocation InsertLoc; 6667 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6668 InsertLoc = D.getName().getSourceRange().getEnd(); 6669 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6670 } 6671 6672 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6673 << Name << RemoveRange 6674 << FixItHint::CreateRemoval(RemoveRange) 6675 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6676 } 6677 } 6678 } 6679 else { 6680 // All template param lists were matched against the scope specifier: 6681 // this is NOT (an explicit specialization of) a template. 6682 if (TemplateParamLists.size() > 0) 6683 // For source fidelity, store all the template param lists. 6684 NewFD->setTemplateParameterListsInfo(Context, 6685 TemplateParamLists.size(), 6686 TemplateParamLists.data()); 6687 } 6688 6689 if (Invalid) { 6690 NewFD->setInvalidDecl(); 6691 if (FunctionTemplate) 6692 FunctionTemplate->setInvalidDecl(); 6693 } 6694 6695 // C++ [dcl.fct.spec]p5: 6696 // The virtual specifier shall only be used in declarations of 6697 // nonstatic class member functions that appear within a 6698 // member-specification of a class declaration; see 10.3. 6699 // 6700 if (isVirtual && !NewFD->isInvalidDecl()) { 6701 if (!isVirtualOkay) { 6702 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6703 diag::err_virtual_non_function); 6704 } else if (!CurContext->isRecord()) { 6705 // 'virtual' was specified outside of the class. 6706 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6707 diag::err_virtual_out_of_class) 6708 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6709 } else if (NewFD->getDescribedFunctionTemplate()) { 6710 // C++ [temp.mem]p3: 6711 // A member function template shall not be virtual. 6712 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6713 diag::err_virtual_member_function_template) 6714 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6715 } else { 6716 // Okay: Add virtual to the method. 6717 NewFD->setVirtualAsWritten(true); 6718 } 6719 6720 if (getLangOpts().CPlusPlus1y && 6721 NewFD->getReturnType()->isUndeducedType()) 6722 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6723 } 6724 6725 if (getLangOpts().CPlusPlus1y && 6726 (NewFD->isDependentContext() || 6727 (isFriend && CurContext->isDependentContext())) && 6728 NewFD->getReturnType()->isUndeducedType()) { 6729 // If the function template is referenced directly (for instance, as a 6730 // member of the current instantiation), pretend it has a dependent type. 6731 // This is not really justified by the standard, but is the only sane 6732 // thing to do. 6733 // FIXME: For a friend function, we have not marked the function as being 6734 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6735 const FunctionProtoType *FPT = 6736 NewFD->getType()->castAs<FunctionProtoType>(); 6737 QualType Result = 6738 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6739 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6740 FPT->getExtProtoInfo())); 6741 } 6742 6743 // C++ [dcl.fct.spec]p3: 6744 // The inline specifier shall not appear on a block scope function 6745 // declaration. 6746 if (isInline && !NewFD->isInvalidDecl()) { 6747 if (CurContext->isFunctionOrMethod()) { 6748 // 'inline' is not allowed on block scope function declaration. 6749 Diag(D.getDeclSpec().getInlineSpecLoc(), 6750 diag::err_inline_declaration_block_scope) << Name 6751 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6752 } 6753 } 6754 6755 // C++ [dcl.fct.spec]p6: 6756 // The explicit specifier shall be used only in the declaration of a 6757 // constructor or conversion function within its class definition; 6758 // see 12.3.1 and 12.3.2. 6759 if (isExplicit && !NewFD->isInvalidDecl()) { 6760 if (!CurContext->isRecord()) { 6761 // 'explicit' was specified outside of the class. 6762 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6763 diag::err_explicit_out_of_class) 6764 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6765 } else if (!isa<CXXConstructorDecl>(NewFD) && 6766 !isa<CXXConversionDecl>(NewFD)) { 6767 // 'explicit' was specified on a function that wasn't a constructor 6768 // or conversion function. 6769 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6770 diag::err_explicit_non_ctor_or_conv_function) 6771 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6772 } 6773 } 6774 6775 if (isConstexpr) { 6776 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6777 // are implicitly inline. 6778 NewFD->setImplicitlyInline(); 6779 6780 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6781 // be either constructors or to return a literal type. Therefore, 6782 // destructors cannot be declared constexpr. 6783 if (isa<CXXDestructorDecl>(NewFD)) 6784 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6785 } 6786 6787 // If __module_private__ was specified, mark the function accordingly. 6788 if (D.getDeclSpec().isModulePrivateSpecified()) { 6789 if (isFunctionTemplateSpecialization) { 6790 SourceLocation ModulePrivateLoc 6791 = D.getDeclSpec().getModulePrivateSpecLoc(); 6792 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6793 << 0 6794 << FixItHint::CreateRemoval(ModulePrivateLoc); 6795 } else { 6796 NewFD->setModulePrivate(); 6797 if (FunctionTemplate) 6798 FunctionTemplate->setModulePrivate(); 6799 } 6800 } 6801 6802 if (isFriend) { 6803 if (FunctionTemplate) { 6804 FunctionTemplate->setObjectOfFriendDecl(); 6805 FunctionTemplate->setAccess(AS_public); 6806 } 6807 NewFD->setObjectOfFriendDecl(); 6808 NewFD->setAccess(AS_public); 6809 } 6810 6811 // If a function is defined as defaulted or deleted, mark it as such now. 6812 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6813 // definition kind to FDK_Definition. 6814 switch (D.getFunctionDefinitionKind()) { 6815 case FDK_Declaration: 6816 case FDK_Definition: 6817 break; 6818 6819 case FDK_Defaulted: 6820 NewFD->setDefaulted(); 6821 break; 6822 6823 case FDK_Deleted: 6824 NewFD->setDeletedAsWritten(); 6825 break; 6826 } 6827 6828 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6829 D.isFunctionDefinition()) { 6830 // C++ [class.mfct]p2: 6831 // A member function may be defined (8.4) in its class definition, in 6832 // which case it is an inline member function (7.1.2) 6833 NewFD->setImplicitlyInline(); 6834 } 6835 6836 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6837 !CurContext->isRecord()) { 6838 // C++ [class.static]p1: 6839 // A data or function member of a class may be declared static 6840 // in a class definition, in which case it is a static member of 6841 // the class. 6842 6843 // Complain about the 'static' specifier if it's on an out-of-line 6844 // member function definition. 6845 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6846 diag::err_static_out_of_line) 6847 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6848 } 6849 6850 // C++11 [except.spec]p15: 6851 // A deallocation function with no exception-specification is treated 6852 // as if it were specified with noexcept(true). 6853 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6854 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6855 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6856 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6857 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6858 EPI.ExceptionSpecType = EST_BasicNoexcept; 6859 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 6860 FPT->getParamTypes(), EPI)); 6861 } 6862 } 6863 6864 // Filter out previous declarations that don't match the scope. 6865 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6866 D.getCXXScopeSpec().isNotEmpty() || 6867 isExplicitSpecialization || 6868 isFunctionTemplateSpecialization); 6869 6870 // Handle GNU asm-label extension (encoded as an attribute). 6871 if (Expr *E = (Expr*) D.getAsmLabel()) { 6872 // The parser guarantees this is a string. 6873 StringLiteral *SE = cast<StringLiteral>(E); 6874 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6875 SE->getString(), 0)); 6876 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6877 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6878 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6879 if (I != ExtnameUndeclaredIdentifiers.end()) { 6880 NewFD->addAttr(I->second); 6881 ExtnameUndeclaredIdentifiers.erase(I); 6882 } 6883 } 6884 6885 // Copy the parameter declarations from the declarator D to the function 6886 // declaration NewFD, if they are available. First scavenge them into Params. 6887 SmallVector<ParmVarDecl*, 16> Params; 6888 if (D.isFunctionDeclarator()) { 6889 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6890 6891 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6892 // function that takes no arguments, not a function that takes a 6893 // single void argument. 6894 // We let through "const void" here because Sema::GetTypeForDeclarator 6895 // already checks for that case. 6896 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 && 6897 FTI.Params[0].Param && 6898 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) { 6899 // Empty arg list, don't push any params. 6900 } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) { 6901 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 6902 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 6903 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6904 Param->setDeclContext(NewFD); 6905 Params.push_back(Param); 6906 6907 if (Param->isInvalidDecl()) 6908 NewFD->setInvalidDecl(); 6909 } 6910 } 6911 6912 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6913 // When we're declaring a function with a typedef, typeof, etc as in the 6914 // following example, we'll need to synthesize (unnamed) 6915 // parameters for use in the declaration. 6916 // 6917 // @code 6918 // typedef void fn(int); 6919 // fn f; 6920 // @endcode 6921 6922 // Synthesize a parameter for each argument type. 6923 for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(), 6924 AE = FT->param_type_end(); 6925 AI != AE; ++AI) { 6926 ParmVarDecl *Param = 6927 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6928 Param->setScopeInfo(0, Params.size()); 6929 Params.push_back(Param); 6930 } 6931 } else { 6932 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6933 "Should not need args for typedef of non-prototype fn"); 6934 } 6935 6936 // Finally, we know we have the right number of parameters, install them. 6937 NewFD->setParams(Params); 6938 6939 // Find all anonymous symbols defined during the declaration of this function 6940 // and add to NewFD. This lets us track decls such 'enum Y' in: 6941 // 6942 // void f(enum Y {AA} x) {} 6943 // 6944 // which would otherwise incorrectly end up in the translation unit scope. 6945 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6946 DeclsInPrototypeScope.clear(); 6947 6948 if (D.getDeclSpec().isNoreturnSpecified()) 6949 NewFD->addAttr( 6950 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6951 Context, 0)); 6952 6953 // Functions returning a variably modified type violate C99 6.7.5.2p2 6954 // because all functions have linkage. 6955 if (!NewFD->isInvalidDecl() && 6956 NewFD->getReturnType()->isVariablyModifiedType()) { 6957 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6958 NewFD->setInvalidDecl(); 6959 } 6960 6961 // Handle attributes. 6962 ProcessDeclAttributes(S, NewFD, D); 6963 6964 QualType RetType = NewFD->getReturnType(); 6965 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6966 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6967 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6968 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6969 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6970 // Attach WarnUnusedResult to functions returning types with that attribute. 6971 // Don't apply the attribute to that type's own non-static member functions 6972 // (to avoid warning on things like assignment operators) 6973 if (!MD || MD->getParent() != Ret) 6974 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 6975 } 6976 6977 if (getLangOpts().OpenCL) { 6978 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 6979 // type declaration will generate a compilation error. 6980 unsigned AddressSpace = RetType.getAddressSpace(); 6981 if (AddressSpace == LangAS::opencl_local || 6982 AddressSpace == LangAS::opencl_global || 6983 AddressSpace == LangAS::opencl_constant) { 6984 Diag(NewFD->getLocation(), 6985 diag::err_opencl_return_value_with_address_space); 6986 NewFD->setInvalidDecl(); 6987 } 6988 } 6989 6990 if (!getLangOpts().CPlusPlus) { 6991 // Perform semantic checking on the function declaration. 6992 bool isExplicitSpecialization=false; 6993 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 6994 CheckMain(NewFD, D.getDeclSpec()); 6995 6996 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 6997 CheckMSVCRTEntryPoint(NewFD); 6998 6999 if (!NewFD->isInvalidDecl()) 7000 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7001 isExplicitSpecialization)); 7002 else if (!Previous.empty()) 7003 // Make graceful recovery from an invalid redeclaration. 7004 D.setRedeclaration(true); 7005 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7006 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7007 "previous declaration set still overloaded"); 7008 } else { 7009 // C++11 [replacement.functions]p3: 7010 // The program's definitions shall not be specified as inline. 7011 // 7012 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7013 // 7014 // Suppress the diagnostic if the function is __attribute__((used)), since 7015 // that forces an external definition to be emitted. 7016 if (D.getDeclSpec().isInlineSpecified() && 7017 NewFD->isReplaceableGlobalAllocationFunction() && 7018 !NewFD->hasAttr<UsedAttr>()) 7019 Diag(D.getDeclSpec().getInlineSpecLoc(), 7020 diag::ext_operator_new_delete_declared_inline) 7021 << NewFD->getDeclName(); 7022 7023 // If the declarator is a template-id, translate the parser's template 7024 // argument list into our AST format. 7025 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7026 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7027 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7028 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7029 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7030 TemplateId->NumArgs); 7031 translateTemplateArguments(TemplateArgsPtr, 7032 TemplateArgs); 7033 7034 HasExplicitTemplateArgs = true; 7035 7036 if (NewFD->isInvalidDecl()) { 7037 HasExplicitTemplateArgs = false; 7038 } else if (FunctionTemplate) { 7039 // Function template with explicit template arguments. 7040 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7041 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7042 7043 HasExplicitTemplateArgs = false; 7044 } else if (!isFunctionTemplateSpecialization && 7045 !D.getDeclSpec().isFriendSpecified()) { 7046 // We have encountered something that the user meant to be a 7047 // specialization (because it has explicitly-specified template 7048 // arguments) but that was not introduced with a "template<>" (or had 7049 // too few of them). 7050 // FIXME: Differentiate between attempts for explicit instantiations 7051 // (starting with "template") and the rest. 7052 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7053 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7054 << FixItHint::CreateInsertion( 7055 D.getDeclSpec().getLocStart(), 7056 "template<> "); 7057 isFunctionTemplateSpecialization = true; 7058 } else { 7059 // "friend void foo<>(int);" is an implicit specialization decl. 7060 isFunctionTemplateSpecialization = true; 7061 } 7062 } else if (isFriend && isFunctionTemplateSpecialization) { 7063 // This combination is only possible in a recovery case; the user 7064 // wrote something like: 7065 // template <> friend void foo(int); 7066 // which we're recovering from as if the user had written: 7067 // friend void foo<>(int); 7068 // Go ahead and fake up a template id. 7069 HasExplicitTemplateArgs = true; 7070 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7071 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7072 } 7073 7074 // If it's a friend (and only if it's a friend), it's possible 7075 // that either the specialized function type or the specialized 7076 // template is dependent, and therefore matching will fail. In 7077 // this case, don't check the specialization yet. 7078 bool InstantiationDependent = false; 7079 if (isFunctionTemplateSpecialization && isFriend && 7080 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7081 TemplateSpecializationType::anyDependentTemplateArguments( 7082 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7083 InstantiationDependent))) { 7084 assert(HasExplicitTemplateArgs && 7085 "friend function specialization without template args"); 7086 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7087 Previous)) 7088 NewFD->setInvalidDecl(); 7089 } else if (isFunctionTemplateSpecialization) { 7090 if (CurContext->isDependentContext() && CurContext->isRecord() 7091 && !isFriend) { 7092 isDependentClassScopeExplicitSpecialization = true; 7093 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7094 diag::ext_function_specialization_in_class : 7095 diag::err_function_specialization_in_class) 7096 << NewFD->getDeclName(); 7097 } else if (CheckFunctionTemplateSpecialization(NewFD, 7098 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7099 Previous)) 7100 NewFD->setInvalidDecl(); 7101 7102 // C++ [dcl.stc]p1: 7103 // A storage-class-specifier shall not be specified in an explicit 7104 // specialization (14.7.3) 7105 FunctionTemplateSpecializationInfo *Info = 7106 NewFD->getTemplateSpecializationInfo(); 7107 if (Info && SC != SC_None) { 7108 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7109 Diag(NewFD->getLocation(), 7110 diag::err_explicit_specialization_inconsistent_storage_class) 7111 << SC 7112 << FixItHint::CreateRemoval( 7113 D.getDeclSpec().getStorageClassSpecLoc()); 7114 7115 else 7116 Diag(NewFD->getLocation(), 7117 diag::ext_explicit_specialization_storage_class) 7118 << FixItHint::CreateRemoval( 7119 D.getDeclSpec().getStorageClassSpecLoc()); 7120 } 7121 7122 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7123 if (CheckMemberSpecialization(NewFD, Previous)) 7124 NewFD->setInvalidDecl(); 7125 } 7126 7127 // Perform semantic checking on the function declaration. 7128 if (!isDependentClassScopeExplicitSpecialization) { 7129 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7130 CheckMain(NewFD, D.getDeclSpec()); 7131 7132 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7133 CheckMSVCRTEntryPoint(NewFD); 7134 7135 if (!NewFD->isInvalidDecl()) 7136 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7137 isExplicitSpecialization)); 7138 } 7139 7140 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7141 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7142 "previous declaration set still overloaded"); 7143 7144 NamedDecl *PrincipalDecl = (FunctionTemplate 7145 ? cast<NamedDecl>(FunctionTemplate) 7146 : NewFD); 7147 7148 if (isFriend && D.isRedeclaration()) { 7149 AccessSpecifier Access = AS_public; 7150 if (!NewFD->isInvalidDecl()) 7151 Access = NewFD->getPreviousDecl()->getAccess(); 7152 7153 NewFD->setAccess(Access); 7154 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7155 } 7156 7157 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7158 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7159 PrincipalDecl->setNonMemberOperator(); 7160 7161 // If we have a function template, check the template parameter 7162 // list. This will check and merge default template arguments. 7163 if (FunctionTemplate) { 7164 FunctionTemplateDecl *PrevTemplate = 7165 FunctionTemplate->getPreviousDecl(); 7166 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7167 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7168 D.getDeclSpec().isFriendSpecified() 7169 ? (D.isFunctionDefinition() 7170 ? TPC_FriendFunctionTemplateDefinition 7171 : TPC_FriendFunctionTemplate) 7172 : (D.getCXXScopeSpec().isSet() && 7173 DC && DC->isRecord() && 7174 DC->isDependentContext()) 7175 ? TPC_ClassTemplateMember 7176 : TPC_FunctionTemplate); 7177 } 7178 7179 if (NewFD->isInvalidDecl()) { 7180 // Ignore all the rest of this. 7181 } else if (!D.isRedeclaration()) { 7182 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7183 AddToScope }; 7184 // Fake up an access specifier if it's supposed to be a class member. 7185 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7186 NewFD->setAccess(AS_public); 7187 7188 // Qualified decls generally require a previous declaration. 7189 if (D.getCXXScopeSpec().isSet()) { 7190 // ...with the major exception of templated-scope or 7191 // dependent-scope friend declarations. 7192 7193 // TODO: we currently also suppress this check in dependent 7194 // contexts because (1) the parameter depth will be off when 7195 // matching friend templates and (2) we might actually be 7196 // selecting a friend based on a dependent factor. But there 7197 // are situations where these conditions don't apply and we 7198 // can actually do this check immediately. 7199 if (isFriend && 7200 (TemplateParamLists.size() || 7201 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7202 CurContext->isDependentContext())) { 7203 // ignore these 7204 } else { 7205 // The user tried to provide an out-of-line definition for a 7206 // function that is a member of a class or namespace, but there 7207 // was no such member function declared (C++ [class.mfct]p2, 7208 // C++ [namespace.memdef]p2). For example: 7209 // 7210 // class X { 7211 // void f() const; 7212 // }; 7213 // 7214 // void X::f() { } // ill-formed 7215 // 7216 // Complain about this problem, and attempt to suggest close 7217 // matches (e.g., those that differ only in cv-qualifiers and 7218 // whether the parameter types are references). 7219 7220 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7221 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7222 AddToScope = ExtraArgs.AddToScope; 7223 return Result; 7224 } 7225 } 7226 7227 // Unqualified local friend declarations are required to resolve 7228 // to something. 7229 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7230 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7231 *this, Previous, NewFD, ExtraArgs, true, S)) { 7232 AddToScope = ExtraArgs.AddToScope; 7233 return Result; 7234 } 7235 } 7236 7237 } else if (!D.isFunctionDefinition() && 7238 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7239 !isFriend && !isFunctionTemplateSpecialization && 7240 !isExplicitSpecialization) { 7241 // An out-of-line member function declaration must also be a 7242 // definition (C++ [class.mfct]p2). 7243 // Note that this is not the case for explicit specializations of 7244 // function templates or member functions of class templates, per 7245 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7246 // extension for compatibility with old SWIG code which likes to 7247 // generate them. 7248 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7249 << D.getCXXScopeSpec().getRange(); 7250 } 7251 } 7252 7253 ProcessPragmaWeak(S, NewFD); 7254 checkAttributesAfterMerging(*this, *NewFD); 7255 7256 AddKnownFunctionAttributes(NewFD); 7257 7258 if (NewFD->hasAttr<OverloadableAttr>() && 7259 !NewFD->getType()->getAs<FunctionProtoType>()) { 7260 Diag(NewFD->getLocation(), 7261 diag::err_attribute_overloadable_no_prototype) 7262 << NewFD; 7263 7264 // Turn this into a variadic function with no parameters. 7265 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7266 FunctionProtoType::ExtProtoInfo EPI( 7267 Context.getDefaultCallingConvention(true, false)); 7268 EPI.Variadic = true; 7269 EPI.ExtInfo = FT->getExtInfo(); 7270 7271 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7272 NewFD->setType(R); 7273 } 7274 7275 // If there's a #pragma GCC visibility in scope, and this isn't a class 7276 // member, set the visibility of this function. 7277 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7278 AddPushedVisibilityAttribute(NewFD); 7279 7280 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7281 // marking the function. 7282 AddCFAuditedAttribute(NewFD); 7283 7284 // If this is the first declaration of an extern C variable, update 7285 // the map of such variables. 7286 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7287 isIncompleteDeclExternC(*this, NewFD)) 7288 RegisterLocallyScopedExternCDecl(NewFD, S); 7289 7290 // Set this FunctionDecl's range up to the right paren. 7291 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7292 7293 if (getLangOpts().CPlusPlus) { 7294 if (FunctionTemplate) { 7295 if (NewFD->isInvalidDecl()) 7296 FunctionTemplate->setInvalidDecl(); 7297 return FunctionTemplate; 7298 } 7299 } 7300 7301 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7302 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7303 if ((getLangOpts().OpenCLVersion >= 120) 7304 && (SC == SC_Static)) { 7305 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7306 D.setInvalidType(); 7307 } 7308 7309 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7310 if (!NewFD->getReturnType()->isVoidType()) { 7311 Diag(D.getIdentifierLoc(), 7312 diag::err_expected_kernel_void_return_type); 7313 D.setInvalidType(); 7314 } 7315 7316 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7317 for (auto Param : NewFD->params()) 7318 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7319 } 7320 7321 MarkUnusedFileScopedDecl(NewFD); 7322 7323 if (getLangOpts().CUDA) 7324 if (IdentifierInfo *II = NewFD->getIdentifier()) 7325 if (!NewFD->isInvalidDecl() && 7326 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7327 if (II->isStr("cudaConfigureCall")) { 7328 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7329 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7330 7331 Context.setcudaConfigureCallDecl(NewFD); 7332 } 7333 } 7334 7335 // Here we have an function template explicit specialization at class scope. 7336 // The actually specialization will be postponed to template instatiation 7337 // time via the ClassScopeFunctionSpecializationDecl node. 7338 if (isDependentClassScopeExplicitSpecialization) { 7339 ClassScopeFunctionSpecializationDecl *NewSpec = 7340 ClassScopeFunctionSpecializationDecl::Create( 7341 Context, CurContext, SourceLocation(), 7342 cast<CXXMethodDecl>(NewFD), 7343 HasExplicitTemplateArgs, TemplateArgs); 7344 CurContext->addDecl(NewSpec); 7345 AddToScope = false; 7346 } 7347 7348 return NewFD; 7349 } 7350 7351 /// \brief Perform semantic checking of a new function declaration. 7352 /// 7353 /// Performs semantic analysis of the new function declaration 7354 /// NewFD. This routine performs all semantic checking that does not 7355 /// require the actual declarator involved in the declaration, and is 7356 /// used both for the declaration of functions as they are parsed 7357 /// (called via ActOnDeclarator) and for the declaration of functions 7358 /// that have been instantiated via C++ template instantiation (called 7359 /// via InstantiateDecl). 7360 /// 7361 /// \param IsExplicitSpecialization whether this new function declaration is 7362 /// an explicit specialization of the previous declaration. 7363 /// 7364 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7365 /// 7366 /// \returns true if the function declaration is a redeclaration. 7367 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7368 LookupResult &Previous, 7369 bool IsExplicitSpecialization) { 7370 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7371 "Variably modified return types are not handled here"); 7372 7373 // Determine whether the type of this function should be merged with 7374 // a previous visible declaration. This never happens for functions in C++, 7375 // and always happens in C if the previous declaration was visible. 7376 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7377 !Previous.isShadowed(); 7378 7379 // Filter out any non-conflicting previous declarations. 7380 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7381 7382 bool Redeclaration = false; 7383 NamedDecl *OldDecl = 0; 7384 7385 // Merge or overload the declaration with an existing declaration of 7386 // the same name, if appropriate. 7387 if (!Previous.empty()) { 7388 // Determine whether NewFD is an overload of PrevDecl or 7389 // a declaration that requires merging. If it's an overload, 7390 // there's no more work to do here; we'll just add the new 7391 // function to the scope. 7392 if (!AllowOverloadingOfFunction(Previous, Context)) { 7393 NamedDecl *Candidate = Previous.getFoundDecl(); 7394 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7395 Redeclaration = true; 7396 OldDecl = Candidate; 7397 } 7398 } else { 7399 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7400 /*NewIsUsingDecl*/ false)) { 7401 case Ovl_Match: 7402 Redeclaration = true; 7403 break; 7404 7405 case Ovl_NonFunction: 7406 Redeclaration = true; 7407 break; 7408 7409 case Ovl_Overload: 7410 Redeclaration = false; 7411 break; 7412 } 7413 7414 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7415 // If a function name is overloadable in C, then every function 7416 // with that name must be marked "overloadable". 7417 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7418 << Redeclaration << NewFD; 7419 NamedDecl *OverloadedDecl = 0; 7420 if (Redeclaration) 7421 OverloadedDecl = OldDecl; 7422 else if (!Previous.empty()) 7423 OverloadedDecl = Previous.getRepresentativeDecl(); 7424 if (OverloadedDecl) 7425 Diag(OverloadedDecl->getLocation(), 7426 diag::note_attribute_overloadable_prev_overload); 7427 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7428 } 7429 } 7430 } 7431 7432 // Check for a previous extern "C" declaration with this name. 7433 if (!Redeclaration && 7434 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7435 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7436 if (!Previous.empty()) { 7437 // This is an extern "C" declaration with the same name as a previous 7438 // declaration, and thus redeclares that entity... 7439 Redeclaration = true; 7440 OldDecl = Previous.getFoundDecl(); 7441 MergeTypeWithPrevious = false; 7442 7443 // ... except in the presence of __attribute__((overloadable)). 7444 if (OldDecl->hasAttr<OverloadableAttr>()) { 7445 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7446 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7447 << Redeclaration << NewFD; 7448 Diag(Previous.getFoundDecl()->getLocation(), 7449 diag::note_attribute_overloadable_prev_overload); 7450 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7451 } 7452 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7453 Redeclaration = false; 7454 OldDecl = 0; 7455 } 7456 } 7457 } 7458 } 7459 7460 // C++11 [dcl.constexpr]p8: 7461 // A constexpr specifier for a non-static member function that is not 7462 // a constructor declares that member function to be const. 7463 // 7464 // This needs to be delayed until we know whether this is an out-of-line 7465 // definition of a static member function. 7466 // 7467 // This rule is not present in C++1y, so we produce a backwards 7468 // compatibility warning whenever it happens in C++11. 7469 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7470 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7471 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7472 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7473 CXXMethodDecl *OldMD = 0; 7474 if (OldDecl) 7475 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7476 if (!OldMD || !OldMD->isStatic()) { 7477 const FunctionProtoType *FPT = 7478 MD->getType()->castAs<FunctionProtoType>(); 7479 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7480 EPI.TypeQuals |= Qualifiers::Const; 7481 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7482 FPT->getParamTypes(), EPI)); 7483 7484 // Warn that we did this, if we're not performing template instantiation. 7485 // In that case, we'll have warned already when the template was defined. 7486 if (ActiveTemplateInstantiations.empty()) { 7487 SourceLocation AddConstLoc; 7488 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7489 .IgnoreParens().getAs<FunctionTypeLoc>()) 7490 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7491 7492 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7493 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7494 } 7495 } 7496 } 7497 7498 if (Redeclaration) { 7499 // NewFD and OldDecl represent declarations that need to be 7500 // merged. 7501 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7502 NewFD->setInvalidDecl(); 7503 return Redeclaration; 7504 } 7505 7506 Previous.clear(); 7507 Previous.addDecl(OldDecl); 7508 7509 if (FunctionTemplateDecl *OldTemplateDecl 7510 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7511 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7512 FunctionTemplateDecl *NewTemplateDecl 7513 = NewFD->getDescribedFunctionTemplate(); 7514 assert(NewTemplateDecl && "Template/non-template mismatch"); 7515 if (CXXMethodDecl *Method 7516 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7517 Method->setAccess(OldTemplateDecl->getAccess()); 7518 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7519 } 7520 7521 // If this is an explicit specialization of a member that is a function 7522 // template, mark it as a member specialization. 7523 if (IsExplicitSpecialization && 7524 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7525 NewTemplateDecl->setMemberSpecialization(); 7526 assert(OldTemplateDecl->isMemberSpecialization()); 7527 } 7528 7529 } else { 7530 // This needs to happen first so that 'inline' propagates. 7531 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7532 7533 if (isa<CXXMethodDecl>(NewFD)) { 7534 // A valid redeclaration of a C++ method must be out-of-line, 7535 // but (unfortunately) it's not necessarily a definition 7536 // because of templates, which means that the previous 7537 // declaration is not necessarily from the class definition. 7538 7539 // For just setting the access, that doesn't matter. 7540 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7541 NewFD->setAccess(oldMethod->getAccess()); 7542 7543 // Update the key-function state if necessary for this ABI. 7544 if (NewFD->isInlined() && 7545 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7546 // setNonKeyFunction needs to work with the original 7547 // declaration from the class definition, and isVirtual() is 7548 // just faster in that case, so map back to that now. 7549 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7550 if (oldMethod->isVirtual()) { 7551 Context.setNonKeyFunction(oldMethod); 7552 } 7553 } 7554 } 7555 } 7556 } 7557 7558 // Semantic checking for this function declaration (in isolation). 7559 if (getLangOpts().CPlusPlus) { 7560 // C++-specific checks. 7561 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7562 CheckConstructor(Constructor); 7563 } else if (CXXDestructorDecl *Destructor = 7564 dyn_cast<CXXDestructorDecl>(NewFD)) { 7565 CXXRecordDecl *Record = Destructor->getParent(); 7566 QualType ClassType = Context.getTypeDeclType(Record); 7567 7568 // FIXME: Shouldn't we be able to perform this check even when the class 7569 // type is dependent? Both gcc and edg can handle that. 7570 if (!ClassType->isDependentType()) { 7571 DeclarationName Name 7572 = Context.DeclarationNames.getCXXDestructorName( 7573 Context.getCanonicalType(ClassType)); 7574 if (NewFD->getDeclName() != Name) { 7575 Diag(NewFD->getLocation(), diag::err_destructor_name); 7576 NewFD->setInvalidDecl(); 7577 return Redeclaration; 7578 } 7579 } 7580 } else if (CXXConversionDecl *Conversion 7581 = dyn_cast<CXXConversionDecl>(NewFD)) { 7582 ActOnConversionDeclarator(Conversion); 7583 } 7584 7585 // Find any virtual functions that this function overrides. 7586 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7587 if (!Method->isFunctionTemplateSpecialization() && 7588 !Method->getDescribedFunctionTemplate() && 7589 Method->isCanonicalDecl()) { 7590 if (AddOverriddenMethods(Method->getParent(), Method)) { 7591 // If the function was marked as "static", we have a problem. 7592 if (NewFD->getStorageClass() == SC_Static) { 7593 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7594 } 7595 } 7596 } 7597 7598 if (Method->isStatic()) 7599 checkThisInStaticMemberFunctionType(Method); 7600 } 7601 7602 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7603 if (NewFD->isOverloadedOperator() && 7604 CheckOverloadedOperatorDeclaration(NewFD)) { 7605 NewFD->setInvalidDecl(); 7606 return Redeclaration; 7607 } 7608 7609 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7610 if (NewFD->getLiteralIdentifier() && 7611 CheckLiteralOperatorDeclaration(NewFD)) { 7612 NewFD->setInvalidDecl(); 7613 return Redeclaration; 7614 } 7615 7616 // In C++, check default arguments now that we have merged decls. Unless 7617 // the lexical context is the class, because in this case this is done 7618 // during delayed parsing anyway. 7619 if (!CurContext->isRecord()) 7620 CheckCXXDefaultArguments(NewFD); 7621 7622 // If this function declares a builtin function, check the type of this 7623 // declaration against the expected type for the builtin. 7624 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7625 ASTContext::GetBuiltinTypeError Error; 7626 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7627 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7628 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7629 // The type of this function differs from the type of the builtin, 7630 // so forget about the builtin entirely. 7631 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7632 } 7633 } 7634 7635 // If this function is declared as being extern "C", then check to see if 7636 // the function returns a UDT (class, struct, or union type) that is not C 7637 // compatible, and if it does, warn the user. 7638 // But, issue any diagnostic on the first declaration only. 7639 if (NewFD->isExternC() && Previous.empty()) { 7640 QualType R = NewFD->getReturnType(); 7641 if (R->isIncompleteType() && !R->isVoidType()) 7642 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7643 << NewFD << R; 7644 else if (!R.isPODType(Context) && !R->isVoidType() && 7645 !R->isObjCObjectPointerType()) 7646 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7647 } 7648 } 7649 return Redeclaration; 7650 } 7651 7652 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7653 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7654 if (!TSI) 7655 return SourceRange(); 7656 7657 TypeLoc TL = TSI->getTypeLoc(); 7658 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7659 if (!FunctionTL) 7660 return SourceRange(); 7661 7662 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7663 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7664 return ResultTL.getSourceRange(); 7665 7666 return SourceRange(); 7667 } 7668 7669 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7670 // C++11 [basic.start.main]p3: 7671 // A program that [...] declares main to be inline, static or 7672 // constexpr is ill-formed. 7673 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7674 // appear in a declaration of main. 7675 // static main is not an error under C99, but we should warn about it. 7676 // We accept _Noreturn main as an extension. 7677 if (FD->getStorageClass() == SC_Static) 7678 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7679 ? diag::err_static_main : diag::warn_static_main) 7680 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7681 if (FD->isInlineSpecified()) 7682 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7683 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7684 if (DS.isNoreturnSpecified()) { 7685 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7686 SourceRange NoreturnRange(NoreturnLoc, 7687 PP.getLocForEndOfToken(NoreturnLoc)); 7688 Diag(NoreturnLoc, diag::ext_noreturn_main); 7689 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7690 << FixItHint::CreateRemoval(NoreturnRange); 7691 } 7692 if (FD->isConstexpr()) { 7693 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7694 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7695 FD->setConstexpr(false); 7696 } 7697 7698 if (getLangOpts().OpenCL) { 7699 Diag(FD->getLocation(), diag::err_opencl_no_main) 7700 << FD->hasAttr<OpenCLKernelAttr>(); 7701 FD->setInvalidDecl(); 7702 return; 7703 } 7704 7705 QualType T = FD->getType(); 7706 assert(T->isFunctionType() && "function decl is not of function type"); 7707 const FunctionType* FT = T->castAs<FunctionType>(); 7708 7709 // All the standards say that main() should should return 'int'. 7710 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7711 // In C and C++, main magically returns 0 if you fall off the end; 7712 // set the flag which tells us that. 7713 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7714 FD->setHasImplicitReturnZero(true); 7715 7716 // In C with GNU extensions we allow main() to have non-integer return 7717 // type, but we should warn about the extension, and we disable the 7718 // implicit-return-zero rule. 7719 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7720 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7721 7722 SourceRange ResultRange = getResultSourceRange(FD); 7723 if (ResultRange.isValid()) 7724 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7725 << FixItHint::CreateReplacement(ResultRange, "int"); 7726 7727 // Otherwise, this is just a flat-out error. 7728 } else { 7729 SourceRange ResultRange = getResultSourceRange(FD); 7730 if (ResultRange.isValid()) 7731 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7732 << FixItHint::CreateReplacement(ResultRange, "int"); 7733 else 7734 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7735 7736 FD->setInvalidDecl(true); 7737 } 7738 7739 // Treat protoless main() as nullary. 7740 if (isa<FunctionNoProtoType>(FT)) return; 7741 7742 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7743 unsigned nparams = FTP->getNumParams(); 7744 assert(FD->getNumParams() == nparams); 7745 7746 bool HasExtraParameters = (nparams > 3); 7747 7748 // Darwin passes an undocumented fourth argument of type char**. If 7749 // other platforms start sprouting these, the logic below will start 7750 // getting shifty. 7751 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7752 HasExtraParameters = false; 7753 7754 if (HasExtraParameters) { 7755 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7756 FD->setInvalidDecl(true); 7757 nparams = 3; 7758 } 7759 7760 // FIXME: a lot of the following diagnostics would be improved 7761 // if we had some location information about types. 7762 7763 QualType CharPP = 7764 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7765 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7766 7767 for (unsigned i = 0; i < nparams; ++i) { 7768 QualType AT = FTP->getParamType(i); 7769 7770 bool mismatch = true; 7771 7772 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7773 mismatch = false; 7774 else if (Expected[i] == CharPP) { 7775 // As an extension, the following forms are okay: 7776 // char const ** 7777 // char const * const * 7778 // char * const * 7779 7780 QualifierCollector qs; 7781 const PointerType* PT; 7782 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7783 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7784 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7785 Context.CharTy)) { 7786 qs.removeConst(); 7787 mismatch = !qs.empty(); 7788 } 7789 } 7790 7791 if (mismatch) { 7792 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7793 // TODO: suggest replacing given type with expected type 7794 FD->setInvalidDecl(true); 7795 } 7796 } 7797 7798 if (nparams == 1 && !FD->isInvalidDecl()) { 7799 Diag(FD->getLocation(), diag::warn_main_one_arg); 7800 } 7801 7802 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7803 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7804 FD->setInvalidDecl(); 7805 } 7806 } 7807 7808 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7809 QualType T = FD->getType(); 7810 assert(T->isFunctionType() && "function decl is not of function type"); 7811 const FunctionType *FT = T->castAs<FunctionType>(); 7812 7813 // Set an implicit return of 'zero' if the function can return some integral, 7814 // enumeration, pointer or nullptr type. 7815 if (FT->getReturnType()->isIntegralOrEnumerationType() || 7816 FT->getReturnType()->isAnyPointerType() || 7817 FT->getReturnType()->isNullPtrType()) 7818 // DllMain is exempt because a return value of zero means it failed. 7819 if (FD->getName() != "DllMain") 7820 FD->setHasImplicitReturnZero(true); 7821 7822 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7823 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7824 FD->setInvalidDecl(); 7825 } 7826 } 7827 7828 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7829 // FIXME: Need strict checking. In C89, we need to check for 7830 // any assignment, increment, decrement, function-calls, or 7831 // commas outside of a sizeof. In C99, it's the same list, 7832 // except that the aforementioned are allowed in unevaluated 7833 // expressions. Everything else falls under the 7834 // "may accept other forms of constant expressions" exception. 7835 // (We never end up here for C++, so the constant expression 7836 // rules there don't matter.) 7837 if (Init->isConstantInitializer(Context, false)) 7838 return false; 7839 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7840 << Init->getSourceRange(); 7841 return true; 7842 } 7843 7844 namespace { 7845 // Visits an initialization expression to see if OrigDecl is evaluated in 7846 // its own initialization and throws a warning if it does. 7847 class SelfReferenceChecker 7848 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7849 Sema &S; 7850 Decl *OrigDecl; 7851 bool isRecordType; 7852 bool isPODType; 7853 bool isReferenceType; 7854 7855 public: 7856 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7857 7858 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7859 S(S), OrigDecl(OrigDecl) { 7860 isPODType = false; 7861 isRecordType = false; 7862 isReferenceType = false; 7863 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7864 isPODType = VD->getType().isPODType(S.Context); 7865 isRecordType = VD->getType()->isRecordType(); 7866 isReferenceType = VD->getType()->isReferenceType(); 7867 } 7868 } 7869 7870 // For most expressions, the cast is directly above the DeclRefExpr. 7871 // For conditional operators, the cast can be outside the conditional 7872 // operator if both expressions are DeclRefExpr's. 7873 void HandleValue(Expr *E) { 7874 if (isReferenceType) 7875 return; 7876 E = E->IgnoreParenImpCasts(); 7877 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7878 HandleDeclRefExpr(DRE); 7879 return; 7880 } 7881 7882 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7883 HandleValue(CO->getTrueExpr()); 7884 HandleValue(CO->getFalseExpr()); 7885 return; 7886 } 7887 7888 if (isa<MemberExpr>(E)) { 7889 Expr *Base = E->IgnoreParenImpCasts(); 7890 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7891 // Check for static member variables and don't warn on them. 7892 if (!isa<FieldDecl>(ME->getMemberDecl())) 7893 return; 7894 Base = ME->getBase()->IgnoreParenImpCasts(); 7895 } 7896 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7897 HandleDeclRefExpr(DRE); 7898 return; 7899 } 7900 } 7901 7902 // Reference types are handled here since all uses of references are 7903 // bad, not just r-value uses. 7904 void VisitDeclRefExpr(DeclRefExpr *E) { 7905 if (isReferenceType) 7906 HandleDeclRefExpr(E); 7907 } 7908 7909 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7910 if (E->getCastKind() == CK_LValueToRValue || 7911 (isRecordType && E->getCastKind() == CK_NoOp)) 7912 HandleValue(E->getSubExpr()); 7913 7914 Inherited::VisitImplicitCastExpr(E); 7915 } 7916 7917 void VisitMemberExpr(MemberExpr *E) { 7918 // Don't warn on arrays since they can be treated as pointers. 7919 if (E->getType()->canDecayToPointerType()) return; 7920 7921 // Warn when a non-static method call is followed by non-static member 7922 // field accesses, which is followed by a DeclRefExpr. 7923 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7924 bool Warn = (MD && !MD->isStatic()); 7925 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7926 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7927 if (!isa<FieldDecl>(ME->getMemberDecl())) 7928 Warn = false; 7929 Base = ME->getBase()->IgnoreParenImpCasts(); 7930 } 7931 7932 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7933 if (Warn) 7934 HandleDeclRefExpr(DRE); 7935 return; 7936 } 7937 7938 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7939 // Visit that expression. 7940 Visit(Base); 7941 } 7942 7943 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7944 if (E->getNumArgs() > 0) 7945 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7946 HandleDeclRefExpr(DRE); 7947 7948 Inherited::VisitCXXOperatorCallExpr(E); 7949 } 7950 7951 void VisitUnaryOperator(UnaryOperator *E) { 7952 // For POD record types, addresses of its own members are well-defined. 7953 if (E->getOpcode() == UO_AddrOf && isRecordType && 7954 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7955 if (!isPODType) 7956 HandleValue(E->getSubExpr()); 7957 return; 7958 } 7959 Inherited::VisitUnaryOperator(E); 7960 } 7961 7962 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7963 7964 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7965 Decl* ReferenceDecl = DRE->getDecl(); 7966 if (OrigDecl != ReferenceDecl) return; 7967 unsigned diag; 7968 if (isReferenceType) { 7969 diag = diag::warn_uninit_self_reference_in_reference_init; 7970 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7971 diag = diag::warn_static_self_reference_in_init; 7972 } else { 7973 diag = diag::warn_uninit_self_reference_in_init; 7974 } 7975 7976 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7977 S.PDiag(diag) 7978 << DRE->getNameInfo().getName() 7979 << OrigDecl->getLocation() 7980 << DRE->getSourceRange()); 7981 } 7982 }; 7983 7984 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 7985 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 7986 bool DirectInit) { 7987 // Parameters arguments are occassionially constructed with itself, 7988 // for instance, in recursive functions. Skip them. 7989 if (isa<ParmVarDecl>(OrigDecl)) 7990 return; 7991 7992 E = E->IgnoreParens(); 7993 7994 // Skip checking T a = a where T is not a record or reference type. 7995 // Doing so is a way to silence uninitialized warnings. 7996 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 7997 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 7998 if (ICE->getCastKind() == CK_LValueToRValue) 7999 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8000 if (DRE->getDecl() == OrigDecl) 8001 return; 8002 8003 SelfReferenceChecker(S, OrigDecl).Visit(E); 8004 } 8005 } 8006 8007 /// AddInitializerToDecl - Adds the initializer Init to the 8008 /// declaration dcl. If DirectInit is true, this is C++ direct 8009 /// initialization rather than copy initialization. 8010 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8011 bool DirectInit, bool TypeMayContainAuto) { 8012 // If there is no declaration, there was an error parsing it. Just ignore 8013 // the initializer. 8014 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8015 return; 8016 8017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8018 // With declarators parsed the way they are, the parser cannot 8019 // distinguish between a normal initializer and a pure-specifier. 8020 // Thus this grotesque test. 8021 IntegerLiteral *IL; 8022 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8023 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8024 CheckPureMethod(Method, Init->getSourceRange()); 8025 else { 8026 Diag(Method->getLocation(), diag::err_member_function_initialization) 8027 << Method->getDeclName() << Init->getSourceRange(); 8028 Method->setInvalidDecl(); 8029 } 8030 return; 8031 } 8032 8033 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8034 if (!VDecl) { 8035 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8036 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8037 RealDecl->setInvalidDecl(); 8038 return; 8039 } 8040 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8041 8042 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8043 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8044 Expr *DeduceInit = Init; 8045 // Initializer could be a C++ direct-initializer. Deduction only works if it 8046 // contains exactly one expression. 8047 if (CXXDirectInit) { 8048 if (CXXDirectInit->getNumExprs() == 0) { 8049 // It isn't possible to write this directly, but it is possible to 8050 // end up in this situation with "auto x(some_pack...);" 8051 Diag(CXXDirectInit->getLocStart(), 8052 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8053 : diag::err_auto_var_init_no_expression) 8054 << VDecl->getDeclName() << VDecl->getType() 8055 << VDecl->getSourceRange(); 8056 RealDecl->setInvalidDecl(); 8057 return; 8058 } else if (CXXDirectInit->getNumExprs() > 1) { 8059 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8060 VDecl->isInitCapture() 8061 ? diag::err_init_capture_multiple_expressions 8062 : diag::err_auto_var_init_multiple_expressions) 8063 << VDecl->getDeclName() << VDecl->getType() 8064 << VDecl->getSourceRange(); 8065 RealDecl->setInvalidDecl(); 8066 return; 8067 } else { 8068 DeduceInit = CXXDirectInit->getExpr(0); 8069 } 8070 } 8071 8072 // Expressions default to 'id' when we're in a debugger. 8073 bool DefaultedToAuto = false; 8074 if (getLangOpts().DebuggerCastResultToId && 8075 Init->getType() == Context.UnknownAnyTy) { 8076 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8077 if (Result.isInvalid()) { 8078 VDecl->setInvalidDecl(); 8079 return; 8080 } 8081 Init = Result.take(); 8082 DefaultedToAuto = true; 8083 } 8084 8085 QualType DeducedType; 8086 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8087 DAR_Failed) 8088 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8089 if (DeducedType.isNull()) { 8090 RealDecl->setInvalidDecl(); 8091 return; 8092 } 8093 VDecl->setType(DeducedType); 8094 assert(VDecl->isLinkageValid()); 8095 8096 // In ARC, infer lifetime. 8097 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8098 VDecl->setInvalidDecl(); 8099 8100 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8101 // 'id' instead of a specific object type prevents most of our usual checks. 8102 // We only want to warn outside of template instantiations, though: 8103 // inside a template, the 'id' could have come from a parameter. 8104 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8105 DeducedType->isObjCIdType()) { 8106 SourceLocation Loc = 8107 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8108 Diag(Loc, diag::warn_auto_var_is_id) 8109 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8110 } 8111 8112 // If this is a redeclaration, check that the type we just deduced matches 8113 // the previously declared type. 8114 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8115 // We never need to merge the type, because we cannot form an incomplete 8116 // array of auto, nor deduce such a type. 8117 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8118 } 8119 8120 // Check the deduced type is valid for a variable declaration. 8121 CheckVariableDeclarationType(VDecl); 8122 if (VDecl->isInvalidDecl()) 8123 return; 8124 } 8125 8126 // dllimport cannot be used on variable definitions. 8127 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8128 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8129 VDecl->setInvalidDecl(); 8130 return; 8131 } 8132 8133 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8134 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8135 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8136 VDecl->setInvalidDecl(); 8137 return; 8138 } 8139 8140 if (!VDecl->getType()->isDependentType()) { 8141 // A definition must end up with a complete type, which means it must be 8142 // complete with the restriction that an array type might be completed by 8143 // the initializer; note that later code assumes this restriction. 8144 QualType BaseDeclType = VDecl->getType(); 8145 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8146 BaseDeclType = Array->getElementType(); 8147 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8148 diag::err_typecheck_decl_incomplete_type)) { 8149 RealDecl->setInvalidDecl(); 8150 return; 8151 } 8152 8153 // The variable can not have an abstract class type. 8154 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8155 diag::err_abstract_type_in_decl, 8156 AbstractVariableType)) 8157 VDecl->setInvalidDecl(); 8158 } 8159 8160 const VarDecl *Def; 8161 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8162 Diag(VDecl->getLocation(), diag::err_redefinition) 8163 << VDecl->getDeclName(); 8164 Diag(Def->getLocation(), diag::note_previous_definition); 8165 VDecl->setInvalidDecl(); 8166 return; 8167 } 8168 8169 const VarDecl* PrevInit = 0; 8170 if (getLangOpts().CPlusPlus) { 8171 // C++ [class.static.data]p4 8172 // If a static data member is of const integral or const 8173 // enumeration type, its declaration in the class definition can 8174 // specify a constant-initializer which shall be an integral 8175 // constant expression (5.19). In that case, the member can appear 8176 // in integral constant expressions. The member shall still be 8177 // defined in a namespace scope if it is used in the program and the 8178 // namespace scope definition shall not contain an initializer. 8179 // 8180 // We already performed a redefinition check above, but for static 8181 // data members we also need to check whether there was an in-class 8182 // declaration with an initializer. 8183 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8184 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8185 << VDecl->getDeclName(); 8186 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8187 return; 8188 } 8189 8190 if (VDecl->hasLocalStorage()) 8191 getCurFunction()->setHasBranchProtectedScope(); 8192 8193 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8194 VDecl->setInvalidDecl(); 8195 return; 8196 } 8197 } 8198 8199 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8200 // a kernel function cannot be initialized." 8201 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8202 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8203 VDecl->setInvalidDecl(); 8204 return; 8205 } 8206 8207 // Get the decls type and save a reference for later, since 8208 // CheckInitializerTypes may change it. 8209 QualType DclT = VDecl->getType(), SavT = DclT; 8210 8211 // Expressions default to 'id' when we're in a debugger 8212 // and we are assigning it to a variable of Objective-C pointer type. 8213 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8214 Init->getType() == Context.UnknownAnyTy) { 8215 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8216 if (Result.isInvalid()) { 8217 VDecl->setInvalidDecl(); 8218 return; 8219 } 8220 Init = Result.take(); 8221 } 8222 8223 // Perform the initialization. 8224 if (!VDecl->isInvalidDecl()) { 8225 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8226 InitializationKind Kind 8227 = DirectInit ? 8228 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8229 Init->getLocStart(), 8230 Init->getLocEnd()) 8231 : InitializationKind::CreateDirectList( 8232 VDecl->getLocation()) 8233 : InitializationKind::CreateCopy(VDecl->getLocation(), 8234 Init->getLocStart()); 8235 8236 MultiExprArg Args = Init; 8237 if (CXXDirectInit) 8238 Args = MultiExprArg(CXXDirectInit->getExprs(), 8239 CXXDirectInit->getNumExprs()); 8240 8241 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8242 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8243 if (Result.isInvalid()) { 8244 VDecl->setInvalidDecl(); 8245 return; 8246 } 8247 8248 Init = Result.takeAs<Expr>(); 8249 } 8250 8251 // Check for self-references within variable initializers. 8252 // Variables declared within a function/method body (except for references) 8253 // are handled by a dataflow analysis. 8254 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8255 VDecl->getType()->isReferenceType()) { 8256 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8257 } 8258 8259 // If the type changed, it means we had an incomplete type that was 8260 // completed by the initializer. For example: 8261 // int ary[] = { 1, 3, 5 }; 8262 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8263 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8264 VDecl->setType(DclT); 8265 8266 if (!VDecl->isInvalidDecl()) { 8267 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8268 8269 if (VDecl->hasAttr<BlocksAttr>()) 8270 checkRetainCycles(VDecl, Init); 8271 8272 // It is safe to assign a weak reference into a strong variable. 8273 // Although this code can still have problems: 8274 // id x = self.weakProp; 8275 // id y = self.weakProp; 8276 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8277 // paths through the function. This should be revisited if 8278 // -Wrepeated-use-of-weak is made flow-sensitive. 8279 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8280 DiagnosticsEngine::Level Level = 8281 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8282 Init->getLocStart()); 8283 if (Level != DiagnosticsEngine::Ignored) 8284 getCurFunction()->markSafeWeakUse(Init); 8285 } 8286 } 8287 8288 // The initialization is usually a full-expression. 8289 // 8290 // FIXME: If this is a braced initialization of an aggregate, it is not 8291 // an expression, and each individual field initializer is a separate 8292 // full-expression. For instance, in: 8293 // 8294 // struct Temp { ~Temp(); }; 8295 // struct S { S(Temp); }; 8296 // struct T { S a, b; } t = { Temp(), Temp() } 8297 // 8298 // we should destroy the first Temp before constructing the second. 8299 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8300 false, 8301 VDecl->isConstexpr()); 8302 if (Result.isInvalid()) { 8303 VDecl->setInvalidDecl(); 8304 return; 8305 } 8306 Init = Result.take(); 8307 8308 // Attach the initializer to the decl. 8309 VDecl->setInit(Init); 8310 8311 if (VDecl->isLocalVarDecl()) { 8312 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8313 // static storage duration shall be constant expressions or string literals. 8314 // C++ does not have this restriction. 8315 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8316 if (VDecl->getStorageClass() == SC_Static) 8317 CheckForConstantInitializer(Init, DclT); 8318 // C89 is stricter than C99 for non-static aggregate types. 8319 // C89 6.5.7p3: All the expressions [...] in an initializer list 8320 // for an object that has aggregate or union type shall be 8321 // constant expressions. 8322 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8323 isa<InitListExpr>(Init) && 8324 !Init->isConstantInitializer(Context, false)) 8325 Diag(Init->getExprLoc(), 8326 diag::ext_aggregate_init_not_constant) 8327 << Init->getSourceRange(); 8328 } 8329 } else if (VDecl->isStaticDataMember() && 8330 VDecl->getLexicalDeclContext()->isRecord()) { 8331 // This is an in-class initialization for a static data member, e.g., 8332 // 8333 // struct S { 8334 // static const int value = 17; 8335 // }; 8336 8337 // C++ [class.mem]p4: 8338 // A member-declarator can contain a constant-initializer only 8339 // if it declares a static member (9.4) of const integral or 8340 // const enumeration type, see 9.4.2. 8341 // 8342 // C++11 [class.static.data]p3: 8343 // If a non-volatile const static data member is of integral or 8344 // enumeration type, its declaration in the class definition can 8345 // specify a brace-or-equal-initializer in which every initalizer-clause 8346 // that is an assignment-expression is a constant expression. A static 8347 // data member of literal type can be declared in the class definition 8348 // with the constexpr specifier; if so, its declaration shall specify a 8349 // brace-or-equal-initializer in which every initializer-clause that is 8350 // an assignment-expression is a constant expression. 8351 8352 // Do nothing on dependent types. 8353 if (DclT->isDependentType()) { 8354 8355 // Allow any 'static constexpr' members, whether or not they are of literal 8356 // type. We separately check that every constexpr variable is of literal 8357 // type. 8358 } else if (VDecl->isConstexpr()) { 8359 8360 // Require constness. 8361 } else if (!DclT.isConstQualified()) { 8362 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8363 << Init->getSourceRange(); 8364 VDecl->setInvalidDecl(); 8365 8366 // We allow integer constant expressions in all cases. 8367 } else if (DclT->isIntegralOrEnumerationType()) { 8368 // Check whether the expression is a constant expression. 8369 SourceLocation Loc; 8370 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8371 // In C++11, a non-constexpr const static data member with an 8372 // in-class initializer cannot be volatile. 8373 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8374 else if (Init->isValueDependent()) 8375 ; // Nothing to check. 8376 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8377 ; // Ok, it's an ICE! 8378 else if (Init->isEvaluatable(Context)) { 8379 // If we can constant fold the initializer through heroics, accept it, 8380 // but report this as a use of an extension for -pedantic. 8381 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8382 << Init->getSourceRange(); 8383 } else { 8384 // Otherwise, this is some crazy unknown case. Report the issue at the 8385 // location provided by the isIntegerConstantExpr failed check. 8386 Diag(Loc, diag::err_in_class_initializer_non_constant) 8387 << Init->getSourceRange(); 8388 VDecl->setInvalidDecl(); 8389 } 8390 8391 // We allow foldable floating-point constants as an extension. 8392 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8393 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8394 // it anyway and provide a fixit to add the 'constexpr'. 8395 if (getLangOpts().CPlusPlus11) { 8396 Diag(VDecl->getLocation(), 8397 diag::ext_in_class_initializer_float_type_cxx11) 8398 << DclT << Init->getSourceRange(); 8399 Diag(VDecl->getLocStart(), 8400 diag::note_in_class_initializer_float_type_cxx11) 8401 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8402 } else { 8403 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8404 << DclT << Init->getSourceRange(); 8405 8406 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8407 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8408 << Init->getSourceRange(); 8409 VDecl->setInvalidDecl(); 8410 } 8411 } 8412 8413 // Suggest adding 'constexpr' in C++11 for literal types. 8414 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8415 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8416 << DclT << Init->getSourceRange() 8417 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8418 VDecl->setConstexpr(true); 8419 8420 } else { 8421 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8422 << DclT << Init->getSourceRange(); 8423 VDecl->setInvalidDecl(); 8424 } 8425 } else if (VDecl->isFileVarDecl()) { 8426 if (VDecl->getStorageClass() == SC_Extern && 8427 (!getLangOpts().CPlusPlus || 8428 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8429 VDecl->isExternC())) && 8430 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8431 Diag(VDecl->getLocation(), diag::warn_extern_init); 8432 8433 // C99 6.7.8p4. All file scoped initializers need to be constant. 8434 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8435 CheckForConstantInitializer(Init, DclT); 8436 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8437 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8438 !Init->isValueDependent() && !VDecl->isConstexpr() && 8439 !Init->isConstantInitializer( 8440 Context, VDecl->getType()->isReferenceType())) { 8441 // GNU C++98 edits for __thread, [basic.start.init]p4: 8442 // An object of thread storage duration shall not require dynamic 8443 // initialization. 8444 // FIXME: Need strict checking here. 8445 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8446 if (getLangOpts().CPlusPlus11) 8447 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8448 } 8449 } 8450 8451 // We will represent direct-initialization similarly to copy-initialization: 8452 // int x(1); -as-> int x = 1; 8453 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8454 // 8455 // Clients that want to distinguish between the two forms, can check for 8456 // direct initializer using VarDecl::getInitStyle(). 8457 // A major benefit is that clients that don't particularly care about which 8458 // exactly form was it (like the CodeGen) can handle both cases without 8459 // special case code. 8460 8461 // C++ 8.5p11: 8462 // The form of initialization (using parentheses or '=') is generally 8463 // insignificant, but does matter when the entity being initialized has a 8464 // class type. 8465 if (CXXDirectInit) { 8466 assert(DirectInit && "Call-style initializer must be direct init."); 8467 VDecl->setInitStyle(VarDecl::CallInit); 8468 } else if (DirectInit) { 8469 // This must be list-initialization. No other way is direct-initialization. 8470 VDecl->setInitStyle(VarDecl::ListInit); 8471 } 8472 8473 CheckCompleteVariableDeclaration(VDecl); 8474 } 8475 8476 /// ActOnInitializerError - Given that there was an error parsing an 8477 /// initializer for the given declaration, try to return to some form 8478 /// of sanity. 8479 void Sema::ActOnInitializerError(Decl *D) { 8480 // Our main concern here is re-establishing invariants like "a 8481 // variable's type is either dependent or complete". 8482 if (!D || D->isInvalidDecl()) return; 8483 8484 VarDecl *VD = dyn_cast<VarDecl>(D); 8485 if (!VD) return; 8486 8487 // Auto types are meaningless if we can't make sense of the initializer. 8488 if (ParsingInitForAutoVars.count(D)) { 8489 D->setInvalidDecl(); 8490 return; 8491 } 8492 8493 QualType Ty = VD->getType(); 8494 if (Ty->isDependentType()) return; 8495 8496 // Require a complete type. 8497 if (RequireCompleteType(VD->getLocation(), 8498 Context.getBaseElementType(Ty), 8499 diag::err_typecheck_decl_incomplete_type)) { 8500 VD->setInvalidDecl(); 8501 return; 8502 } 8503 8504 // Require an abstract type. 8505 if (RequireNonAbstractType(VD->getLocation(), Ty, 8506 diag::err_abstract_type_in_decl, 8507 AbstractVariableType)) { 8508 VD->setInvalidDecl(); 8509 return; 8510 } 8511 8512 // Don't bother complaining about constructors or destructors, 8513 // though. 8514 } 8515 8516 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8517 bool TypeMayContainAuto) { 8518 // If there is no declaration, there was an error parsing it. Just ignore it. 8519 if (RealDecl == 0) 8520 return; 8521 8522 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8523 QualType Type = Var->getType(); 8524 8525 // C++11 [dcl.spec.auto]p3 8526 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8527 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8528 << Var->getDeclName() << Type; 8529 Var->setInvalidDecl(); 8530 return; 8531 } 8532 8533 // C++11 [class.static.data]p3: A static data member can be declared with 8534 // the constexpr specifier; if so, its declaration shall specify 8535 // a brace-or-equal-initializer. 8536 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8537 // the definition of a variable [...] or the declaration of a static data 8538 // member. 8539 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8540 if (Var->isStaticDataMember()) 8541 Diag(Var->getLocation(), 8542 diag::err_constexpr_static_mem_var_requires_init) 8543 << Var->getDeclName(); 8544 else 8545 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8546 Var->setInvalidDecl(); 8547 return; 8548 } 8549 8550 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8551 // be initialized. 8552 if (!Var->isInvalidDecl() && 8553 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8554 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8555 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 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 // Warn about externally-visible variables being defined without a 8791 // prior declaration. We only want to do this for global 8792 // declarations, but we also specifically need to avoid doing it for 8793 // class members because the linkage of an anonymous class can 8794 // change if it's later given a typedef name. 8795 if (var->isThisDeclarationADefinition() && 8796 var->getDeclContext()->getRedeclContext()->isFileContext() && 8797 var->isExternallyVisible() && var->hasLinkage() && 8798 getDiagnostics().getDiagnosticLevel( 8799 diag::warn_missing_variable_declarations, 8800 var->getLocation())) { 8801 // Find a previous declaration that's not a definition. 8802 VarDecl *prev = var->getPreviousDecl(); 8803 while (prev && prev->isThisDeclarationADefinition()) 8804 prev = prev->getPreviousDecl(); 8805 8806 if (!prev) 8807 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8808 } 8809 8810 if (var->getTLSKind() == VarDecl::TLS_Static && 8811 var->getType().isDestructedType()) { 8812 // GNU C++98 edits for __thread, [basic.start.term]p3: 8813 // The type of an object with thread storage duration shall not 8814 // have a non-trivial destructor. 8815 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8816 if (getLangOpts().CPlusPlus11) 8817 Diag(var->getLocation(), diag::note_use_thread_local); 8818 } 8819 8820 // All the following checks are C++ only. 8821 if (!getLangOpts().CPlusPlus) return; 8822 8823 QualType type = var->getType(); 8824 if (type->isDependentType()) return; 8825 8826 // __block variables might require us to capture a copy-initializer. 8827 if (var->hasAttr<BlocksAttr>()) { 8828 // It's currently invalid to ever have a __block variable with an 8829 // array type; should we diagnose that here? 8830 8831 // Regardless, we don't want to ignore array nesting when 8832 // constructing this copy. 8833 if (type->isStructureOrClassType()) { 8834 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8835 SourceLocation poi = var->getLocation(); 8836 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8837 ExprResult result 8838 = PerformMoveOrCopyInitialization( 8839 InitializedEntity::InitializeBlock(poi, type, false), 8840 var, var->getType(), varRef, /*AllowNRVO=*/true); 8841 if (!result.isInvalid()) { 8842 result = MaybeCreateExprWithCleanups(result); 8843 Expr *init = result.takeAs<Expr>(); 8844 Context.setBlockVarCopyInits(var, init); 8845 } 8846 } 8847 } 8848 8849 Expr *Init = var->getInit(); 8850 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8851 QualType baseType = Context.getBaseElementType(type); 8852 8853 if (!var->getDeclContext()->isDependentContext() && 8854 Init && !Init->isValueDependent()) { 8855 if (IsGlobal && !var->isConstexpr() && 8856 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8857 var->getLocation()) 8858 != DiagnosticsEngine::Ignored) { 8859 // Warn about globals which don't have a constant initializer. Don't 8860 // warn about globals with a non-trivial destructor because we already 8861 // warned about them. 8862 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8863 if (!(RD && !RD->hasTrivialDestructor()) && 8864 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8865 Diag(var->getLocation(), diag::warn_global_constructor) 8866 << Init->getSourceRange(); 8867 } 8868 8869 if (var->isConstexpr()) { 8870 SmallVector<PartialDiagnosticAt, 8> Notes; 8871 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8872 SourceLocation DiagLoc = var->getLocation(); 8873 // If the note doesn't add any useful information other than a source 8874 // location, fold it into the primary diagnostic. 8875 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 8876 diag::note_invalid_subexpr_in_const_expr) { 8877 DiagLoc = Notes[0].first; 8878 Notes.clear(); 8879 } 8880 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 8881 << var << Init->getSourceRange(); 8882 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 8883 Diag(Notes[I].first, Notes[I].second); 8884 } 8885 } else if (var->isUsableInConstantExpressions(Context)) { 8886 // Check whether the initializer of a const variable of integral or 8887 // enumeration type is an ICE now, since we can't tell whether it was 8888 // initialized by a constant expression if we check later. 8889 var->checkInitIsICE(); 8890 } 8891 } 8892 8893 // Require the destructor. 8894 if (const RecordType *recordType = baseType->getAs<RecordType>()) 8895 FinalizeVarWithDestructor(var, recordType); 8896 } 8897 8898 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 8899 /// any semantic actions necessary after any initializer has been attached. 8900 void 8901 Sema::FinalizeDeclaration(Decl *ThisDecl) { 8902 // Note that we are no longer parsing the initializer for this declaration. 8903 ParsingInitForAutoVars.erase(ThisDecl); 8904 8905 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 8906 if (!VD) 8907 return; 8908 8909 checkAttributesAfterMerging(*this, *VD); 8910 8911 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 8912 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 8913 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 8914 VD->dropAttr<UsedAttr>(); 8915 } 8916 } 8917 8918 if (!VD->isInvalidDecl() && 8919 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 8920 if (const VarDecl *Def = VD->getDefinition()) { 8921 if (Def->hasAttr<AliasAttr>()) { 8922 Diag(VD->getLocation(), diag::err_tentative_after_alias) 8923 << VD->getDeclName(); 8924 Diag(Def->getLocation(), diag::note_previous_definition); 8925 VD->setInvalidDecl(); 8926 } 8927 } 8928 } 8929 8930 const DeclContext *DC = VD->getDeclContext(); 8931 // If there's a #pragma GCC visibility in scope, and this isn't a class 8932 // member, set the visibility of this variable. 8933 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 8934 AddPushedVisibilityAttribute(VD); 8935 8936 if (VD->isFileVarDecl()) 8937 MarkUnusedFileScopedDecl(VD); 8938 8939 // Now we have parsed the initializer and can update the table of magic 8940 // tag values. 8941 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8942 !VD->getType()->isIntegralOrEnumerationType()) 8943 return; 8944 8945 for (specific_attr_iterator<TypeTagForDatatypeAttr> 8946 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 8947 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 8948 I != E; ++I) { 8949 const Expr *MagicValueExpr = VD->getInit(); 8950 if (!MagicValueExpr) { 8951 continue; 8952 } 8953 llvm::APSInt MagicValueInt; 8954 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8955 Diag(I->getRange().getBegin(), 8956 diag::err_type_tag_for_datatype_not_ice) 8957 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8958 continue; 8959 } 8960 if (MagicValueInt.getActiveBits() > 64) { 8961 Diag(I->getRange().getBegin(), 8962 diag::err_type_tag_for_datatype_too_large) 8963 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8964 continue; 8965 } 8966 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8967 RegisterTypeTagForDatatype(I->getArgumentKind(), 8968 MagicValue, 8969 I->getMatchingCType(), 8970 I->getLayoutCompatible(), 8971 I->getMustBeNull()); 8972 } 8973 } 8974 8975 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8976 ArrayRef<Decl *> Group) { 8977 SmallVector<Decl*, 8> Decls; 8978 8979 if (DS.isTypeSpecOwned()) 8980 Decls.push_back(DS.getRepAsDecl()); 8981 8982 DeclaratorDecl *FirstDeclaratorInGroup = 0; 8983 for (unsigned i = 0, e = Group.size(); i != e; ++i) 8984 if (Decl *D = Group[i]) { 8985 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 8986 if (!FirstDeclaratorInGroup) 8987 FirstDeclaratorInGroup = DD; 8988 Decls.push_back(D); 8989 } 8990 8991 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 8992 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 8993 HandleTagNumbering(*this, Tag, S); 8994 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 8995 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 8996 } 8997 } 8998 8999 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9000 } 9001 9002 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9003 /// group, performing any necessary semantic checking. 9004 Sema::DeclGroupPtrTy 9005 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 9006 bool TypeMayContainAuto) { 9007 // C++0x [dcl.spec.auto]p7: 9008 // If the type deduced for the template parameter U is not the same in each 9009 // deduction, the program is ill-formed. 9010 // FIXME: When initializer-list support is added, a distinction is needed 9011 // between the deduced type U and the deduced type which 'auto' stands for. 9012 // auto a = 0, b = { 1, 2, 3 }; 9013 // is legal because the deduced type U is 'int' in both cases. 9014 if (TypeMayContainAuto && Group.size() > 1) { 9015 QualType Deduced; 9016 CanQualType DeducedCanon; 9017 VarDecl *DeducedDecl = 0; 9018 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9019 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9020 AutoType *AT = D->getType()->getContainedAutoType(); 9021 // Don't reissue diagnostics when instantiating a template. 9022 if (AT && D->isInvalidDecl()) 9023 break; 9024 QualType U = AT ? AT->getDeducedType() : QualType(); 9025 if (!U.isNull()) { 9026 CanQualType UCanon = Context.getCanonicalType(U); 9027 if (Deduced.isNull()) { 9028 Deduced = U; 9029 DeducedCanon = UCanon; 9030 DeducedDecl = D; 9031 } else if (DeducedCanon != UCanon) { 9032 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9033 diag::err_auto_different_deductions) 9034 << (AT->isDecltypeAuto() ? 1 : 0) 9035 << Deduced << DeducedDecl->getDeclName() 9036 << U << D->getDeclName() 9037 << DeducedDecl->getInit()->getSourceRange() 9038 << D->getInit()->getSourceRange(); 9039 D->setInvalidDecl(); 9040 break; 9041 } 9042 } 9043 } 9044 } 9045 } 9046 9047 ActOnDocumentableDecls(Group); 9048 9049 return DeclGroupPtrTy::make( 9050 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9051 } 9052 9053 void Sema::ActOnDocumentableDecl(Decl *D) { 9054 ActOnDocumentableDecls(D); 9055 } 9056 9057 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9058 // Don't parse the comment if Doxygen diagnostics are ignored. 9059 if (Group.empty() || !Group[0]) 9060 return; 9061 9062 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9063 Group[0]->getLocation()) 9064 == DiagnosticsEngine::Ignored) 9065 return; 9066 9067 if (Group.size() >= 2) { 9068 // This is a decl group. Normally it will contain only declarations 9069 // produced from declarator list. But in case we have any definitions or 9070 // additional declaration references: 9071 // 'typedef struct S {} S;' 9072 // 'typedef struct S *S;' 9073 // 'struct S *pS;' 9074 // FinalizeDeclaratorGroup adds these as separate declarations. 9075 Decl *MaybeTagDecl = Group[0]; 9076 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9077 Group = Group.slice(1); 9078 } 9079 } 9080 9081 // See if there are any new comments that are not attached to a decl. 9082 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9083 if (!Comments.empty() && 9084 !Comments.back()->isAttached()) { 9085 // There is at least one comment that not attached to a decl. 9086 // Maybe it should be attached to one of these decls? 9087 // 9088 // Note that this way we pick up not only comments that precede the 9089 // declaration, but also comments that *follow* the declaration -- thanks to 9090 // the lookahead in the lexer: we've consumed the semicolon and looked 9091 // ahead through comments. 9092 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9093 Context.getCommentForDecl(Group[i], &PP); 9094 } 9095 } 9096 9097 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9098 /// to introduce parameters into function prototype scope. 9099 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9100 const DeclSpec &DS = D.getDeclSpec(); 9101 9102 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9103 9104 // C++03 [dcl.stc]p2 also permits 'auto'. 9105 VarDecl::StorageClass StorageClass = SC_None; 9106 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9107 StorageClass = SC_Register; 9108 } else if (getLangOpts().CPlusPlus && 9109 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9110 StorageClass = SC_Auto; 9111 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9112 Diag(DS.getStorageClassSpecLoc(), 9113 diag::err_invalid_storage_class_in_func_decl); 9114 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9115 } 9116 9117 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9118 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9119 << DeclSpec::getSpecifierName(TSCS); 9120 if (DS.isConstexprSpecified()) 9121 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9122 << 0; 9123 9124 DiagnoseFunctionSpecifiers(DS); 9125 9126 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9127 QualType parmDeclType = TInfo->getType(); 9128 9129 if (getLangOpts().CPlusPlus) { 9130 // Check that there are no default arguments inside the type of this 9131 // parameter. 9132 CheckExtraCXXDefaultArguments(D); 9133 9134 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9135 if (D.getCXXScopeSpec().isSet()) { 9136 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9137 << D.getCXXScopeSpec().getRange(); 9138 D.getCXXScopeSpec().clear(); 9139 } 9140 } 9141 9142 // Ensure we have a valid name 9143 IdentifierInfo *II = 0; 9144 if (D.hasName()) { 9145 II = D.getIdentifier(); 9146 if (!II) { 9147 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9148 << GetNameForDeclarator(D).getName(); 9149 D.setInvalidType(true); 9150 } 9151 } 9152 9153 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9154 if (II) { 9155 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9156 ForRedeclaration); 9157 LookupName(R, S); 9158 if (R.isSingleResult()) { 9159 NamedDecl *PrevDecl = R.getFoundDecl(); 9160 if (PrevDecl->isTemplateParameter()) { 9161 // Maybe we will complain about the shadowed template parameter. 9162 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9163 // Just pretend that we didn't see the previous declaration. 9164 PrevDecl = 0; 9165 } else if (S->isDeclScope(PrevDecl)) { 9166 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9167 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9168 9169 // Recover by removing the name 9170 II = 0; 9171 D.SetIdentifier(0, D.getIdentifierLoc()); 9172 D.setInvalidType(true); 9173 } 9174 } 9175 } 9176 9177 // Temporarily put parameter variables in the translation unit, not 9178 // the enclosing context. This prevents them from accidentally 9179 // looking like class members in C++. 9180 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9181 D.getLocStart(), 9182 D.getIdentifierLoc(), II, 9183 parmDeclType, TInfo, 9184 StorageClass); 9185 9186 if (D.isInvalidType()) 9187 New->setInvalidDecl(); 9188 9189 assert(S->isFunctionPrototypeScope()); 9190 assert(S->getFunctionPrototypeDepth() >= 1); 9191 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9192 S->getNextFunctionPrototypeIndex()); 9193 9194 // Add the parameter declaration into this scope. 9195 S->AddDecl(New); 9196 if (II) 9197 IdResolver.AddDecl(New); 9198 9199 ProcessDeclAttributes(S, New, D); 9200 9201 if (D.getDeclSpec().isModulePrivateSpecified()) 9202 Diag(New->getLocation(), diag::err_module_private_local) 9203 << 1 << New->getDeclName() 9204 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9205 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9206 9207 if (New->hasAttr<BlocksAttr>()) { 9208 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9209 } 9210 return New; 9211 } 9212 9213 /// \brief Synthesizes a variable for a parameter arising from a 9214 /// typedef. 9215 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9216 SourceLocation Loc, 9217 QualType T) { 9218 /* FIXME: setting StartLoc == Loc. 9219 Would it be worth to modify callers so as to provide proper source 9220 location for the unnamed parameters, embedding the parameter's type? */ 9221 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9222 T, Context.getTrivialTypeSourceInfo(T, Loc), 9223 SC_None, 0); 9224 Param->setImplicit(); 9225 return Param; 9226 } 9227 9228 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9229 ParmVarDecl * const *ParamEnd) { 9230 // Don't diagnose unused-parameter errors in template instantiations; we 9231 // will already have done so in the template itself. 9232 if (!ActiveTemplateInstantiations.empty()) 9233 return; 9234 9235 for (; Param != ParamEnd; ++Param) { 9236 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9237 !(*Param)->hasAttr<UnusedAttr>()) { 9238 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9239 << (*Param)->getDeclName(); 9240 } 9241 } 9242 } 9243 9244 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9245 ParmVarDecl * const *ParamEnd, 9246 QualType ReturnTy, 9247 NamedDecl *D) { 9248 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9249 return; 9250 9251 // Warn if the return value is pass-by-value and larger than the specified 9252 // threshold. 9253 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9254 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9255 if (Size > LangOpts.NumLargeByValueCopy) 9256 Diag(D->getLocation(), diag::warn_return_value_size) 9257 << D->getDeclName() << Size; 9258 } 9259 9260 // Warn if any parameter is pass-by-value and larger than the specified 9261 // threshold. 9262 for (; Param != ParamEnd; ++Param) { 9263 QualType T = (*Param)->getType(); 9264 if (T->isDependentType() || !T.isPODType(Context)) 9265 continue; 9266 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9267 if (Size > LangOpts.NumLargeByValueCopy) 9268 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9269 << (*Param)->getDeclName() << Size; 9270 } 9271 } 9272 9273 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9274 SourceLocation NameLoc, IdentifierInfo *Name, 9275 QualType T, TypeSourceInfo *TSInfo, 9276 VarDecl::StorageClass StorageClass) { 9277 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9278 if (getLangOpts().ObjCAutoRefCount && 9279 T.getObjCLifetime() == Qualifiers::OCL_None && 9280 T->isObjCLifetimeType()) { 9281 9282 Qualifiers::ObjCLifetime lifetime; 9283 9284 // Special cases for arrays: 9285 // - if it's const, use __unsafe_unretained 9286 // - otherwise, it's an error 9287 if (T->isArrayType()) { 9288 if (!T.isConstQualified()) { 9289 DelayedDiagnostics.add( 9290 sema::DelayedDiagnostic::makeForbiddenType( 9291 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9292 } 9293 lifetime = Qualifiers::OCL_ExplicitNone; 9294 } else { 9295 lifetime = T->getObjCARCImplicitLifetime(); 9296 } 9297 T = Context.getLifetimeQualifiedType(T, lifetime); 9298 } 9299 9300 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9301 Context.getAdjustedParameterType(T), 9302 TSInfo, 9303 StorageClass, 0); 9304 9305 // Parameters can not be abstract class types. 9306 // For record types, this is done by the AbstractClassUsageDiagnoser once 9307 // the class has been completely parsed. 9308 if (!CurContext->isRecord() && 9309 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9310 AbstractParamType)) 9311 New->setInvalidDecl(); 9312 9313 // Parameter declarators cannot be interface types. All ObjC objects are 9314 // passed by reference. 9315 if (T->isObjCObjectType()) { 9316 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9317 Diag(NameLoc, 9318 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9319 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9320 T = Context.getObjCObjectPointerType(T); 9321 New->setType(T); 9322 } 9323 9324 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9325 // duration shall not be qualified by an address-space qualifier." 9326 // Since all parameters have automatic store duration, they can not have 9327 // an address space. 9328 if (T.getAddressSpace() != 0) { 9329 Diag(NameLoc, diag::err_arg_with_address_space); 9330 New->setInvalidDecl(); 9331 } 9332 9333 return New; 9334 } 9335 9336 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9337 SourceLocation LocAfterDecls) { 9338 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9339 9340 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9341 // for a K&R function. 9342 if (!FTI.hasPrototype) { 9343 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 9344 --i; 9345 if (FTI.Params[i].Param == 0) { 9346 SmallString<256> Code; 9347 llvm::raw_svector_ostream(Code) 9348 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 9349 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 9350 << FTI.Params[i].Ident 9351 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9352 9353 // Implicitly declare the argument as type 'int' for lack of a better 9354 // type. 9355 AttributeFactory attrs; 9356 DeclSpec DS(attrs); 9357 const char* PrevSpec; // unused 9358 unsigned DiagID; // unused 9359 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 9360 DiagID, Context.getPrintingPolicy()); 9361 // Use the identifier location for the type source range. 9362 DS.SetRangeStart(FTI.Params[i].IdentLoc); 9363 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 9364 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9365 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 9366 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 9367 } 9368 } 9369 } 9370 } 9371 9372 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9373 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9374 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9375 Scope *ParentScope = FnBodyScope->getParent(); 9376 9377 D.setFunctionDefinitionKind(FDK_Definition); 9378 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9379 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9380 } 9381 9382 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9383 const FunctionDecl*& PossibleZeroParamPrototype) { 9384 // Don't warn about invalid declarations. 9385 if (FD->isInvalidDecl()) 9386 return false; 9387 9388 // Or declarations that aren't global. 9389 if (!FD->isGlobal()) 9390 return false; 9391 9392 // Don't warn about C++ member functions. 9393 if (isa<CXXMethodDecl>(FD)) 9394 return false; 9395 9396 // Don't warn about 'main'. 9397 if (FD->isMain()) 9398 return false; 9399 9400 // Don't warn about inline functions. 9401 if (FD->isInlined()) 9402 return false; 9403 9404 // Don't warn about function templates. 9405 if (FD->getDescribedFunctionTemplate()) 9406 return false; 9407 9408 // Don't warn about function template specializations. 9409 if (FD->isFunctionTemplateSpecialization()) 9410 return false; 9411 9412 // Don't warn for OpenCL kernels. 9413 if (FD->hasAttr<OpenCLKernelAttr>()) 9414 return false; 9415 9416 bool MissingPrototype = true; 9417 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9418 Prev; Prev = Prev->getPreviousDecl()) { 9419 // Ignore any declarations that occur in function or method 9420 // scope, because they aren't visible from the header. 9421 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9422 continue; 9423 9424 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9425 if (FD->getNumParams() == 0) 9426 PossibleZeroParamPrototype = Prev; 9427 break; 9428 } 9429 9430 return MissingPrototype; 9431 } 9432 9433 void 9434 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9435 const FunctionDecl *EffectiveDefinition) { 9436 // Don't complain if we're in GNU89 mode and the previous definition 9437 // was an extern inline function. 9438 const FunctionDecl *Definition = EffectiveDefinition; 9439 if (!Definition) 9440 if (!FD->isDefined(Definition)) 9441 return; 9442 9443 if (canRedefineFunction(Definition, getLangOpts())) 9444 return; 9445 9446 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9447 Definition->getStorageClass() == SC_Extern) 9448 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9449 << FD->getDeclName() << getLangOpts().CPlusPlus; 9450 else 9451 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9452 9453 Diag(Definition->getLocation(), diag::note_previous_definition); 9454 FD->setInvalidDecl(); 9455 } 9456 9457 9458 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9459 Sema &S) { 9460 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9461 9462 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9463 LSI->CallOperator = CallOperator; 9464 LSI->Lambda = LambdaClass; 9465 LSI->ReturnType = CallOperator->getReturnType(); 9466 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9467 9468 if (LCD == LCD_None) 9469 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9470 else if (LCD == LCD_ByCopy) 9471 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9472 else if (LCD == LCD_ByRef) 9473 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9474 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9475 9476 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9477 LSI->Mutable = !CallOperator->isConst(); 9478 9479 // Add the captures to the LSI so they can be noted as already 9480 // captured within tryCaptureVar. 9481 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(), 9482 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) { 9483 if (C->capturesVariable()) { 9484 VarDecl *VD = C->getCapturedVar(); 9485 if (VD->isInitCapture()) 9486 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9487 QualType CaptureType = VD->getType(); 9488 const bool ByRef = C->getCaptureKind() == LCK_ByRef; 9489 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9490 /*RefersToEnclosingLocal*/true, C->getLocation(), 9491 /*EllipsisLoc*/C->isPackExpansion() 9492 ? C->getEllipsisLoc() : SourceLocation(), 9493 CaptureType, /*Expr*/ 0); 9494 9495 } else if (C->capturesThis()) { 9496 LSI->addThisCapture(/*Nested*/ false, C->getLocation(), 9497 S.getCurrentThisType(), /*Expr*/ 0); 9498 } 9499 } 9500 } 9501 9502 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9503 // Clear the last template instantiation error context. 9504 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9505 9506 if (!D) 9507 return D; 9508 FunctionDecl *FD = 0; 9509 9510 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9511 FD = FunTmpl->getTemplatedDecl(); 9512 else 9513 FD = cast<FunctionDecl>(D); 9514 // If we are instantiating a generic lambda call operator, push 9515 // a LambdaScopeInfo onto the function stack. But use the information 9516 // that's already been calculated (ActOnLambdaExpr) to prime the current 9517 // LambdaScopeInfo. 9518 // When the template operator is being specialized, the LambdaScopeInfo, 9519 // has to be properly restored so that tryCaptureVariable doesn't try 9520 // and capture any new variables. In addition when calculating potential 9521 // captures during transformation of nested lambdas, it is necessary to 9522 // have the LSI properly restored. 9523 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9524 assert(ActiveTemplateInstantiations.size() && 9525 "There should be an active template instantiation on the stack " 9526 "when instantiating a generic lambda!"); 9527 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9528 } 9529 else 9530 // Enter a new function scope 9531 PushFunctionScope(); 9532 9533 // See if this is a redefinition. 9534 if (!FD->isLateTemplateParsed()) 9535 CheckForFunctionRedefinition(FD); 9536 9537 // Builtin functions cannot be defined. 9538 if (unsigned BuiltinID = FD->getBuiltinID()) { 9539 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9540 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9541 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9542 FD->setInvalidDecl(); 9543 } 9544 } 9545 9546 // The return type of a function definition must be complete 9547 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9548 QualType ResultType = FD->getReturnType(); 9549 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9550 !FD->isInvalidDecl() && 9551 RequireCompleteType(FD->getLocation(), ResultType, 9552 diag::err_func_def_incomplete_result)) 9553 FD->setInvalidDecl(); 9554 9555 // GNU warning -Wmissing-prototypes: 9556 // Warn if a global function is defined without a previous 9557 // prototype declaration. This warning is issued even if the 9558 // definition itself provides a prototype. The aim is to detect 9559 // global functions that fail to be declared in header files. 9560 const FunctionDecl *PossibleZeroParamPrototype = 0; 9561 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9562 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9563 9564 if (PossibleZeroParamPrototype) { 9565 // We found a declaration that is not a prototype, 9566 // but that could be a zero-parameter prototype 9567 if (TypeSourceInfo *TI = 9568 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9569 TypeLoc TL = TI->getTypeLoc(); 9570 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9571 Diag(PossibleZeroParamPrototype->getLocation(), 9572 diag::note_declaration_not_a_prototype) 9573 << PossibleZeroParamPrototype 9574 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9575 } 9576 } 9577 } 9578 9579 if (FnBodyScope) 9580 PushDeclContext(FnBodyScope, FD); 9581 9582 // Check the validity of our function parameters 9583 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9584 /*CheckParameterNames=*/true); 9585 9586 // Introduce our parameters into the function scope 9587 for (auto Param : FD->params()) { 9588 Param->setOwningFunction(FD); 9589 9590 // If this has an identifier, add it to the scope stack. 9591 if (Param->getIdentifier() && FnBodyScope) { 9592 CheckShadow(FnBodyScope, Param); 9593 9594 PushOnScopeChains(Param, FnBodyScope); 9595 } 9596 } 9597 9598 // If we had any tags defined in the function prototype, 9599 // introduce them into the function scope. 9600 if (FnBodyScope) { 9601 for (ArrayRef<NamedDecl *>::iterator 9602 I = FD->getDeclsInPrototypeScope().begin(), 9603 E = FD->getDeclsInPrototypeScope().end(); 9604 I != E; ++I) { 9605 NamedDecl *D = *I; 9606 9607 // Some of these decls (like enums) may have been pinned to the translation unit 9608 // for lack of a real context earlier. If so, remove from the translation unit 9609 // and reattach to the current context. 9610 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9611 // Is the decl actually in the context? 9612 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 9613 if (DI == D) { 9614 Context.getTranslationUnitDecl()->removeDecl(D); 9615 break; 9616 } 9617 } 9618 // Either way, reassign the lexical decl context to our FunctionDecl. 9619 D->setLexicalDeclContext(CurContext); 9620 } 9621 9622 // If the decl has a non-null name, make accessible in the current scope. 9623 if (!D->getName().empty()) 9624 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9625 9626 // Similarly, dive into enums and fish their constants out, making them 9627 // accessible in this scope. 9628 if (auto *ED = dyn_cast<EnumDecl>(D)) { 9629 for (auto *EI : ED->enumerators()) 9630 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 9631 } 9632 } 9633 } 9634 9635 // Ensure that the function's exception specification is instantiated. 9636 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9637 ResolveExceptionSpec(D->getLocation(), FPT); 9638 9639 // Checking attributes of current function definition 9640 // dllimport attribute. 9641 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9642 if (DA && (!FD->hasAttr<DLLExportAttr>())) { 9643 // dllimport attribute cannot be directly applied to definition. 9644 // Microsoft accepts dllimport for functions defined within class scope. 9645 if (!DA->isInherited() && 9646 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9647 Diag(FD->getLocation(), 9648 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9649 << DA; 9650 FD->setInvalidDecl(); 9651 return D; 9652 } 9653 9654 // Visual C++ appears to not think this is an issue, so only issue 9655 // a warning when Microsoft extensions are disabled. 9656 if (!LangOpts.MicrosoftExt) { 9657 // If a symbol previously declared dllimport is later defined, the 9658 // attribute is ignored in subsequent references, and a warning is 9659 // emitted. 9660 Diag(FD->getLocation(), 9661 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 9662 << FD << DA; 9663 } 9664 } 9665 // We want to attach documentation to original Decl (which might be 9666 // a function template). 9667 ActOnDocumentableDecl(D); 9668 return D; 9669 } 9670 9671 /// \brief Given the set of return statements within a function body, 9672 /// compute the variables that are subject to the named return value 9673 /// optimization. 9674 /// 9675 /// Each of the variables that is subject to the named return value 9676 /// optimization will be marked as NRVO variables in the AST, and any 9677 /// return statement that has a marked NRVO variable as its NRVO candidate can 9678 /// use the named return value optimization. 9679 /// 9680 /// This function applies a very simplistic algorithm for NRVO: if every return 9681 /// statement in the function has the same NRVO candidate, that candidate is 9682 /// the NRVO variable. 9683 /// 9684 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9685 /// statements and the lifetimes of the NRVO candidates. We should be able to 9686 /// find a maximal set of NRVO variables. 9687 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9688 ReturnStmt **Returns = Scope->Returns.data(); 9689 9690 const VarDecl *NRVOCandidate = 0; 9691 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9692 if (!Returns[I]->getNRVOCandidate()) 9693 return; 9694 9695 if (!NRVOCandidate) 9696 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9697 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9698 return; 9699 } 9700 9701 if (NRVOCandidate) 9702 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9703 } 9704 9705 bool Sema::canSkipFunctionBody(Decl *D) { 9706 // We cannot skip the body of a function (or function template) which is 9707 // constexpr, since we may need to evaluate its body in order to parse the 9708 // rest of the file. 9709 // We cannot skip the body of a function with an undeduced return type, 9710 // because any callers of that function need to know the type. 9711 if (const FunctionDecl *FD = D->getAsFunction()) 9712 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9713 return false; 9714 return Consumer.shouldSkipFunctionBody(D); 9715 } 9716 9717 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9718 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9719 FD->setHasSkippedBody(); 9720 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9721 MD->setHasSkippedBody(); 9722 return ActOnFinishFunctionBody(Decl, 0); 9723 } 9724 9725 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9726 return ActOnFinishFunctionBody(D, BodyArg, false); 9727 } 9728 9729 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9730 bool IsInstantiation) { 9731 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0; 9732 9733 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9734 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9735 9736 if (FD) { 9737 FD->setBody(Body); 9738 9739 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9740 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 9741 // If the function has a deduced result type but contains no 'return' 9742 // statements, the result type as written must be exactly 'auto', and 9743 // the deduced result type is 'void'. 9744 if (!FD->getReturnType()->getAs<AutoType>()) { 9745 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9746 << FD->getReturnType(); 9747 FD->setInvalidDecl(); 9748 } else { 9749 // Substitute 'void' for the 'auto' in the type. 9750 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9751 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 9752 Context.adjustDeducedFunctionResultType( 9753 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9754 } 9755 } 9756 9757 // The only way to be included in UndefinedButUsed is if there is an 9758 // ODR use before the definition. Avoid the expensive map lookup if this 9759 // is the first declaration. 9760 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9761 if (!FD->isExternallyVisible()) 9762 UndefinedButUsed.erase(FD); 9763 else if (FD->isInlined() && 9764 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9765 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9766 UndefinedButUsed.erase(FD); 9767 } 9768 9769 // If the function implicitly returns zero (like 'main') or is naked, 9770 // don't complain about missing return statements. 9771 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9772 WP.disableCheckFallThrough(); 9773 9774 // MSVC permits the use of pure specifier (=0) on function definition, 9775 // defined at class scope, warn about this non-standard construct. 9776 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9777 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9778 9779 if (!FD->isInvalidDecl()) { 9780 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9781 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9782 FD->getReturnType(), FD); 9783 9784 // If this is a constructor, we need a vtable. 9785 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9786 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9787 9788 // Try to apply the named return value optimization. We have to check 9789 // if we can do this here because lambdas keep return statements around 9790 // to deduce an implicit return type. 9791 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 9792 !FD->isDependentContext()) 9793 computeNRVO(Body, getCurFunction()); 9794 } 9795 9796 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9797 "Function parsing confused"); 9798 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9799 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9800 MD->setBody(Body); 9801 if (!MD->isInvalidDecl()) { 9802 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9803 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9804 MD->getReturnType(), MD); 9805 9806 if (Body) 9807 computeNRVO(Body, getCurFunction()); 9808 } 9809 if (getCurFunction()->ObjCShouldCallSuper) { 9810 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9811 << MD->getSelector().getAsString(); 9812 getCurFunction()->ObjCShouldCallSuper = false; 9813 } 9814 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 9815 const ObjCMethodDecl *InitMethod = 0; 9816 bool isDesignated = 9817 MD->isDesignatedInitializerForTheInterface(&InitMethod); 9818 assert(isDesignated && InitMethod); 9819 (void)isDesignated; 9820 Diag(MD->getLocation(), 9821 diag::warn_objc_designated_init_missing_super_call); 9822 Diag(InitMethod->getLocation(), 9823 diag::note_objc_designated_init_marked_here); 9824 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 9825 } 9826 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 9827 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 9828 getCurFunction()->ObjCWarnForNoInitDelegation = false; 9829 } 9830 } else { 9831 return 0; 9832 } 9833 9834 assert(!getCurFunction()->ObjCShouldCallSuper && 9835 "This should only be set for ObjC methods, which should have been " 9836 "handled in the block above."); 9837 9838 // Verify and clean out per-function state. 9839 if (Body) { 9840 // C++ constructors that have function-try-blocks can't have return 9841 // statements in the handlers of that block. (C++ [except.handle]p14) 9842 // Verify this. 9843 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 9844 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 9845 9846 // Verify that gotos and switch cases don't jump into scopes illegally. 9847 if (getCurFunction()->NeedsScopeChecking() && 9848 !dcl->isInvalidDecl() && 9849 !hasAnyUnrecoverableErrorsInThisFunction() && 9850 !PP.isCodeCompletionEnabled()) 9851 DiagnoseInvalidJumps(Body); 9852 9853 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 9854 if (!Destructor->getParent()->isDependentType()) 9855 CheckDestructor(Destructor); 9856 9857 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9858 Destructor->getParent()); 9859 } 9860 9861 // If any errors have occurred, clear out any temporaries that may have 9862 // been leftover. This ensures that these temporaries won't be picked up for 9863 // deletion in some later function. 9864 if (PP.getDiagnostics().hasErrorOccurred() || 9865 PP.getDiagnostics().getSuppressAllDiagnostics()) { 9866 DiscardCleanupsInEvaluationContext(); 9867 } 9868 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 9869 !isa<FunctionTemplateDecl>(dcl)) { 9870 // Since the body is valid, issue any analysis-based warnings that are 9871 // enabled. 9872 ActivePolicy = &WP; 9873 } 9874 9875 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 9876 (!CheckConstexprFunctionDecl(FD) || 9877 !CheckConstexprFunctionBody(FD, Body))) 9878 FD->setInvalidDecl(); 9879 9880 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 9881 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 9882 assert(MaybeODRUseExprs.empty() && 9883 "Leftover expressions for odr-use checking"); 9884 } 9885 9886 if (!IsInstantiation) 9887 PopDeclContext(); 9888 9889 PopFunctionScopeInfo(ActivePolicy, dcl); 9890 // If any errors have occurred, clear out any temporaries that may have 9891 // been leftover. This ensures that these temporaries won't be picked up for 9892 // deletion in some later function. 9893 if (getDiagnostics().hasErrorOccurred()) { 9894 DiscardCleanupsInEvaluationContext(); 9895 } 9896 9897 return dcl; 9898 } 9899 9900 9901 /// When we finish delayed parsing of an attribute, we must attach it to the 9902 /// relevant Decl. 9903 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 9904 ParsedAttributes &Attrs) { 9905 // Always attach attributes to the underlying decl. 9906 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9907 D = TD->getTemplatedDecl(); 9908 ProcessDeclAttributeList(S, D, Attrs.getList()); 9909 9910 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 9911 if (Method->isStatic()) 9912 checkThisInStaticMemberFunctionAttributes(Method); 9913 } 9914 9915 9916 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 9917 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 9918 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 9919 IdentifierInfo &II, Scope *S) { 9920 // Before we produce a declaration for an implicitly defined 9921 // function, see whether there was a locally-scoped declaration of 9922 // this name as a function or variable. If so, use that 9923 // (non-visible) declaration, and complain about it. 9924 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 9925 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 9926 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 9927 return ExternCPrev; 9928 } 9929 9930 // Extension in C99. Legal in C90, but warn about it. 9931 unsigned diag_id; 9932 if (II.getName().startswith("__builtin_")) 9933 diag_id = diag::warn_builtin_unknown; 9934 else if (getLangOpts().C99) 9935 diag_id = diag::ext_implicit_function_decl; 9936 else 9937 diag_id = diag::warn_implicit_function_decl; 9938 Diag(Loc, diag_id) << &II; 9939 9940 // Because typo correction is expensive, only do it if the implicit 9941 // function declaration is going to be treated as an error. 9942 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 9943 TypoCorrection Corrected; 9944 DeclFilterCCC<FunctionDecl> Validator; 9945 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 9946 LookupOrdinaryName, S, 0, Validator))) 9947 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 9948 /*ErrorRecovery*/false); 9949 } 9950 9951 // Set a Declarator for the implicit definition: int foo(); 9952 const char *Dummy; 9953 AttributeFactory attrFactory; 9954 DeclSpec DS(attrFactory); 9955 unsigned DiagID; 9956 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 9957 Context.getPrintingPolicy()); 9958 (void)Error; // Silence warning. 9959 assert(!Error && "Error setting up implicit decl!"); 9960 SourceLocation NoLoc; 9961 Declarator D(DS, Declarator::BlockContext); 9962 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 9963 /*IsAmbiguous=*/false, 9964 /*RParenLoc=*/NoLoc, 9965 /*ArgInfo=*/0, 9966 /*NumArgs=*/0, 9967 /*EllipsisLoc=*/NoLoc, 9968 /*RParenLoc=*/NoLoc, 9969 /*TypeQuals=*/0, 9970 /*RefQualifierIsLvalueRef=*/true, 9971 /*RefQualifierLoc=*/NoLoc, 9972 /*ConstQualifierLoc=*/NoLoc, 9973 /*VolatileQualifierLoc=*/NoLoc, 9974 /*MutableLoc=*/NoLoc, 9975 EST_None, 9976 /*ESpecLoc=*/NoLoc, 9977 /*Exceptions=*/0, 9978 /*ExceptionRanges=*/0, 9979 /*NumExceptions=*/0, 9980 /*NoexceptExpr=*/0, 9981 Loc, Loc, D), 9982 DS.getAttributes(), 9983 SourceLocation()); 9984 D.SetIdentifier(&II, Loc); 9985 9986 // Insert this function into translation-unit scope. 9987 9988 DeclContext *PrevDC = CurContext; 9989 CurContext = Context.getTranslationUnitDecl(); 9990 9991 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 9992 FD->setImplicit(); 9993 9994 CurContext = PrevDC; 9995 9996 AddKnownFunctionAttributes(FD); 9997 9998 return FD; 9999 } 10000 10001 /// \brief Adds any function attributes that we know a priori based on 10002 /// the declaration of this function. 10003 /// 10004 /// These attributes can apply both to implicitly-declared builtins 10005 /// (like __builtin___printf_chk) or to library-declared functions 10006 /// like NSLog or printf. 10007 /// 10008 /// We need to check for duplicate attributes both here and where user-written 10009 /// attributes are applied to declarations. 10010 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10011 if (FD->isInvalidDecl()) 10012 return; 10013 10014 // If this is a built-in function, map its builtin attributes to 10015 // actual attributes. 10016 if (unsigned BuiltinID = FD->getBuiltinID()) { 10017 // Handle printf-formatting attributes. 10018 unsigned FormatIdx; 10019 bool HasVAListArg; 10020 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10021 if (!FD->hasAttr<FormatAttr>()) { 10022 const char *fmt = "printf"; 10023 unsigned int NumParams = FD->getNumParams(); 10024 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10025 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10026 fmt = "NSString"; 10027 FD->addAttr(FormatAttr::CreateImplicit(Context, 10028 &Context.Idents.get(fmt), 10029 FormatIdx+1, 10030 HasVAListArg ? 0 : FormatIdx+2, 10031 FD->getLocation())); 10032 } 10033 } 10034 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10035 HasVAListArg)) { 10036 if (!FD->hasAttr<FormatAttr>()) 10037 FD->addAttr(FormatAttr::CreateImplicit(Context, 10038 &Context.Idents.get("scanf"), 10039 FormatIdx+1, 10040 HasVAListArg ? 0 : FormatIdx+2, 10041 FD->getLocation())); 10042 } 10043 10044 // Mark const if we don't care about errno and that is the only 10045 // thing preventing the function from being const. This allows 10046 // IRgen to use LLVM intrinsics for such functions. 10047 if (!getLangOpts().MathErrno && 10048 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10049 if (!FD->hasAttr<ConstAttr>()) 10050 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10051 } 10052 10053 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10054 !FD->hasAttr<ReturnsTwiceAttr>()) 10055 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10056 FD->getLocation())); 10057 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10058 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10059 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10060 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10061 } 10062 10063 IdentifierInfo *Name = FD->getIdentifier(); 10064 if (!Name) 10065 return; 10066 if ((!getLangOpts().CPlusPlus && 10067 FD->getDeclContext()->isTranslationUnit()) || 10068 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10069 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10070 LinkageSpecDecl::lang_c)) { 10071 // Okay: this could be a libc/libm/Objective-C function we know 10072 // about. 10073 } else 10074 return; 10075 10076 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10077 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10078 // target-specific builtins, perhaps? 10079 if (!FD->hasAttr<FormatAttr>()) 10080 FD->addAttr(FormatAttr::CreateImplicit(Context, 10081 &Context.Idents.get("printf"), 2, 10082 Name->isStr("vasprintf") ? 0 : 3, 10083 FD->getLocation())); 10084 } 10085 10086 if (Name->isStr("__CFStringMakeConstantString")) { 10087 // We already have a __builtin___CFStringMakeConstantString, 10088 // but builds that use -fno-constant-cfstrings don't go through that. 10089 if (!FD->hasAttr<FormatArgAttr>()) 10090 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10091 FD->getLocation())); 10092 } 10093 } 10094 10095 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10096 TypeSourceInfo *TInfo) { 10097 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10098 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10099 10100 if (!TInfo) { 10101 assert(D.isInvalidType() && "no declarator info for valid type"); 10102 TInfo = Context.getTrivialTypeSourceInfo(T); 10103 } 10104 10105 // Scope manipulation handled by caller. 10106 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10107 D.getLocStart(), 10108 D.getIdentifierLoc(), 10109 D.getIdentifier(), 10110 TInfo); 10111 10112 // Bail out immediately if we have an invalid declaration. 10113 if (D.isInvalidType()) { 10114 NewTD->setInvalidDecl(); 10115 return NewTD; 10116 } 10117 10118 if (D.getDeclSpec().isModulePrivateSpecified()) { 10119 if (CurContext->isFunctionOrMethod()) 10120 Diag(NewTD->getLocation(), diag::err_module_private_local) 10121 << 2 << NewTD->getDeclName() 10122 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10123 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10124 else 10125 NewTD->setModulePrivate(); 10126 } 10127 10128 // C++ [dcl.typedef]p8: 10129 // If the typedef declaration defines an unnamed class (or 10130 // enum), the first typedef-name declared by the declaration 10131 // to be that class type (or enum type) is used to denote the 10132 // class type (or enum type) for linkage purposes only. 10133 // We need to check whether the type was declared in the declaration. 10134 switch (D.getDeclSpec().getTypeSpecType()) { 10135 case TST_enum: 10136 case TST_struct: 10137 case TST_interface: 10138 case TST_union: 10139 case TST_class: { 10140 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10141 10142 // Do nothing if the tag is not anonymous or already has an 10143 // associated typedef (from an earlier typedef in this decl group). 10144 if (tagFromDeclSpec->getIdentifier()) break; 10145 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10146 10147 // A well-formed anonymous tag must always be a TUK_Definition. 10148 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10149 10150 // The type must match the tag exactly; no qualifiers allowed. 10151 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10152 break; 10153 10154 // If we've already computed linkage for the anonymous tag, then 10155 // adding a typedef name for the anonymous decl can change that 10156 // linkage, which might be a serious problem. Diagnose this as 10157 // unsupported and ignore the typedef name. TODO: we should 10158 // pursue this as a language defect and establish a formal rule 10159 // for how to handle it. 10160 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10161 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10162 10163 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10164 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(), 10165 getLangOpts()); 10166 10167 llvm::SmallString<40> textToInsert; 10168 textToInsert += ' '; 10169 textToInsert += D.getIdentifier()->getName(); 10170 Diag(tagLoc, diag::note_typedef_changes_linkage) 10171 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10172 break; 10173 } 10174 10175 // Otherwise, set this is the anon-decl typedef for the tag. 10176 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10177 break; 10178 } 10179 10180 default: 10181 break; 10182 } 10183 10184 return NewTD; 10185 } 10186 10187 10188 /// \brief Check that this is a valid underlying type for an enum declaration. 10189 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10190 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10191 QualType T = TI->getType(); 10192 10193 if (T->isDependentType()) 10194 return false; 10195 10196 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10197 if (BT->isInteger()) 10198 return false; 10199 10200 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10201 return true; 10202 } 10203 10204 /// Check whether this is a valid redeclaration of a previous enumeration. 10205 /// \return true if the redeclaration was invalid. 10206 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10207 QualType EnumUnderlyingTy, 10208 const EnumDecl *Prev) { 10209 bool IsFixed = !EnumUnderlyingTy.isNull(); 10210 10211 if (IsScoped != Prev->isScoped()) { 10212 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10213 << Prev->isScoped(); 10214 Diag(Prev->getLocation(), diag::note_previous_declaration); 10215 return true; 10216 } 10217 10218 if (IsFixed && Prev->isFixed()) { 10219 if (!EnumUnderlyingTy->isDependentType() && 10220 !Prev->getIntegerType()->isDependentType() && 10221 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10222 Prev->getIntegerType())) { 10223 // TODO: Highlight the underlying type of the redeclaration. 10224 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10225 << EnumUnderlyingTy << Prev->getIntegerType(); 10226 Diag(Prev->getLocation(), diag::note_previous_declaration) 10227 << Prev->getIntegerTypeRange(); 10228 return true; 10229 } 10230 } else if (IsFixed != Prev->isFixed()) { 10231 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10232 << Prev->isFixed(); 10233 Diag(Prev->getLocation(), diag::note_previous_declaration); 10234 return true; 10235 } 10236 10237 return false; 10238 } 10239 10240 /// \brief Get diagnostic %select index for tag kind for 10241 /// redeclaration diagnostic message. 10242 /// WARNING: Indexes apply to particular diagnostics only! 10243 /// 10244 /// \returns diagnostic %select index. 10245 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10246 switch (Tag) { 10247 case TTK_Struct: return 0; 10248 case TTK_Interface: return 1; 10249 case TTK_Class: return 2; 10250 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10251 } 10252 } 10253 10254 /// \brief Determine if tag kind is a class-key compatible with 10255 /// class for redeclaration (class, struct, or __interface). 10256 /// 10257 /// \returns true iff the tag kind is compatible. 10258 static bool isClassCompatTagKind(TagTypeKind Tag) 10259 { 10260 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10261 } 10262 10263 /// \brief Determine whether a tag with a given kind is acceptable 10264 /// as a redeclaration of the given tag declaration. 10265 /// 10266 /// \returns true if the new tag kind is acceptable, false otherwise. 10267 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10268 TagTypeKind NewTag, bool isDefinition, 10269 SourceLocation NewTagLoc, 10270 const IdentifierInfo &Name) { 10271 // C++ [dcl.type.elab]p3: 10272 // The class-key or enum keyword present in the 10273 // elaborated-type-specifier shall agree in kind with the 10274 // declaration to which the name in the elaborated-type-specifier 10275 // refers. This rule also applies to the form of 10276 // elaborated-type-specifier that declares a class-name or 10277 // friend class since it can be construed as referring to the 10278 // definition of the class. Thus, in any 10279 // elaborated-type-specifier, the enum keyword shall be used to 10280 // refer to an enumeration (7.2), the union class-key shall be 10281 // used to refer to a union (clause 9), and either the class or 10282 // struct class-key shall be used to refer to a class (clause 9) 10283 // declared using the class or struct class-key. 10284 TagTypeKind OldTag = Previous->getTagKind(); 10285 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10286 if (OldTag == NewTag) 10287 return true; 10288 10289 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10290 // Warn about the struct/class tag mismatch. 10291 bool isTemplate = false; 10292 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10293 isTemplate = Record->getDescribedClassTemplate(); 10294 10295 if (!ActiveTemplateInstantiations.empty()) { 10296 // In a template instantiation, do not offer fix-its for tag mismatches 10297 // since they usually mess up the template instead of fixing the problem. 10298 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10299 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10300 << getRedeclDiagFromTagKind(OldTag); 10301 return true; 10302 } 10303 10304 if (isDefinition) { 10305 // On definitions, check previous tags and issue a fix-it for each 10306 // one that doesn't match the current tag. 10307 if (Previous->getDefinition()) { 10308 // Don't suggest fix-its for redefinitions. 10309 return true; 10310 } 10311 10312 bool previousMismatch = false; 10313 for (auto I : Previous->redecls()) { 10314 if (I->getTagKind() != NewTag) { 10315 if (!previousMismatch) { 10316 previousMismatch = true; 10317 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10318 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10319 << getRedeclDiagFromTagKind(I->getTagKind()); 10320 } 10321 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10322 << getRedeclDiagFromTagKind(NewTag) 10323 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10324 TypeWithKeyword::getTagTypeKindName(NewTag)); 10325 } 10326 } 10327 return true; 10328 } 10329 10330 // Check for a previous definition. If current tag and definition 10331 // are same type, do nothing. If no definition, but disagree with 10332 // with previous tag type, give a warning, but no fix-it. 10333 const TagDecl *Redecl = Previous->getDefinition() ? 10334 Previous->getDefinition() : Previous; 10335 if (Redecl->getTagKind() == NewTag) { 10336 return true; 10337 } 10338 10339 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10340 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10341 << getRedeclDiagFromTagKind(OldTag); 10342 Diag(Redecl->getLocation(), diag::note_previous_use); 10343 10344 // If there is a previous definition, suggest a fix-it. 10345 if (Previous->getDefinition()) { 10346 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10347 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10348 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10349 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10350 } 10351 10352 return true; 10353 } 10354 return false; 10355 } 10356 10357 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10358 /// former case, Name will be non-null. In the later case, Name will be null. 10359 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10360 /// reference/declaration/definition of a tag. 10361 /// 10362 /// IsTypeSpecifier is true if this is a type-specifier (or 10363 /// trailing-type-specifier) other than one in an alias-declaration. 10364 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10365 SourceLocation KWLoc, CXXScopeSpec &SS, 10366 IdentifierInfo *Name, SourceLocation NameLoc, 10367 AttributeList *Attr, AccessSpecifier AS, 10368 SourceLocation ModulePrivateLoc, 10369 MultiTemplateParamsArg TemplateParameterLists, 10370 bool &OwnedDecl, bool &IsDependent, 10371 SourceLocation ScopedEnumKWLoc, 10372 bool ScopedEnumUsesClassTag, 10373 TypeResult UnderlyingType, 10374 bool IsTypeSpecifier) { 10375 // If this is not a definition, it must have a name. 10376 IdentifierInfo *OrigName = Name; 10377 assert((Name != 0 || TUK == TUK_Definition) && 10378 "Nameless record must be a definition!"); 10379 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10380 10381 OwnedDecl = false; 10382 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10383 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10384 10385 // FIXME: Check explicit specializations more carefully. 10386 bool isExplicitSpecialization = false; 10387 bool Invalid = false; 10388 10389 // We only need to do this matching if we have template parameters 10390 // or a scope specifier, which also conveniently avoids this work 10391 // for non-C++ cases. 10392 if (TemplateParameterLists.size() > 0 || 10393 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10394 if (TemplateParameterList *TemplateParams = 10395 MatchTemplateParametersToScopeSpecifier( 10396 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10397 isExplicitSpecialization, Invalid)) { 10398 if (Kind == TTK_Enum) { 10399 Diag(KWLoc, diag::err_enum_template); 10400 return 0; 10401 } 10402 10403 if (TemplateParams->size() > 0) { 10404 // This is a declaration or definition of a class template (which may 10405 // be a member of another template). 10406 10407 if (Invalid) 10408 return 0; 10409 10410 OwnedDecl = false; 10411 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10412 SS, Name, NameLoc, Attr, 10413 TemplateParams, AS, 10414 ModulePrivateLoc, 10415 TemplateParameterLists.size()-1, 10416 TemplateParameterLists.data()); 10417 return Result.get(); 10418 } else { 10419 // The "template<>" header is extraneous. 10420 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10421 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10422 isExplicitSpecialization = true; 10423 } 10424 } 10425 } 10426 10427 // Figure out the underlying type if this a enum declaration. We need to do 10428 // this early, because it's needed to detect if this is an incompatible 10429 // redeclaration. 10430 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10431 10432 if (Kind == TTK_Enum) { 10433 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10434 // No underlying type explicitly specified, or we failed to parse the 10435 // type, default to int. 10436 EnumUnderlying = Context.IntTy.getTypePtr(); 10437 else if (UnderlyingType.get()) { 10438 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10439 // integral type; any cv-qualification is ignored. 10440 TypeSourceInfo *TI = 0; 10441 GetTypeFromParser(UnderlyingType.get(), &TI); 10442 EnumUnderlying = TI; 10443 10444 if (CheckEnumUnderlyingType(TI)) 10445 // Recover by falling back to int. 10446 EnumUnderlying = Context.IntTy.getTypePtr(); 10447 10448 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10449 UPPC_FixedUnderlyingType)) 10450 EnumUnderlying = Context.IntTy.getTypePtr(); 10451 10452 } else if (getLangOpts().MSVCCompat) 10453 // Microsoft enums are always of int type. 10454 EnumUnderlying = Context.IntTy.getTypePtr(); 10455 } 10456 10457 DeclContext *SearchDC = CurContext; 10458 DeclContext *DC = CurContext; 10459 bool isStdBadAlloc = false; 10460 10461 RedeclarationKind Redecl = ForRedeclaration; 10462 if (TUK == TUK_Friend || TUK == TUK_Reference) 10463 Redecl = NotForRedeclaration; 10464 10465 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10466 bool FriendSawTagOutsideEnclosingNamespace = false; 10467 if (Name && SS.isNotEmpty()) { 10468 // We have a nested-name tag ('struct foo::bar'). 10469 10470 // Check for invalid 'foo::'. 10471 if (SS.isInvalid()) { 10472 Name = 0; 10473 goto CreateNewDecl; 10474 } 10475 10476 // If this is a friend or a reference to a class in a dependent 10477 // context, don't try to make a decl for it. 10478 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10479 DC = computeDeclContext(SS, false); 10480 if (!DC) { 10481 IsDependent = true; 10482 return 0; 10483 } 10484 } else { 10485 DC = computeDeclContext(SS, true); 10486 if (!DC) { 10487 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10488 << SS.getRange(); 10489 return 0; 10490 } 10491 } 10492 10493 if (RequireCompleteDeclContext(SS, DC)) 10494 return 0; 10495 10496 SearchDC = DC; 10497 // Look-up name inside 'foo::'. 10498 LookupQualifiedName(Previous, DC); 10499 10500 if (Previous.isAmbiguous()) 10501 return 0; 10502 10503 if (Previous.empty()) { 10504 // Name lookup did not find anything. However, if the 10505 // nested-name-specifier refers to the current instantiation, 10506 // and that current instantiation has any dependent base 10507 // classes, we might find something at instantiation time: treat 10508 // this as a dependent elaborated-type-specifier. 10509 // But this only makes any sense for reference-like lookups. 10510 if (Previous.wasNotFoundInCurrentInstantiation() && 10511 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10512 IsDependent = true; 10513 return 0; 10514 } 10515 10516 // A tag 'foo::bar' must already exist. 10517 Diag(NameLoc, diag::err_not_tag_in_scope) 10518 << Kind << Name << DC << SS.getRange(); 10519 Name = 0; 10520 Invalid = true; 10521 goto CreateNewDecl; 10522 } 10523 } else if (Name) { 10524 // If this is a named struct, check to see if there was a previous forward 10525 // declaration or definition. 10526 // FIXME: We're looking into outer scopes here, even when we 10527 // shouldn't be. Doing so can result in ambiguities that we 10528 // shouldn't be diagnosing. 10529 LookupName(Previous, S); 10530 10531 // When declaring or defining a tag, ignore ambiguities introduced 10532 // by types using'ed into this scope. 10533 if (Previous.isAmbiguous() && 10534 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10535 LookupResult::Filter F = Previous.makeFilter(); 10536 while (F.hasNext()) { 10537 NamedDecl *ND = F.next(); 10538 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10539 F.erase(); 10540 } 10541 F.done(); 10542 } 10543 10544 // C++11 [namespace.memdef]p3: 10545 // If the name in a friend declaration is neither qualified nor 10546 // a template-id and the declaration is a function or an 10547 // elaborated-type-specifier, the lookup to determine whether 10548 // the entity has been previously declared shall not consider 10549 // any scopes outside the innermost enclosing namespace. 10550 // 10551 // Does it matter that this should be by scope instead of by 10552 // semantic context? 10553 if (!Previous.empty() && TUK == TUK_Friend) { 10554 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10555 LookupResult::Filter F = Previous.makeFilter(); 10556 while (F.hasNext()) { 10557 NamedDecl *ND = F.next(); 10558 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10559 if (DC->isFileContext() && 10560 !EnclosingNS->Encloses(ND->getDeclContext())) { 10561 F.erase(); 10562 FriendSawTagOutsideEnclosingNamespace = true; 10563 } 10564 } 10565 F.done(); 10566 } 10567 10568 // Note: there used to be some attempt at recovery here. 10569 if (Previous.isAmbiguous()) 10570 return 0; 10571 10572 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10573 // FIXME: This makes sure that we ignore the contexts associated 10574 // with C structs, unions, and enums when looking for a matching 10575 // tag declaration or definition. See the similar lookup tweak 10576 // in Sema::LookupName; is there a better way to deal with this? 10577 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10578 SearchDC = SearchDC->getParent(); 10579 } 10580 } else if (S->isFunctionPrototypeScope()) { 10581 // If this is an enum declaration in function prototype scope, set its 10582 // initial context to the translation unit. 10583 // FIXME: [citation needed] 10584 SearchDC = Context.getTranslationUnitDecl(); 10585 } 10586 10587 if (Previous.isSingleResult() && 10588 Previous.getFoundDecl()->isTemplateParameter()) { 10589 // Maybe we will complain about the shadowed template parameter. 10590 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10591 // Just pretend that we didn't see the previous declaration. 10592 Previous.clear(); 10593 } 10594 10595 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10596 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10597 // This is a declaration of or a reference to "std::bad_alloc". 10598 isStdBadAlloc = true; 10599 10600 if (Previous.empty() && StdBadAlloc) { 10601 // std::bad_alloc has been implicitly declared (but made invisible to 10602 // name lookup). Fill in this implicit declaration as the previous 10603 // declaration, so that the declarations get chained appropriately. 10604 Previous.addDecl(getStdBadAlloc()); 10605 } 10606 } 10607 10608 // If we didn't find a previous declaration, and this is a reference 10609 // (or friend reference), move to the correct scope. In C++, we 10610 // also need to do a redeclaration lookup there, just in case 10611 // there's a shadow friend decl. 10612 if (Name && Previous.empty() && 10613 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10614 if (Invalid) goto CreateNewDecl; 10615 assert(SS.isEmpty()); 10616 10617 if (TUK == TUK_Reference) { 10618 // C++ [basic.scope.pdecl]p5: 10619 // -- for an elaborated-type-specifier of the form 10620 // 10621 // class-key identifier 10622 // 10623 // if the elaborated-type-specifier is used in the 10624 // decl-specifier-seq or parameter-declaration-clause of a 10625 // function defined in namespace scope, the identifier is 10626 // declared as a class-name in the namespace that contains 10627 // the declaration; otherwise, except as a friend 10628 // declaration, the identifier is declared in the smallest 10629 // non-class, non-function-prototype scope that contains the 10630 // declaration. 10631 // 10632 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10633 // C structs and unions. 10634 // 10635 // It is an error in C++ to declare (rather than define) an enum 10636 // type, including via an elaborated type specifier. We'll 10637 // diagnose that later; for now, declare the enum in the same 10638 // scope as we would have picked for any other tag type. 10639 // 10640 // GNU C also supports this behavior as part of its incomplete 10641 // enum types extension, while GNU C++ does not. 10642 // 10643 // Find the context where we'll be declaring the tag. 10644 // FIXME: We would like to maintain the current DeclContext as the 10645 // lexical context, 10646 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10647 SearchDC = SearchDC->getParent(); 10648 10649 // Find the scope where we'll be declaring the tag. 10650 while (S->isClassScope() || 10651 (getLangOpts().CPlusPlus && 10652 S->isFunctionPrototypeScope()) || 10653 ((S->getFlags() & Scope::DeclScope) == 0) || 10654 (S->getEntity() && S->getEntity()->isTransparentContext())) 10655 S = S->getParent(); 10656 } else { 10657 assert(TUK == TUK_Friend); 10658 // C++ [namespace.memdef]p3: 10659 // If a friend declaration in a non-local class first declares a 10660 // class or function, the friend class or function is a member of 10661 // the innermost enclosing namespace. 10662 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10663 } 10664 10665 // In C++, we need to do a redeclaration lookup to properly 10666 // diagnose some problems. 10667 if (getLangOpts().CPlusPlus) { 10668 Previous.setRedeclarationKind(ForRedeclaration); 10669 LookupQualifiedName(Previous, SearchDC); 10670 } 10671 } 10672 10673 if (!Previous.empty()) { 10674 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10675 NamedDecl *DirectPrevDecl = 10676 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10677 10678 // It's okay to have a tag decl in the same scope as a typedef 10679 // which hides a tag decl in the same scope. Finding this 10680 // insanity with a redeclaration lookup can only actually happen 10681 // in C++. 10682 // 10683 // This is also okay for elaborated-type-specifiers, which is 10684 // technically forbidden by the current standard but which is 10685 // okay according to the likely resolution of an open issue; 10686 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10687 if (getLangOpts().CPlusPlus) { 10688 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10689 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10690 TagDecl *Tag = TT->getDecl(); 10691 if (Tag->getDeclName() == Name && 10692 Tag->getDeclContext()->getRedeclContext() 10693 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10694 PrevDecl = Tag; 10695 Previous.clear(); 10696 Previous.addDecl(Tag); 10697 Previous.resolveKind(); 10698 } 10699 } 10700 } 10701 } 10702 10703 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10704 // If this is a use of a previous tag, or if the tag is already declared 10705 // in the same scope (so that the definition/declaration completes or 10706 // rementions the tag), reuse the decl. 10707 if (TUK == TUK_Reference || TUK == TUK_Friend || 10708 isDeclInScope(DirectPrevDecl, SearchDC, S, 10709 SS.isNotEmpty() || isExplicitSpecialization)) { 10710 // Make sure that this wasn't declared as an enum and now used as a 10711 // struct or something similar. 10712 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10713 TUK == TUK_Definition, KWLoc, 10714 *Name)) { 10715 bool SafeToContinue 10716 = (PrevTagDecl->getTagKind() != TTK_Enum && 10717 Kind != TTK_Enum); 10718 if (SafeToContinue) 10719 Diag(KWLoc, diag::err_use_with_wrong_tag) 10720 << Name 10721 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10722 PrevTagDecl->getKindName()); 10723 else 10724 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10725 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10726 10727 if (SafeToContinue) 10728 Kind = PrevTagDecl->getTagKind(); 10729 else { 10730 // Recover by making this an anonymous redefinition. 10731 Name = 0; 10732 Previous.clear(); 10733 Invalid = true; 10734 } 10735 } 10736 10737 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10738 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10739 10740 // If this is an elaborated-type-specifier for a scoped enumeration, 10741 // the 'class' keyword is not necessary and not permitted. 10742 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10743 if (ScopedEnum) 10744 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10745 << PrevEnum->isScoped() 10746 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10747 return PrevTagDecl; 10748 } 10749 10750 QualType EnumUnderlyingTy; 10751 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10752 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 10753 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10754 EnumUnderlyingTy = QualType(T, 0); 10755 10756 // All conflicts with previous declarations are recovered by 10757 // returning the previous declaration, unless this is a definition, 10758 // in which case we want the caller to bail out. 10759 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10760 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10761 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10762 } 10763 10764 // C++11 [class.mem]p1: 10765 // A member shall not be declared twice in the member-specification, 10766 // except that a nested class or member class template can be declared 10767 // and then later defined. 10768 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10769 S->isDeclScope(PrevDecl)) { 10770 Diag(NameLoc, diag::ext_member_redeclared); 10771 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10772 } 10773 10774 if (!Invalid) { 10775 // If this is a use, just return the declaration we found. 10776 10777 // FIXME: In the future, return a variant or some other clue 10778 // for the consumer of this Decl to know it doesn't own it. 10779 // For our current ASTs this shouldn't be a problem, but will 10780 // need to be changed with DeclGroups. 10781 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10782 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10783 return PrevTagDecl; 10784 10785 // Diagnose attempts to redefine a tag. 10786 if (TUK == TUK_Definition) { 10787 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10788 // If we're defining a specialization and the previous definition 10789 // is from an implicit instantiation, don't emit an error 10790 // here; we'll catch this in the general case below. 10791 bool IsExplicitSpecializationAfterInstantiation = false; 10792 if (isExplicitSpecialization) { 10793 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10794 IsExplicitSpecializationAfterInstantiation = 10795 RD->getTemplateSpecializationKind() != 10796 TSK_ExplicitSpecialization; 10797 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10798 IsExplicitSpecializationAfterInstantiation = 10799 ED->getTemplateSpecializationKind() != 10800 TSK_ExplicitSpecialization; 10801 } 10802 10803 if (!IsExplicitSpecializationAfterInstantiation) { 10804 // A redeclaration in function prototype scope in C isn't 10805 // visible elsewhere, so merely issue a warning. 10806 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10807 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10808 else 10809 Diag(NameLoc, diag::err_redefinition) << Name; 10810 Diag(Def->getLocation(), diag::note_previous_definition); 10811 // If this is a redefinition, recover by making this 10812 // struct be anonymous, which will make any later 10813 // references get the previous definition. 10814 Name = 0; 10815 Previous.clear(); 10816 Invalid = true; 10817 } 10818 } else { 10819 // If the type is currently being defined, complain 10820 // about a nested redefinition. 10821 const TagType *Tag 10822 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10823 if (Tag->isBeingDefined()) { 10824 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10825 Diag(PrevTagDecl->getLocation(), 10826 diag::note_previous_definition); 10827 Name = 0; 10828 Previous.clear(); 10829 Invalid = true; 10830 } 10831 } 10832 10833 // Okay, this is definition of a previously declared or referenced 10834 // tag PrevDecl. We're going to create a new Decl for it. 10835 } 10836 } 10837 // If we get here we have (another) forward declaration or we 10838 // have a definition. Just create a new decl. 10839 10840 } else { 10841 // If we get here, this is a definition of a new tag type in a nested 10842 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 10843 // new decl/type. We set PrevDecl to NULL so that the entities 10844 // have distinct types. 10845 Previous.clear(); 10846 } 10847 // If we get here, we're going to create a new Decl. If PrevDecl 10848 // is non-NULL, it's a definition of the tag declared by 10849 // PrevDecl. If it's NULL, we have a new definition. 10850 10851 10852 // Otherwise, PrevDecl is not a tag, but was found with tag 10853 // lookup. This is only actually possible in C++, where a few 10854 // things like templates still live in the tag namespace. 10855 } else { 10856 // Use a better diagnostic if an elaborated-type-specifier 10857 // found the wrong kind of type on the first 10858 // (non-redeclaration) lookup. 10859 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 10860 !Previous.isForRedeclaration()) { 10861 unsigned Kind = 0; 10862 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10863 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10864 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10865 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 10866 Diag(PrevDecl->getLocation(), diag::note_declared_at); 10867 Invalid = true; 10868 10869 // Otherwise, only diagnose if the declaration is in scope. 10870 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 10871 SS.isNotEmpty() || isExplicitSpecialization)) { 10872 // do nothing 10873 10874 // Diagnose implicit declarations introduced by elaborated types. 10875 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 10876 unsigned Kind = 0; 10877 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10878 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10879 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10880 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 10881 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10882 Invalid = true; 10883 10884 // Otherwise it's a declaration. Call out a particularly common 10885 // case here. 10886 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10887 unsigned Kind = 0; 10888 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 10889 Diag(NameLoc, diag::err_tag_definition_of_typedef) 10890 << Name << Kind << TND->getUnderlyingType(); 10891 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10892 Invalid = true; 10893 10894 // Otherwise, diagnose. 10895 } else { 10896 // The tag name clashes with something else in the target scope, 10897 // issue an error and recover by making this tag be anonymous. 10898 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 10899 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10900 Name = 0; 10901 Invalid = true; 10902 } 10903 10904 // The existing declaration isn't relevant to us; we're in a 10905 // new scope, so clear out the previous declaration. 10906 Previous.clear(); 10907 } 10908 } 10909 10910 CreateNewDecl: 10911 10912 TagDecl *PrevDecl = 0; 10913 if (Previous.isSingleResult()) 10914 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 10915 10916 // If there is an identifier, use the location of the identifier as the 10917 // location of the decl, otherwise use the location of the struct/union 10918 // keyword. 10919 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 10920 10921 // Otherwise, create a new declaration. If there is a previous 10922 // declaration of the same entity, the two will be linked via 10923 // PrevDecl. 10924 TagDecl *New; 10925 10926 bool IsForwardReference = false; 10927 if (Kind == TTK_Enum) { 10928 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10929 // enum X { A, B, C } D; D should chain to X. 10930 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 10931 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 10932 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 10933 // If this is an undefined enum, warn. 10934 if (TUK != TUK_Definition && !Invalid) { 10935 TagDecl *Def; 10936 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 10937 cast<EnumDecl>(New)->isFixed()) { 10938 // C++0x: 7.2p2: opaque-enum-declaration. 10939 // Conflicts are diagnosed above. Do nothing. 10940 } 10941 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 10942 Diag(Loc, diag::ext_forward_ref_enum_def) 10943 << New; 10944 Diag(Def->getLocation(), diag::note_previous_definition); 10945 } else { 10946 unsigned DiagID = diag::ext_forward_ref_enum; 10947 if (getLangOpts().MSVCCompat) 10948 DiagID = diag::ext_ms_forward_ref_enum; 10949 else if (getLangOpts().CPlusPlus) 10950 DiagID = diag::err_forward_ref_enum; 10951 Diag(Loc, DiagID); 10952 10953 // If this is a forward-declared reference to an enumeration, make a 10954 // note of it; we won't actually be introducing the declaration into 10955 // the declaration context. 10956 if (TUK == TUK_Reference) 10957 IsForwardReference = true; 10958 } 10959 } 10960 10961 if (EnumUnderlying) { 10962 EnumDecl *ED = cast<EnumDecl>(New); 10963 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10964 ED->setIntegerTypeSourceInfo(TI); 10965 else 10966 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 10967 ED->setPromotionType(ED->getIntegerType()); 10968 } 10969 10970 } else { 10971 // struct/union/class 10972 10973 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10974 // struct X { int A; } D; D should chain to X. 10975 if (getLangOpts().CPlusPlus) { 10976 // FIXME: Look for a way to use RecordDecl for simple structs. 10977 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10978 cast_or_null<CXXRecordDecl>(PrevDecl)); 10979 10980 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 10981 StdBadAlloc = cast<CXXRecordDecl>(New); 10982 } else 10983 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10984 cast_or_null<RecordDecl>(PrevDecl)); 10985 } 10986 10987 // C++11 [dcl.type]p3: 10988 // A type-specifier-seq shall not define a class or enumeration [...]. 10989 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 10990 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 10991 << Context.getTagDeclType(New); 10992 Invalid = true; 10993 } 10994 10995 // Maybe add qualifier info. 10996 if (SS.isNotEmpty()) { 10997 if (SS.isSet()) { 10998 // If this is either a declaration or a definition, check the 10999 // nested-name-specifier against the current context. We don't do this 11000 // for explicit specializations, because they have similar checking 11001 // (with more specific diagnostics) in the call to 11002 // CheckMemberSpecialization, below. 11003 if (!isExplicitSpecialization && 11004 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11005 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11006 Invalid = true; 11007 11008 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11009 if (TemplateParameterLists.size() > 0) { 11010 New->setTemplateParameterListsInfo(Context, 11011 TemplateParameterLists.size(), 11012 TemplateParameterLists.data()); 11013 } 11014 } 11015 else 11016 Invalid = true; 11017 } 11018 11019 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11020 // Add alignment attributes if necessary; these attributes are checked when 11021 // the ASTContext lays out the structure. 11022 // 11023 // It is important for implementing the correct semantics that this 11024 // happen here (in act on tag decl). The #pragma pack stack is 11025 // maintained as a result of parser callbacks which can occur at 11026 // many points during the parsing of a struct declaration (because 11027 // the #pragma tokens are effectively skipped over during the 11028 // parsing of the struct). 11029 if (TUK == TUK_Definition) { 11030 AddAlignmentAttributesForRecord(RD); 11031 AddMsStructLayoutForRecord(RD); 11032 } 11033 } 11034 11035 if (ModulePrivateLoc.isValid()) { 11036 if (isExplicitSpecialization) 11037 Diag(New->getLocation(), diag::err_module_private_specialization) 11038 << 2 11039 << FixItHint::CreateRemoval(ModulePrivateLoc); 11040 // __module_private__ does not apply to local classes. However, we only 11041 // diagnose this as an error when the declaration specifiers are 11042 // freestanding. Here, we just ignore the __module_private__. 11043 else if (!SearchDC->isFunctionOrMethod()) 11044 New->setModulePrivate(); 11045 } 11046 11047 // If this is a specialization of a member class (of a class template), 11048 // check the specialization. 11049 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11050 Invalid = true; 11051 11052 if (Invalid) 11053 New->setInvalidDecl(); 11054 11055 if (Attr) 11056 ProcessDeclAttributeList(S, New, Attr); 11057 11058 // If we're declaring or defining a tag in function prototype scope in C, 11059 // note that this type can only be used within the function and add it to 11060 // the list of decls to inject into the function definition scope. 11061 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) && 11062 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11063 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11064 DeclsInPrototypeScope.push_back(New); 11065 } 11066 11067 // Set the lexical context. If the tag has a C++ scope specifier, the 11068 // lexical context will be different from the semantic context. 11069 New->setLexicalDeclContext(CurContext); 11070 11071 // Mark this as a friend decl if applicable. 11072 // In Microsoft mode, a friend declaration also acts as a forward 11073 // declaration so we always pass true to setObjectOfFriendDecl to make 11074 // the tag name visible. 11075 if (TUK == TUK_Friend) 11076 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11077 getLangOpts().MicrosoftExt); 11078 11079 // Set the access specifier. 11080 if (!Invalid && SearchDC->isRecord()) 11081 SetMemberAccessSpecifier(New, PrevDecl, AS); 11082 11083 if (TUK == TUK_Definition) 11084 New->startDefinition(); 11085 11086 // If this has an identifier, add it to the scope stack. 11087 if (TUK == TUK_Friend) { 11088 // We might be replacing an existing declaration in the lookup tables; 11089 // if so, borrow its access specifier. 11090 if (PrevDecl) 11091 New->setAccess(PrevDecl->getAccess()); 11092 11093 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11094 DC->makeDeclVisibleInContext(New); 11095 if (Name) // can be null along some error paths 11096 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11097 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11098 } else if (Name) { 11099 S = getNonFieldDeclScope(S); 11100 PushOnScopeChains(New, S, !IsForwardReference); 11101 if (IsForwardReference) 11102 SearchDC->makeDeclVisibleInContext(New); 11103 11104 } else { 11105 CurContext->addDecl(New); 11106 } 11107 11108 // If this is the C FILE type, notify the AST context. 11109 if (IdentifierInfo *II = New->getIdentifier()) 11110 if (!New->isInvalidDecl() && 11111 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11112 II->isStr("FILE")) 11113 Context.setFILEDecl(New); 11114 11115 if (PrevDecl) 11116 mergeDeclAttributes(New, PrevDecl); 11117 11118 // If there's a #pragma GCC visibility in scope, set the visibility of this 11119 // record. 11120 AddPushedVisibilityAttribute(New); 11121 11122 OwnedDecl = true; 11123 // In C++, don't return an invalid declaration. We can't recover well from 11124 // the cases where we make the type anonymous. 11125 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11126 } 11127 11128 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11129 AdjustDeclIfTemplate(TagD); 11130 TagDecl *Tag = cast<TagDecl>(TagD); 11131 11132 // Enter the tag context. 11133 PushDeclContext(S, Tag); 11134 11135 ActOnDocumentableDecl(TagD); 11136 11137 // If there's a #pragma GCC visibility in scope, set the visibility of this 11138 // record. 11139 AddPushedVisibilityAttribute(Tag); 11140 } 11141 11142 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11143 assert(isa<ObjCContainerDecl>(IDecl) && 11144 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11145 DeclContext *OCD = cast<DeclContext>(IDecl); 11146 assert(getContainingDC(OCD) == CurContext && 11147 "The next DeclContext should be lexically contained in the current one."); 11148 CurContext = OCD; 11149 return IDecl; 11150 } 11151 11152 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11153 SourceLocation FinalLoc, 11154 bool IsFinalSpelledSealed, 11155 SourceLocation LBraceLoc) { 11156 AdjustDeclIfTemplate(TagD); 11157 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11158 11159 FieldCollector->StartClass(); 11160 11161 if (!Record->getIdentifier()) 11162 return; 11163 11164 if (FinalLoc.isValid()) 11165 Record->addAttr(new (Context) 11166 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11167 11168 // C++ [class]p2: 11169 // [...] The class-name is also inserted into the scope of the 11170 // class itself; this is known as the injected-class-name. For 11171 // purposes of access checking, the injected-class-name is treated 11172 // as if it were a public member name. 11173 CXXRecordDecl *InjectedClassName 11174 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11175 Record->getLocStart(), Record->getLocation(), 11176 Record->getIdentifier(), 11177 /*PrevDecl=*/0, 11178 /*DelayTypeCreation=*/true); 11179 Context.getTypeDeclType(InjectedClassName, Record); 11180 InjectedClassName->setImplicit(); 11181 InjectedClassName->setAccess(AS_public); 11182 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11183 InjectedClassName->setDescribedClassTemplate(Template); 11184 PushOnScopeChains(InjectedClassName, S); 11185 assert(InjectedClassName->isInjectedClassName() && 11186 "Broken injected-class-name"); 11187 } 11188 11189 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11190 SourceLocation RBraceLoc) { 11191 AdjustDeclIfTemplate(TagD); 11192 TagDecl *Tag = cast<TagDecl>(TagD); 11193 Tag->setRBraceLoc(RBraceLoc); 11194 11195 // Make sure we "complete" the definition even it is invalid. 11196 if (Tag->isBeingDefined()) { 11197 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11198 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11199 RD->completeDefinition(); 11200 } 11201 11202 if (isa<CXXRecordDecl>(Tag)) 11203 FieldCollector->FinishClass(); 11204 11205 // Exit this scope of this tag's definition. 11206 PopDeclContext(); 11207 11208 if (getCurLexicalContext()->isObjCContainer() && 11209 Tag->getDeclContext()->isFileContext()) 11210 Tag->setTopLevelDeclInObjCContainer(); 11211 11212 // Notify the consumer that we've defined a tag. 11213 if (!Tag->isInvalidDecl()) 11214 Consumer.HandleTagDeclDefinition(Tag); 11215 } 11216 11217 void Sema::ActOnObjCContainerFinishDefinition() { 11218 // Exit this scope of this interface definition. 11219 PopDeclContext(); 11220 } 11221 11222 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11223 assert(DC == CurContext && "Mismatch of container contexts"); 11224 OriginalLexicalContext = DC; 11225 ActOnObjCContainerFinishDefinition(); 11226 } 11227 11228 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11229 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11230 OriginalLexicalContext = 0; 11231 } 11232 11233 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11234 AdjustDeclIfTemplate(TagD); 11235 TagDecl *Tag = cast<TagDecl>(TagD); 11236 Tag->setInvalidDecl(); 11237 11238 // Make sure we "complete" the definition even it is invalid. 11239 if (Tag->isBeingDefined()) { 11240 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11241 RD->completeDefinition(); 11242 } 11243 11244 // We're undoing ActOnTagStartDefinition here, not 11245 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11246 // the FieldCollector. 11247 11248 PopDeclContext(); 11249 } 11250 11251 // Note that FieldName may be null for anonymous bitfields. 11252 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11253 IdentifierInfo *FieldName, 11254 QualType FieldTy, bool IsMsStruct, 11255 Expr *BitWidth, bool *ZeroWidth) { 11256 // Default to true; that shouldn't confuse checks for emptiness 11257 if (ZeroWidth) 11258 *ZeroWidth = true; 11259 11260 // C99 6.7.2.1p4 - verify the field type. 11261 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11262 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11263 // Handle incomplete types with specific error. 11264 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11265 return ExprError(); 11266 if (FieldName) 11267 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11268 << FieldName << FieldTy << BitWidth->getSourceRange(); 11269 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11270 << FieldTy << BitWidth->getSourceRange(); 11271 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11272 UPPC_BitFieldWidth)) 11273 return ExprError(); 11274 11275 // If the bit-width is type- or value-dependent, don't try to check 11276 // it now. 11277 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11278 return Owned(BitWidth); 11279 11280 llvm::APSInt Value; 11281 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11282 if (ICE.isInvalid()) 11283 return ICE; 11284 BitWidth = ICE.take(); 11285 11286 if (Value != 0 && ZeroWidth) 11287 *ZeroWidth = false; 11288 11289 // Zero-width bitfield is ok for anonymous field. 11290 if (Value == 0 && FieldName) 11291 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11292 11293 if (Value.isSigned() && Value.isNegative()) { 11294 if (FieldName) 11295 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11296 << FieldName << Value.toString(10); 11297 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11298 << Value.toString(10); 11299 } 11300 11301 if (!FieldTy->isDependentType()) { 11302 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11303 if (Value.getZExtValue() > TypeSize) { 11304 if (!getLangOpts().CPlusPlus || IsMsStruct || 11305 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11306 if (FieldName) 11307 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11308 << FieldName << (unsigned)Value.getZExtValue() 11309 << (unsigned)TypeSize; 11310 11311 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11312 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11313 } 11314 11315 if (FieldName) 11316 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11317 << FieldName << (unsigned)Value.getZExtValue() 11318 << (unsigned)TypeSize; 11319 else 11320 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11321 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11322 } 11323 } 11324 11325 return Owned(BitWidth); 11326 } 11327 11328 /// ActOnField - Each field of a C struct/union is passed into this in order 11329 /// to create a FieldDecl object for it. 11330 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11331 Declarator &D, Expr *BitfieldWidth) { 11332 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11333 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11334 /*InitStyle=*/ICIS_NoInit, AS_public); 11335 return Res; 11336 } 11337 11338 /// HandleField - Analyze a field of a C struct or a C++ data member. 11339 /// 11340 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11341 SourceLocation DeclStart, 11342 Declarator &D, Expr *BitWidth, 11343 InClassInitStyle InitStyle, 11344 AccessSpecifier AS) { 11345 IdentifierInfo *II = D.getIdentifier(); 11346 SourceLocation Loc = DeclStart; 11347 if (II) Loc = D.getIdentifierLoc(); 11348 11349 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11350 QualType T = TInfo->getType(); 11351 if (getLangOpts().CPlusPlus) { 11352 CheckExtraCXXDefaultArguments(D); 11353 11354 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11355 UPPC_DataMemberType)) { 11356 D.setInvalidType(); 11357 T = Context.IntTy; 11358 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11359 } 11360 } 11361 11362 // TR 18037 does not allow fields to be declared with address spaces. 11363 if (T.getQualifiers().hasAddressSpace()) { 11364 Diag(Loc, diag::err_field_with_address_space); 11365 D.setInvalidType(); 11366 } 11367 11368 // OpenCL 1.2 spec, s6.9 r: 11369 // The event type cannot be used to declare a structure or union field. 11370 if (LangOpts.OpenCL && T->isEventT()) { 11371 Diag(Loc, diag::err_event_t_struct_field); 11372 D.setInvalidType(); 11373 } 11374 11375 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11376 11377 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11378 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11379 diag::err_invalid_thread) 11380 << DeclSpec::getSpecifierName(TSCS); 11381 11382 // Check to see if this name was declared as a member previously 11383 NamedDecl *PrevDecl = 0; 11384 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11385 LookupName(Previous, S); 11386 switch (Previous.getResultKind()) { 11387 case LookupResult::Found: 11388 case LookupResult::FoundUnresolvedValue: 11389 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11390 break; 11391 11392 case LookupResult::FoundOverloaded: 11393 PrevDecl = Previous.getRepresentativeDecl(); 11394 break; 11395 11396 case LookupResult::NotFound: 11397 case LookupResult::NotFoundInCurrentInstantiation: 11398 case LookupResult::Ambiguous: 11399 break; 11400 } 11401 Previous.suppressDiagnostics(); 11402 11403 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11404 // Maybe we will complain about the shadowed template parameter. 11405 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11406 // Just pretend that we didn't see the previous declaration. 11407 PrevDecl = 0; 11408 } 11409 11410 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11411 PrevDecl = 0; 11412 11413 bool Mutable 11414 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11415 SourceLocation TSSL = D.getLocStart(); 11416 FieldDecl *NewFD 11417 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11418 TSSL, AS, PrevDecl, &D); 11419 11420 if (NewFD->isInvalidDecl()) 11421 Record->setInvalidDecl(); 11422 11423 if (D.getDeclSpec().isModulePrivateSpecified()) 11424 NewFD->setModulePrivate(); 11425 11426 if (NewFD->isInvalidDecl() && PrevDecl) { 11427 // Don't introduce NewFD into scope; there's already something 11428 // with the same name in the same scope. 11429 } else if (II) { 11430 PushOnScopeChains(NewFD, S); 11431 } else 11432 Record->addDecl(NewFD); 11433 11434 return NewFD; 11435 } 11436 11437 /// \brief Build a new FieldDecl and check its well-formedness. 11438 /// 11439 /// This routine builds a new FieldDecl given the fields name, type, 11440 /// record, etc. \p PrevDecl should refer to any previous declaration 11441 /// with the same name and in the same scope as the field to be 11442 /// created. 11443 /// 11444 /// \returns a new FieldDecl. 11445 /// 11446 /// \todo The Declarator argument is a hack. It will be removed once 11447 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11448 TypeSourceInfo *TInfo, 11449 RecordDecl *Record, SourceLocation Loc, 11450 bool Mutable, Expr *BitWidth, 11451 InClassInitStyle InitStyle, 11452 SourceLocation TSSL, 11453 AccessSpecifier AS, NamedDecl *PrevDecl, 11454 Declarator *D) { 11455 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11456 bool InvalidDecl = false; 11457 if (D) InvalidDecl = D->isInvalidType(); 11458 11459 // If we receive a broken type, recover by assuming 'int' and 11460 // marking this declaration as invalid. 11461 if (T.isNull()) { 11462 InvalidDecl = true; 11463 T = Context.IntTy; 11464 } 11465 11466 QualType EltTy = Context.getBaseElementType(T); 11467 if (!EltTy->isDependentType()) { 11468 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11469 // Fields of incomplete type force their record to be invalid. 11470 Record->setInvalidDecl(); 11471 InvalidDecl = true; 11472 } else { 11473 NamedDecl *Def; 11474 EltTy->isIncompleteType(&Def); 11475 if (Def && Def->isInvalidDecl()) { 11476 Record->setInvalidDecl(); 11477 InvalidDecl = true; 11478 } 11479 } 11480 } 11481 11482 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11483 if (BitWidth && getLangOpts().OpenCL) { 11484 Diag(Loc, diag::err_opencl_bitfields); 11485 InvalidDecl = true; 11486 } 11487 11488 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11489 // than a variably modified type. 11490 if (!InvalidDecl && T->isVariablyModifiedType()) { 11491 bool SizeIsNegative; 11492 llvm::APSInt Oversized; 11493 11494 TypeSourceInfo *FixedTInfo = 11495 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11496 SizeIsNegative, 11497 Oversized); 11498 if (FixedTInfo) { 11499 Diag(Loc, diag::warn_illegal_constant_array_size); 11500 TInfo = FixedTInfo; 11501 T = FixedTInfo->getType(); 11502 } else { 11503 if (SizeIsNegative) 11504 Diag(Loc, diag::err_typecheck_negative_array_size); 11505 else if (Oversized.getBoolValue()) 11506 Diag(Loc, diag::err_array_too_large) 11507 << Oversized.toString(10); 11508 else 11509 Diag(Loc, diag::err_typecheck_field_variable_size); 11510 InvalidDecl = true; 11511 } 11512 } 11513 11514 // Fields can not have abstract class types 11515 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11516 diag::err_abstract_type_in_decl, 11517 AbstractFieldType)) 11518 InvalidDecl = true; 11519 11520 bool ZeroWidth = false; 11521 // If this is declared as a bit-field, check the bit-field. 11522 if (!InvalidDecl && BitWidth) { 11523 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11524 &ZeroWidth).take(); 11525 if (!BitWidth) { 11526 InvalidDecl = true; 11527 BitWidth = 0; 11528 ZeroWidth = false; 11529 } 11530 } 11531 11532 // Check that 'mutable' is consistent with the type of the declaration. 11533 if (!InvalidDecl && Mutable) { 11534 unsigned DiagID = 0; 11535 if (T->isReferenceType()) 11536 DiagID = diag::err_mutable_reference; 11537 else if (T.isConstQualified()) 11538 DiagID = diag::err_mutable_const; 11539 11540 if (DiagID) { 11541 SourceLocation ErrLoc = Loc; 11542 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11543 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11544 Diag(ErrLoc, DiagID); 11545 Mutable = false; 11546 InvalidDecl = true; 11547 } 11548 } 11549 11550 // C++11 [class.union]p8 (DR1460): 11551 // At most one variant member of a union may have a 11552 // brace-or-equal-initializer. 11553 if (InitStyle != ICIS_NoInit) 11554 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11555 11556 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11557 BitWidth, Mutable, InitStyle); 11558 if (InvalidDecl) 11559 NewFD->setInvalidDecl(); 11560 11561 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11562 Diag(Loc, diag::err_duplicate_member) << II; 11563 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11564 NewFD->setInvalidDecl(); 11565 } 11566 11567 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11568 if (Record->isUnion()) { 11569 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11570 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11571 if (RDecl->getDefinition()) { 11572 // C++ [class.union]p1: An object of a class with a non-trivial 11573 // constructor, a non-trivial copy constructor, a non-trivial 11574 // destructor, or a non-trivial copy assignment operator 11575 // cannot be a member of a union, nor can an array of such 11576 // objects. 11577 if (CheckNontrivialField(NewFD)) 11578 NewFD->setInvalidDecl(); 11579 } 11580 } 11581 11582 // C++ [class.union]p1: If a union contains a member of reference type, 11583 // the program is ill-formed, except when compiling with MSVC extensions 11584 // enabled. 11585 if (EltTy->isReferenceType()) { 11586 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11587 diag::ext_union_member_of_reference_type : 11588 diag::err_union_member_of_reference_type) 11589 << NewFD->getDeclName() << EltTy; 11590 if (!getLangOpts().MicrosoftExt) 11591 NewFD->setInvalidDecl(); 11592 } 11593 } 11594 } 11595 11596 // FIXME: We need to pass in the attributes given an AST 11597 // representation, not a parser representation. 11598 if (D) { 11599 // FIXME: The current scope is almost... but not entirely... correct here. 11600 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11601 11602 if (NewFD->hasAttrs()) 11603 CheckAlignasUnderalignment(NewFD); 11604 } 11605 11606 // In auto-retain/release, infer strong retension for fields of 11607 // retainable type. 11608 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11609 NewFD->setInvalidDecl(); 11610 11611 if (T.isObjCGCWeak()) 11612 Diag(Loc, diag::warn_attribute_weak_on_field); 11613 11614 NewFD->setAccess(AS); 11615 return NewFD; 11616 } 11617 11618 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11619 assert(FD); 11620 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11621 11622 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11623 return false; 11624 11625 QualType EltTy = Context.getBaseElementType(FD->getType()); 11626 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11627 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11628 if (RDecl->getDefinition()) { 11629 // We check for copy constructors before constructors 11630 // because otherwise we'll never get complaints about 11631 // copy constructors. 11632 11633 CXXSpecialMember member = CXXInvalid; 11634 // We're required to check for any non-trivial constructors. Since the 11635 // implicit default constructor is suppressed if there are any 11636 // user-declared constructors, we just need to check that there is a 11637 // trivial default constructor and a trivial copy constructor. (We don't 11638 // worry about move constructors here, since this is a C++98 check.) 11639 if (RDecl->hasNonTrivialCopyConstructor()) 11640 member = CXXCopyConstructor; 11641 else if (!RDecl->hasTrivialDefaultConstructor()) 11642 member = CXXDefaultConstructor; 11643 else if (RDecl->hasNonTrivialCopyAssignment()) 11644 member = CXXCopyAssignment; 11645 else if (RDecl->hasNonTrivialDestructor()) 11646 member = CXXDestructor; 11647 11648 if (member != CXXInvalid) { 11649 if (!getLangOpts().CPlusPlus11 && 11650 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11651 // Objective-C++ ARC: it is an error to have a non-trivial field of 11652 // a union. However, system headers in Objective-C programs 11653 // occasionally have Objective-C lifetime objects within unions, 11654 // and rather than cause the program to fail, we make those 11655 // members unavailable. 11656 SourceLocation Loc = FD->getLocation(); 11657 if (getSourceManager().isInSystemHeader(Loc)) { 11658 if (!FD->hasAttr<UnavailableAttr>()) 11659 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11660 "this system field has retaining ownership", 11661 Loc)); 11662 return false; 11663 } 11664 } 11665 11666 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11667 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11668 diag::err_illegal_union_or_anon_struct_member) 11669 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11670 DiagnoseNontrivial(RDecl, member); 11671 return !getLangOpts().CPlusPlus11; 11672 } 11673 } 11674 } 11675 11676 return false; 11677 } 11678 11679 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11680 /// AST enum value. 11681 static ObjCIvarDecl::AccessControl 11682 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11683 switch (ivarVisibility) { 11684 default: llvm_unreachable("Unknown visitibility kind"); 11685 case tok::objc_private: return ObjCIvarDecl::Private; 11686 case tok::objc_public: return ObjCIvarDecl::Public; 11687 case tok::objc_protected: return ObjCIvarDecl::Protected; 11688 case tok::objc_package: return ObjCIvarDecl::Package; 11689 } 11690 } 11691 11692 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11693 /// in order to create an IvarDecl object for it. 11694 Decl *Sema::ActOnIvar(Scope *S, 11695 SourceLocation DeclStart, 11696 Declarator &D, Expr *BitfieldWidth, 11697 tok::ObjCKeywordKind Visibility) { 11698 11699 IdentifierInfo *II = D.getIdentifier(); 11700 Expr *BitWidth = (Expr*)BitfieldWidth; 11701 SourceLocation Loc = DeclStart; 11702 if (II) Loc = D.getIdentifierLoc(); 11703 11704 // FIXME: Unnamed fields can be handled in various different ways, for 11705 // example, unnamed unions inject all members into the struct namespace! 11706 11707 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11708 QualType T = TInfo->getType(); 11709 11710 if (BitWidth) { 11711 // 6.7.2.1p3, 6.7.2.1p4 11712 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11713 if (!BitWidth) 11714 D.setInvalidType(); 11715 } else { 11716 // Not a bitfield. 11717 11718 // validate II. 11719 11720 } 11721 if (T->isReferenceType()) { 11722 Diag(Loc, diag::err_ivar_reference_type); 11723 D.setInvalidType(); 11724 } 11725 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11726 // than a variably modified type. 11727 else if (T->isVariablyModifiedType()) { 11728 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11729 D.setInvalidType(); 11730 } 11731 11732 // Get the visibility (access control) for this ivar. 11733 ObjCIvarDecl::AccessControl ac = 11734 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11735 : ObjCIvarDecl::None; 11736 // Must set ivar's DeclContext to its enclosing interface. 11737 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11738 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11739 return 0; 11740 ObjCContainerDecl *EnclosingContext; 11741 if (ObjCImplementationDecl *IMPDecl = 11742 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11743 if (LangOpts.ObjCRuntime.isFragile()) { 11744 // Case of ivar declared in an implementation. Context is that of its class. 11745 EnclosingContext = IMPDecl->getClassInterface(); 11746 assert(EnclosingContext && "Implementation has no class interface!"); 11747 } 11748 else 11749 EnclosingContext = EnclosingDecl; 11750 } else { 11751 if (ObjCCategoryDecl *CDecl = 11752 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11753 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11754 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11755 return 0; 11756 } 11757 } 11758 EnclosingContext = EnclosingDecl; 11759 } 11760 11761 // Construct the decl. 11762 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11763 DeclStart, Loc, II, T, 11764 TInfo, ac, (Expr *)BitfieldWidth); 11765 11766 if (II) { 11767 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11768 ForRedeclaration); 11769 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11770 && !isa<TagDecl>(PrevDecl)) { 11771 Diag(Loc, diag::err_duplicate_member) << II; 11772 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11773 NewID->setInvalidDecl(); 11774 } 11775 } 11776 11777 // Process attributes attached to the ivar. 11778 ProcessDeclAttributes(S, NewID, D); 11779 11780 if (D.isInvalidType()) 11781 NewID->setInvalidDecl(); 11782 11783 // In ARC, infer 'retaining' for ivars of retainable type. 11784 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11785 NewID->setInvalidDecl(); 11786 11787 if (D.getDeclSpec().isModulePrivateSpecified()) 11788 NewID->setModulePrivate(); 11789 11790 if (II) { 11791 // FIXME: When interfaces are DeclContexts, we'll need to add 11792 // these to the interface. 11793 S->AddDecl(NewID); 11794 IdResolver.AddDecl(NewID); 11795 } 11796 11797 if (LangOpts.ObjCRuntime.isNonFragile() && 11798 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11799 Diag(Loc, diag::warn_ivars_in_interface); 11800 11801 return NewID; 11802 } 11803 11804 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11805 /// class and class extensions. For every class \@interface and class 11806 /// extension \@interface, if the last ivar is a bitfield of any type, 11807 /// then add an implicit `char :0` ivar to the end of that interface. 11808 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11809 SmallVectorImpl<Decl *> &AllIvarDecls) { 11810 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11811 return; 11812 11813 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11814 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11815 11816 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11817 return; 11818 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11819 if (!ID) { 11820 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11821 if (!CD->IsClassExtension()) 11822 return; 11823 } 11824 // No need to add this to end of @implementation. 11825 else 11826 return; 11827 } 11828 // All conditions are met. Add a new bitfield to the tail end of ivars. 11829 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11830 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11831 11832 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11833 DeclLoc, DeclLoc, 0, 11834 Context.CharTy, 11835 Context.getTrivialTypeSourceInfo(Context.CharTy, 11836 DeclLoc), 11837 ObjCIvarDecl::Private, BW, 11838 true); 11839 AllIvarDecls.push_back(Ivar); 11840 } 11841 11842 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 11843 ArrayRef<Decl *> Fields, SourceLocation LBrac, 11844 SourceLocation RBrac, AttributeList *Attr) { 11845 assert(EnclosingDecl && "missing record or interface decl"); 11846 11847 // If this is an Objective-C @implementation or category and we have 11848 // new fields here we should reset the layout of the interface since 11849 // it will now change. 11850 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 11851 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 11852 switch (DC->getKind()) { 11853 default: break; 11854 case Decl::ObjCCategory: 11855 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 11856 break; 11857 case Decl::ObjCImplementation: 11858 Context. 11859 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 11860 break; 11861 } 11862 } 11863 11864 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 11865 11866 // Start counting up the number of named members; make sure to include 11867 // members of anonymous structs and unions in the total. 11868 unsigned NumNamedMembers = 0; 11869 if (Record) { 11870 for (const auto *I : Record->decls()) { 11871 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 11872 if (IFD->getDeclName()) 11873 ++NumNamedMembers; 11874 } 11875 } 11876 11877 // Verify that all the fields are okay. 11878 SmallVector<FieldDecl*, 32> RecFields; 11879 11880 bool ARCErrReported = false; 11881 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 11882 i != end; ++i) { 11883 FieldDecl *FD = cast<FieldDecl>(*i); 11884 11885 // Get the type for the field. 11886 const Type *FDTy = FD->getType().getTypePtr(); 11887 11888 if (!FD->isAnonymousStructOrUnion()) { 11889 // Remember all fields written by the user. 11890 RecFields.push_back(FD); 11891 } 11892 11893 // If the field is already invalid for some reason, don't emit more 11894 // diagnostics about it. 11895 if (FD->isInvalidDecl()) { 11896 EnclosingDecl->setInvalidDecl(); 11897 continue; 11898 } 11899 11900 // C99 6.7.2.1p2: 11901 // A structure or union shall not contain a member with 11902 // incomplete or function type (hence, a structure shall not 11903 // contain an instance of itself, but may contain a pointer to 11904 // an instance of itself), except that the last member of a 11905 // structure with more than one named member may have incomplete 11906 // array type; such a structure (and any union containing, 11907 // possibly recursively, a member that is such a structure) 11908 // shall not be a member of a structure or an element of an 11909 // array. 11910 if (FDTy->isFunctionType()) { 11911 // Field declared as a function. 11912 Diag(FD->getLocation(), diag::err_field_declared_as_function) 11913 << FD->getDeclName(); 11914 FD->setInvalidDecl(); 11915 EnclosingDecl->setInvalidDecl(); 11916 continue; 11917 } else if (FDTy->isIncompleteArrayType() && Record && 11918 ((i + 1 == Fields.end() && !Record->isUnion()) || 11919 ((getLangOpts().MicrosoftExt || 11920 getLangOpts().CPlusPlus) && 11921 (i + 1 == Fields.end() || Record->isUnion())))) { 11922 // Flexible array member. 11923 // Microsoft and g++ is more permissive regarding flexible array. 11924 // It will accept flexible array in union and also 11925 // as the sole element of a struct/class. 11926 unsigned DiagID = 0; 11927 if (Record->isUnion()) 11928 DiagID = getLangOpts().MicrosoftExt 11929 ? diag::ext_flexible_array_union_ms 11930 : getLangOpts().CPlusPlus 11931 ? diag::ext_flexible_array_union_gnu 11932 : diag::err_flexible_array_union; 11933 else if (Fields.size() == 1) 11934 DiagID = getLangOpts().MicrosoftExt 11935 ? diag::ext_flexible_array_empty_aggregate_ms 11936 : getLangOpts().CPlusPlus 11937 ? diag::ext_flexible_array_empty_aggregate_gnu 11938 : NumNamedMembers < 1 11939 ? diag::err_flexible_array_empty_aggregate 11940 : 0; 11941 11942 if (DiagID) 11943 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 11944 << Record->getTagKind(); 11945 // While the layout of types that contain virtual bases is not specified 11946 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 11947 // virtual bases after the derived members. This would make a flexible 11948 // array member declared at the end of an object not adjacent to the end 11949 // of the type. 11950 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 11951 if (RD->getNumVBases() != 0) 11952 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 11953 << FD->getDeclName() << Record->getTagKind(); 11954 if (!getLangOpts().C99) 11955 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11956 << FD->getDeclName() << Record->getTagKind(); 11957 11958 // If the element type has a non-trivial destructor, we would not 11959 // implicitly destroy the elements, so disallow it for now. 11960 // 11961 // FIXME: GCC allows this. We should probably either implicitly delete 11962 // the destructor of the containing class, or just allow this. 11963 QualType BaseElem = Context.getBaseElementType(FD->getType()); 11964 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 11965 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 11966 << FD->getDeclName() << FD->getType(); 11967 FD->setInvalidDecl(); 11968 EnclosingDecl->setInvalidDecl(); 11969 continue; 11970 } 11971 // Okay, we have a legal flexible array member at the end of the struct. 11972 if (Record) 11973 Record->setHasFlexibleArrayMember(true); 11974 } else if (!FDTy->isDependentType() && 11975 RequireCompleteType(FD->getLocation(), FD->getType(), 11976 diag::err_field_incomplete)) { 11977 // Incomplete type 11978 FD->setInvalidDecl(); 11979 EnclosingDecl->setInvalidDecl(); 11980 continue; 11981 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 11982 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 11983 // If this is a member of a union, then entire union becomes "flexible". 11984 if (Record && Record->isUnion()) { 11985 Record->setHasFlexibleArrayMember(true); 11986 } else { 11987 // If this is a struct/class and this is not the last element, reject 11988 // it. Note that GCC supports variable sized arrays in the middle of 11989 // structures. 11990 if (i + 1 != Fields.end()) 11991 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 11992 << FD->getDeclName() << FD->getType(); 11993 else { 11994 // We support flexible arrays at the end of structs in 11995 // other structs as an extension. 11996 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 11997 << FD->getDeclName(); 11998 if (Record) 11999 Record->setHasFlexibleArrayMember(true); 12000 } 12001 } 12002 } 12003 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12004 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12005 diag::err_abstract_type_in_decl, 12006 AbstractIvarType)) { 12007 // Ivars can not have abstract class types 12008 FD->setInvalidDecl(); 12009 } 12010 if (Record && FDTTy->getDecl()->hasObjectMember()) 12011 Record->setHasObjectMember(true); 12012 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12013 Record->setHasVolatileMember(true); 12014 } else if (FDTy->isObjCObjectType()) { 12015 /// A field cannot be an Objective-c object 12016 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12017 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12018 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12019 FD->setType(T); 12020 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12021 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12022 // It's an error in ARC if a field has lifetime. 12023 // We don't want to report this in a system header, though, 12024 // so we just make the field unavailable. 12025 // FIXME: that's really not sufficient; we need to make the type 12026 // itself invalid to, say, initialize or copy. 12027 QualType T = FD->getType(); 12028 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12029 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12030 SourceLocation loc = FD->getLocation(); 12031 if (getSourceManager().isInSystemHeader(loc)) { 12032 if (!FD->hasAttr<UnavailableAttr>()) { 12033 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12034 "this system field has retaining ownership", 12035 loc)); 12036 } 12037 } else { 12038 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12039 << T->isBlockPointerType() << Record->getTagKind(); 12040 } 12041 ARCErrReported = true; 12042 } 12043 } else if (getLangOpts().ObjC1 && 12044 getLangOpts().getGC() != LangOptions::NonGC && 12045 Record && !Record->hasObjectMember()) { 12046 if (FD->getType()->isObjCObjectPointerType() || 12047 FD->getType().isObjCGCStrong()) 12048 Record->setHasObjectMember(true); 12049 else if (Context.getAsArrayType(FD->getType())) { 12050 QualType BaseType = Context.getBaseElementType(FD->getType()); 12051 if (BaseType->isRecordType() && 12052 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12053 Record->setHasObjectMember(true); 12054 else if (BaseType->isObjCObjectPointerType() || 12055 BaseType.isObjCGCStrong()) 12056 Record->setHasObjectMember(true); 12057 } 12058 } 12059 if (Record && FD->getType().isVolatileQualified()) 12060 Record->setHasVolatileMember(true); 12061 // Keep track of the number of named members. 12062 if (FD->getIdentifier()) 12063 ++NumNamedMembers; 12064 } 12065 12066 // Okay, we successfully defined 'Record'. 12067 if (Record) { 12068 bool Completed = false; 12069 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12070 if (!CXXRecord->isInvalidDecl()) { 12071 // Set access bits correctly on the directly-declared conversions. 12072 for (CXXRecordDecl::conversion_iterator 12073 I = CXXRecord->conversion_begin(), 12074 E = CXXRecord->conversion_end(); I != E; ++I) 12075 I.setAccess((*I)->getAccess()); 12076 12077 if (!CXXRecord->isDependentType()) { 12078 if (CXXRecord->hasUserDeclaredDestructor()) { 12079 // Adjust user-defined destructor exception spec. 12080 if (getLangOpts().CPlusPlus11) 12081 AdjustDestructorExceptionSpec(CXXRecord, 12082 CXXRecord->getDestructor()); 12083 } 12084 12085 // Add any implicitly-declared members to this class. 12086 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12087 12088 // If we have virtual base classes, we may end up finding multiple 12089 // final overriders for a given virtual function. Check for this 12090 // problem now. 12091 if (CXXRecord->getNumVBases()) { 12092 CXXFinalOverriderMap FinalOverriders; 12093 CXXRecord->getFinalOverriders(FinalOverriders); 12094 12095 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12096 MEnd = FinalOverriders.end(); 12097 M != MEnd; ++M) { 12098 for (OverridingMethods::iterator SO = M->second.begin(), 12099 SOEnd = M->second.end(); 12100 SO != SOEnd; ++SO) { 12101 assert(SO->second.size() > 0 && 12102 "Virtual function without overridding functions?"); 12103 if (SO->second.size() == 1) 12104 continue; 12105 12106 // C++ [class.virtual]p2: 12107 // In a derived class, if a virtual member function of a base 12108 // class subobject has more than one final overrider the 12109 // program is ill-formed. 12110 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12111 << (const NamedDecl *)M->first << Record; 12112 Diag(M->first->getLocation(), 12113 diag::note_overridden_virtual_function); 12114 for (OverridingMethods::overriding_iterator 12115 OM = SO->second.begin(), 12116 OMEnd = SO->second.end(); 12117 OM != OMEnd; ++OM) 12118 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12119 << (const NamedDecl *)M->first << OM->Method->getParent(); 12120 12121 Record->setInvalidDecl(); 12122 } 12123 } 12124 CXXRecord->completeDefinition(&FinalOverriders); 12125 Completed = true; 12126 } 12127 } 12128 } 12129 } 12130 12131 if (!Completed) 12132 Record->completeDefinition(); 12133 12134 if (Record->hasAttrs()) { 12135 CheckAlignasUnderalignment(Record); 12136 12137 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12138 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12139 IA->getRange(), IA->getBestCase(), 12140 IA->getSemanticSpelling()); 12141 } 12142 12143 // Check if the structure/union declaration is a type that can have zero 12144 // size in C. For C this is a language extension, for C++ it may cause 12145 // compatibility problems. 12146 bool CheckForZeroSize; 12147 if (!getLangOpts().CPlusPlus) { 12148 CheckForZeroSize = true; 12149 } else { 12150 // For C++ filter out types that cannot be referenced in C code. 12151 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12152 CheckForZeroSize = 12153 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12154 !CXXRecord->isDependentType() && 12155 CXXRecord->isCLike(); 12156 } 12157 if (CheckForZeroSize) { 12158 bool ZeroSize = true; 12159 bool IsEmpty = true; 12160 unsigned NonBitFields = 0; 12161 for (RecordDecl::field_iterator I = Record->field_begin(), 12162 E = Record->field_end(); 12163 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12164 IsEmpty = false; 12165 if (I->isUnnamedBitfield()) { 12166 if (I->getBitWidthValue(Context) > 0) 12167 ZeroSize = false; 12168 } else { 12169 ++NonBitFields; 12170 QualType FieldType = I->getType(); 12171 if (FieldType->isIncompleteType() || 12172 !Context.getTypeSizeInChars(FieldType).isZero()) 12173 ZeroSize = false; 12174 } 12175 } 12176 12177 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12178 // allowed in C++, but warn if its declaration is inside 12179 // extern "C" block. 12180 if (ZeroSize) { 12181 Diag(RecLoc, getLangOpts().CPlusPlus ? 12182 diag::warn_zero_size_struct_union_in_extern_c : 12183 diag::warn_zero_size_struct_union_compat) 12184 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12185 } 12186 12187 // Structs without named members are extension in C (C99 6.7.2.1p7), 12188 // but are accepted by GCC. 12189 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12190 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12191 diag::ext_no_named_members_in_struct_union) 12192 << Record->isUnion(); 12193 } 12194 } 12195 } else { 12196 ObjCIvarDecl **ClsFields = 12197 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12198 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12199 ID->setEndOfDefinitionLoc(RBrac); 12200 // Add ivar's to class's DeclContext. 12201 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12202 ClsFields[i]->setLexicalDeclContext(ID); 12203 ID->addDecl(ClsFields[i]); 12204 } 12205 // Must enforce the rule that ivars in the base classes may not be 12206 // duplicates. 12207 if (ID->getSuperClass()) 12208 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12209 } else if (ObjCImplementationDecl *IMPDecl = 12210 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12211 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12212 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12213 // Ivar declared in @implementation never belongs to the implementation. 12214 // Only it is in implementation's lexical context. 12215 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12216 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12217 IMPDecl->setIvarLBraceLoc(LBrac); 12218 IMPDecl->setIvarRBraceLoc(RBrac); 12219 } else if (ObjCCategoryDecl *CDecl = 12220 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12221 // case of ivars in class extension; all other cases have been 12222 // reported as errors elsewhere. 12223 // FIXME. Class extension does not have a LocEnd field. 12224 // CDecl->setLocEnd(RBrac); 12225 // Add ivar's to class extension's DeclContext. 12226 // Diagnose redeclaration of private ivars. 12227 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12228 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12229 if (IDecl) { 12230 if (const ObjCIvarDecl *ClsIvar = 12231 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12232 Diag(ClsFields[i]->getLocation(), 12233 diag::err_duplicate_ivar_declaration); 12234 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12235 continue; 12236 } 12237 for (ObjCInterfaceDecl::known_extensions_iterator 12238 Ext = IDecl->known_extensions_begin(), 12239 ExtEnd = IDecl->known_extensions_end(); 12240 Ext != ExtEnd; ++Ext) { 12241 if (const ObjCIvarDecl *ClsExtIvar 12242 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12243 Diag(ClsFields[i]->getLocation(), 12244 diag::err_duplicate_ivar_declaration); 12245 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12246 continue; 12247 } 12248 } 12249 } 12250 ClsFields[i]->setLexicalDeclContext(CDecl); 12251 CDecl->addDecl(ClsFields[i]); 12252 } 12253 CDecl->setIvarLBraceLoc(LBrac); 12254 CDecl->setIvarRBraceLoc(RBrac); 12255 } 12256 } 12257 12258 if (Attr) 12259 ProcessDeclAttributeList(S, Record, Attr); 12260 } 12261 12262 /// \brief Determine whether the given integral value is representable within 12263 /// the given type T. 12264 static bool isRepresentableIntegerValue(ASTContext &Context, 12265 llvm::APSInt &Value, 12266 QualType T) { 12267 assert(T->isIntegralType(Context) && "Integral type required!"); 12268 unsigned BitWidth = Context.getIntWidth(T); 12269 12270 if (Value.isUnsigned() || Value.isNonNegative()) { 12271 if (T->isSignedIntegerOrEnumerationType()) 12272 --BitWidth; 12273 return Value.getActiveBits() <= BitWidth; 12274 } 12275 return Value.getMinSignedBits() <= BitWidth; 12276 } 12277 12278 // \brief Given an integral type, return the next larger integral type 12279 // (or a NULL type of no such type exists). 12280 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12281 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12282 // enum checking below. 12283 assert(T->isIntegralType(Context) && "Integral type required!"); 12284 const unsigned NumTypes = 4; 12285 QualType SignedIntegralTypes[NumTypes] = { 12286 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12287 }; 12288 QualType UnsignedIntegralTypes[NumTypes] = { 12289 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12290 Context.UnsignedLongLongTy 12291 }; 12292 12293 unsigned BitWidth = Context.getTypeSize(T); 12294 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12295 : UnsignedIntegralTypes; 12296 for (unsigned I = 0; I != NumTypes; ++I) 12297 if (Context.getTypeSize(Types[I]) > BitWidth) 12298 return Types[I]; 12299 12300 return QualType(); 12301 } 12302 12303 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12304 EnumConstantDecl *LastEnumConst, 12305 SourceLocation IdLoc, 12306 IdentifierInfo *Id, 12307 Expr *Val) { 12308 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12309 llvm::APSInt EnumVal(IntWidth); 12310 QualType EltTy; 12311 12312 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12313 Val = 0; 12314 12315 if (Val) 12316 Val = DefaultLvalueConversion(Val).take(); 12317 12318 if (Val) { 12319 if (Enum->isDependentType() || Val->isTypeDependent()) 12320 EltTy = Context.DependentTy; 12321 else { 12322 SourceLocation ExpLoc; 12323 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12324 !getLangOpts().MSVCCompat) { 12325 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12326 // constant-expression in the enumerator-definition shall be a converted 12327 // constant expression of the underlying type. 12328 EltTy = Enum->getIntegerType(); 12329 ExprResult Converted = 12330 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12331 CCEK_Enumerator); 12332 if (Converted.isInvalid()) 12333 Val = 0; 12334 else 12335 Val = Converted.take(); 12336 } else if (!Val->isValueDependent() && 12337 !(Val = VerifyIntegerConstantExpression(Val, 12338 &EnumVal).take())) { 12339 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12340 } else { 12341 if (Enum->isFixed()) { 12342 EltTy = Enum->getIntegerType(); 12343 12344 // In Obj-C and Microsoft mode, require the enumeration value to be 12345 // representable in the underlying type of the enumeration. In C++11, 12346 // we perform a non-narrowing conversion as part of converted constant 12347 // expression checking. 12348 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12349 if (getLangOpts().MSVCCompat) { 12350 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12351 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12352 } else 12353 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12354 } else 12355 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12356 } else if (getLangOpts().CPlusPlus) { 12357 // C++11 [dcl.enum]p5: 12358 // If the underlying type is not fixed, the type of each enumerator 12359 // is the type of its initializing value: 12360 // - If an initializer is specified for an enumerator, the 12361 // initializing value has the same type as the expression. 12362 EltTy = Val->getType(); 12363 } else { 12364 // C99 6.7.2.2p2: 12365 // The expression that defines the value of an enumeration constant 12366 // shall be an integer constant expression that has a value 12367 // representable as an int. 12368 12369 // Complain if the value is not representable in an int. 12370 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12371 Diag(IdLoc, diag::ext_enum_value_not_int) 12372 << EnumVal.toString(10) << Val->getSourceRange() 12373 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12374 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12375 // Force the type of the expression to 'int'. 12376 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12377 } 12378 EltTy = Val->getType(); 12379 } 12380 } 12381 } 12382 } 12383 12384 if (!Val) { 12385 if (Enum->isDependentType()) 12386 EltTy = Context.DependentTy; 12387 else if (!LastEnumConst) { 12388 // C++0x [dcl.enum]p5: 12389 // If the underlying type is not fixed, the type of each enumerator 12390 // is the type of its initializing value: 12391 // - If no initializer is specified for the first enumerator, the 12392 // initializing value has an unspecified integral type. 12393 // 12394 // GCC uses 'int' for its unspecified integral type, as does 12395 // C99 6.7.2.2p3. 12396 if (Enum->isFixed()) { 12397 EltTy = Enum->getIntegerType(); 12398 } 12399 else { 12400 EltTy = Context.IntTy; 12401 } 12402 } else { 12403 // Assign the last value + 1. 12404 EnumVal = LastEnumConst->getInitVal(); 12405 ++EnumVal; 12406 EltTy = LastEnumConst->getType(); 12407 12408 // Check for overflow on increment. 12409 if (EnumVal < LastEnumConst->getInitVal()) { 12410 // C++0x [dcl.enum]p5: 12411 // If the underlying type is not fixed, the type of each enumerator 12412 // is the type of its initializing value: 12413 // 12414 // - Otherwise the type of the initializing value is the same as 12415 // the type of the initializing value of the preceding enumerator 12416 // unless the incremented value is not representable in that type, 12417 // in which case the type is an unspecified integral type 12418 // sufficient to contain the incremented value. If no such type 12419 // exists, the program is ill-formed. 12420 QualType T = getNextLargerIntegralType(Context, EltTy); 12421 if (T.isNull() || Enum->isFixed()) { 12422 // There is no integral type larger enough to represent this 12423 // value. Complain, then allow the value to wrap around. 12424 EnumVal = LastEnumConst->getInitVal(); 12425 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12426 ++EnumVal; 12427 if (Enum->isFixed()) 12428 // When the underlying type is fixed, this is ill-formed. 12429 Diag(IdLoc, diag::err_enumerator_wrapped) 12430 << EnumVal.toString(10) 12431 << EltTy; 12432 else 12433 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 12434 << EnumVal.toString(10); 12435 } else { 12436 EltTy = T; 12437 } 12438 12439 // Retrieve the last enumerator's value, extent that type to the 12440 // type that is supposed to be large enough to represent the incremented 12441 // value, then increment. 12442 EnumVal = LastEnumConst->getInitVal(); 12443 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12444 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12445 ++EnumVal; 12446 12447 // If we're not in C++, diagnose the overflow of enumerator values, 12448 // which in C99 means that the enumerator value is not representable in 12449 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12450 // permits enumerator values that are representable in some larger 12451 // integral type. 12452 if (!getLangOpts().CPlusPlus && !T.isNull()) 12453 Diag(IdLoc, diag::warn_enum_value_overflow); 12454 } else if (!getLangOpts().CPlusPlus && 12455 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12456 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12457 Diag(IdLoc, diag::ext_enum_value_not_int) 12458 << EnumVal.toString(10) << 1; 12459 } 12460 } 12461 } 12462 12463 if (!EltTy->isDependentType()) { 12464 // Make the enumerator value match the signedness and size of the 12465 // enumerator's type. 12466 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12467 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12468 } 12469 12470 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12471 Val, EnumVal); 12472 } 12473 12474 12475 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12476 SourceLocation IdLoc, IdentifierInfo *Id, 12477 AttributeList *Attr, 12478 SourceLocation EqualLoc, Expr *Val) { 12479 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12480 EnumConstantDecl *LastEnumConst = 12481 cast_or_null<EnumConstantDecl>(lastEnumConst); 12482 12483 // The scope passed in may not be a decl scope. Zip up the scope tree until 12484 // we find one that is. 12485 S = getNonFieldDeclScope(S); 12486 12487 // Verify that there isn't already something declared with this name in this 12488 // scope. 12489 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12490 ForRedeclaration); 12491 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12492 // Maybe we will complain about the shadowed template parameter. 12493 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12494 // Just pretend that we didn't see the previous declaration. 12495 PrevDecl = 0; 12496 } 12497 12498 if (PrevDecl) { 12499 // When in C++, we may get a TagDecl with the same name; in this case the 12500 // enum constant will 'hide' the tag. 12501 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12502 "Received TagDecl when not in C++!"); 12503 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12504 if (isa<EnumConstantDecl>(PrevDecl)) 12505 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12506 else 12507 Diag(IdLoc, diag::err_redefinition) << Id; 12508 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12509 return 0; 12510 } 12511 } 12512 12513 // C++ [class.mem]p15: 12514 // If T is the name of a class, then each of the following shall have a name 12515 // different from T: 12516 // - every enumerator of every member of class T that is an unscoped 12517 // enumerated type 12518 if (CXXRecordDecl *Record 12519 = dyn_cast<CXXRecordDecl>( 12520 TheEnumDecl->getDeclContext()->getRedeclContext())) 12521 if (!TheEnumDecl->isScoped() && 12522 Record->getIdentifier() && Record->getIdentifier() == Id) 12523 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12524 12525 EnumConstantDecl *New = 12526 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12527 12528 if (New) { 12529 // Process attributes. 12530 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12531 12532 // Register this decl in the current scope stack. 12533 New->setAccess(TheEnumDecl->getAccess()); 12534 PushOnScopeChains(New, S); 12535 } 12536 12537 ActOnDocumentableDecl(New); 12538 12539 return New; 12540 } 12541 12542 // Returns true when the enum initial expression does not trigger the 12543 // duplicate enum warning. A few common cases are exempted as follows: 12544 // Element2 = Element1 12545 // Element2 = Element1 + 1 12546 // Element2 = Element1 - 1 12547 // Where Element2 and Element1 are from the same enum. 12548 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12549 Expr *InitExpr = ECD->getInitExpr(); 12550 if (!InitExpr) 12551 return true; 12552 InitExpr = InitExpr->IgnoreImpCasts(); 12553 12554 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12555 if (!BO->isAdditiveOp()) 12556 return true; 12557 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12558 if (!IL) 12559 return true; 12560 if (IL->getValue() != 1) 12561 return true; 12562 12563 InitExpr = BO->getLHS(); 12564 } 12565 12566 // This checks if the elements are from the same enum. 12567 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12568 if (!DRE) 12569 return true; 12570 12571 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12572 if (!EnumConstant) 12573 return true; 12574 12575 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12576 Enum) 12577 return true; 12578 12579 return false; 12580 } 12581 12582 struct DupKey { 12583 int64_t val; 12584 bool isTombstoneOrEmptyKey; 12585 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12586 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12587 }; 12588 12589 static DupKey GetDupKey(const llvm::APSInt& Val) { 12590 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12591 false); 12592 } 12593 12594 struct DenseMapInfoDupKey { 12595 static DupKey getEmptyKey() { return DupKey(0, true); } 12596 static DupKey getTombstoneKey() { return DupKey(1, true); } 12597 static unsigned getHashValue(const DupKey Key) { 12598 return (unsigned)(Key.val * 37); 12599 } 12600 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12601 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12602 LHS.val == RHS.val; 12603 } 12604 }; 12605 12606 // Emits a warning when an element is implicitly set a value that 12607 // a previous element has already been set to. 12608 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12609 EnumDecl *Enum, 12610 QualType EnumType) { 12611 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12612 Enum->getLocation()) == 12613 DiagnosticsEngine::Ignored) 12614 return; 12615 // Avoid anonymous enums 12616 if (!Enum->getIdentifier()) 12617 return; 12618 12619 // Only check for small enums. 12620 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12621 return; 12622 12623 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12624 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12625 12626 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12627 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12628 ValueToVectorMap; 12629 12630 DuplicatesVector DupVector; 12631 ValueToVectorMap EnumMap; 12632 12633 // Populate the EnumMap with all values represented by enum constants without 12634 // an initialier. 12635 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12636 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12637 12638 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12639 // this constant. Skip this enum since it may be ill-formed. 12640 if (!ECD) { 12641 return; 12642 } 12643 12644 if (ECD->getInitExpr()) 12645 continue; 12646 12647 DupKey Key = GetDupKey(ECD->getInitVal()); 12648 DeclOrVector &Entry = EnumMap[Key]; 12649 12650 // First time encountering this value. 12651 if (Entry.isNull()) 12652 Entry = ECD; 12653 } 12654 12655 // Create vectors for any values that has duplicates. 12656 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12657 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12658 if (!ValidDuplicateEnum(ECD, Enum)) 12659 continue; 12660 12661 DupKey Key = GetDupKey(ECD->getInitVal()); 12662 12663 DeclOrVector& Entry = EnumMap[Key]; 12664 if (Entry.isNull()) 12665 continue; 12666 12667 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12668 // Ensure constants are different. 12669 if (D == ECD) 12670 continue; 12671 12672 // Create new vector and push values onto it. 12673 ECDVector *Vec = new ECDVector(); 12674 Vec->push_back(D); 12675 Vec->push_back(ECD); 12676 12677 // Update entry to point to the duplicates vector. 12678 Entry = Vec; 12679 12680 // Store the vector somewhere we can consult later for quick emission of 12681 // diagnostics. 12682 DupVector.push_back(Vec); 12683 continue; 12684 } 12685 12686 ECDVector *Vec = Entry.get<ECDVector*>(); 12687 // Make sure constants are not added more than once. 12688 if (*Vec->begin() == ECD) 12689 continue; 12690 12691 Vec->push_back(ECD); 12692 } 12693 12694 // Emit diagnostics. 12695 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12696 DupVectorEnd = DupVector.end(); 12697 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12698 ECDVector *Vec = *DupVectorIter; 12699 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12700 12701 // Emit warning for one enum constant. 12702 ECDVector::iterator I = Vec->begin(); 12703 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12704 << (*I)->getName() << (*I)->getInitVal().toString(10) 12705 << (*I)->getSourceRange(); 12706 ++I; 12707 12708 // Emit one note for each of the remaining enum constants with 12709 // the same value. 12710 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12711 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12712 << (*I)->getName() << (*I)->getInitVal().toString(10) 12713 << (*I)->getSourceRange(); 12714 delete Vec; 12715 } 12716 } 12717 12718 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12719 SourceLocation RBraceLoc, Decl *EnumDeclX, 12720 ArrayRef<Decl *> Elements, 12721 Scope *S, AttributeList *Attr) { 12722 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12723 QualType EnumType = Context.getTypeDeclType(Enum); 12724 12725 if (Attr) 12726 ProcessDeclAttributeList(S, Enum, Attr); 12727 12728 if (Enum->isDependentType()) { 12729 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12730 EnumConstantDecl *ECD = 12731 cast_or_null<EnumConstantDecl>(Elements[i]); 12732 if (!ECD) continue; 12733 12734 ECD->setType(EnumType); 12735 } 12736 12737 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12738 return; 12739 } 12740 12741 // TODO: If the result value doesn't fit in an int, it must be a long or long 12742 // long value. ISO C does not support this, but GCC does as an extension, 12743 // emit a warning. 12744 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12745 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12746 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12747 12748 // Verify that all the values are okay, compute the size of the values, and 12749 // reverse the list. 12750 unsigned NumNegativeBits = 0; 12751 unsigned NumPositiveBits = 0; 12752 12753 // Keep track of whether all elements have type int. 12754 bool AllElementsInt = true; 12755 12756 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12757 EnumConstantDecl *ECD = 12758 cast_or_null<EnumConstantDecl>(Elements[i]); 12759 if (!ECD) continue; // Already issued a diagnostic. 12760 12761 const llvm::APSInt &InitVal = ECD->getInitVal(); 12762 12763 // Keep track of the size of positive and negative values. 12764 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12765 NumPositiveBits = std::max(NumPositiveBits, 12766 (unsigned)InitVal.getActiveBits()); 12767 else 12768 NumNegativeBits = std::max(NumNegativeBits, 12769 (unsigned)InitVal.getMinSignedBits()); 12770 12771 // Keep track of whether every enum element has type int (very commmon). 12772 if (AllElementsInt) 12773 AllElementsInt = ECD->getType() == Context.IntTy; 12774 } 12775 12776 // Figure out the type that should be used for this enum. 12777 QualType BestType; 12778 unsigned BestWidth; 12779 12780 // C++0x N3000 [conv.prom]p3: 12781 // An rvalue of an unscoped enumeration type whose underlying 12782 // type is not fixed can be converted to an rvalue of the first 12783 // of the following types that can represent all the values of 12784 // the enumeration: int, unsigned int, long int, unsigned long 12785 // int, long long int, or unsigned long long int. 12786 // C99 6.4.4.3p2: 12787 // An identifier declared as an enumeration constant has type int. 12788 // The C99 rule is modified by a gcc extension 12789 QualType BestPromotionType; 12790 12791 bool Packed = Enum->hasAttr<PackedAttr>(); 12792 // -fshort-enums is the equivalent to specifying the packed attribute on all 12793 // enum definitions. 12794 if (LangOpts.ShortEnums) 12795 Packed = true; 12796 12797 if (Enum->isFixed()) { 12798 BestType = Enum->getIntegerType(); 12799 if (BestType->isPromotableIntegerType()) 12800 BestPromotionType = Context.getPromotedIntegerType(BestType); 12801 else 12802 BestPromotionType = BestType; 12803 // We don't need to set BestWidth, because BestType is going to be the type 12804 // of the enumerators, but we do anyway because otherwise some compilers 12805 // warn that it might be used uninitialized. 12806 BestWidth = CharWidth; 12807 } 12808 else if (NumNegativeBits) { 12809 // If there is a negative value, figure out the smallest integer type (of 12810 // int/long/longlong) that fits. 12811 // If it's packed, check also if it fits a char or a short. 12812 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12813 BestType = Context.SignedCharTy; 12814 BestWidth = CharWidth; 12815 } else if (Packed && NumNegativeBits <= ShortWidth && 12816 NumPositiveBits < ShortWidth) { 12817 BestType = Context.ShortTy; 12818 BestWidth = ShortWidth; 12819 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12820 BestType = Context.IntTy; 12821 BestWidth = IntWidth; 12822 } else { 12823 BestWidth = Context.getTargetInfo().getLongWidth(); 12824 12825 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12826 BestType = Context.LongTy; 12827 } else { 12828 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12829 12830 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12831 Diag(Enum->getLocation(), diag::ext_enum_too_large); 12832 BestType = Context.LongLongTy; 12833 } 12834 } 12835 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12836 } else { 12837 // If there is no negative value, figure out the smallest type that fits 12838 // all of the enumerator values. 12839 // If it's packed, check also if it fits a char or a short. 12840 if (Packed && NumPositiveBits <= CharWidth) { 12841 BestType = Context.UnsignedCharTy; 12842 BestPromotionType = Context.IntTy; 12843 BestWidth = CharWidth; 12844 } else if (Packed && NumPositiveBits <= ShortWidth) { 12845 BestType = Context.UnsignedShortTy; 12846 BestPromotionType = Context.IntTy; 12847 BestWidth = ShortWidth; 12848 } else if (NumPositiveBits <= IntWidth) { 12849 BestType = Context.UnsignedIntTy; 12850 BestWidth = IntWidth; 12851 BestPromotionType 12852 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12853 ? Context.UnsignedIntTy : Context.IntTy; 12854 } else if (NumPositiveBits <= 12855 (BestWidth = Context.getTargetInfo().getLongWidth())) { 12856 BestType = Context.UnsignedLongTy; 12857 BestPromotionType 12858 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12859 ? Context.UnsignedLongTy : Context.LongTy; 12860 } else { 12861 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12862 assert(NumPositiveBits <= BestWidth && 12863 "How could an initializer get larger than ULL?"); 12864 BestType = Context.UnsignedLongLongTy; 12865 BestPromotionType 12866 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12867 ? Context.UnsignedLongLongTy : Context.LongLongTy; 12868 } 12869 } 12870 12871 // Loop over all of the enumerator constants, changing their types to match 12872 // the type of the enum if needed. 12873 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12874 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12875 if (!ECD) continue; // Already issued a diagnostic. 12876 12877 // Standard C says the enumerators have int type, but we allow, as an 12878 // extension, the enumerators to be larger than int size. If each 12879 // enumerator value fits in an int, type it as an int, otherwise type it the 12880 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 12881 // that X has type 'int', not 'unsigned'. 12882 12883 // Determine whether the value fits into an int. 12884 llvm::APSInt InitVal = ECD->getInitVal(); 12885 12886 // If it fits into an integer type, force it. Otherwise force it to match 12887 // the enum decl type. 12888 QualType NewTy; 12889 unsigned NewWidth; 12890 bool NewSign; 12891 if (!getLangOpts().CPlusPlus && 12892 !Enum->isFixed() && 12893 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 12894 NewTy = Context.IntTy; 12895 NewWidth = IntWidth; 12896 NewSign = true; 12897 } else if (ECD->getType() == BestType) { 12898 // Already the right type! 12899 if (getLangOpts().CPlusPlus) 12900 // C++ [dcl.enum]p4: Following the closing brace of an 12901 // enum-specifier, each enumerator has the type of its 12902 // enumeration. 12903 ECD->setType(EnumType); 12904 continue; 12905 } else { 12906 NewTy = BestType; 12907 NewWidth = BestWidth; 12908 NewSign = BestType->isSignedIntegerOrEnumerationType(); 12909 } 12910 12911 // Adjust the APSInt value. 12912 InitVal = InitVal.extOrTrunc(NewWidth); 12913 InitVal.setIsSigned(NewSign); 12914 ECD->setInitVal(InitVal); 12915 12916 // Adjust the Expr initializer and type. 12917 if (ECD->getInitExpr() && 12918 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 12919 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 12920 CK_IntegralCast, 12921 ECD->getInitExpr(), 12922 /*base paths*/ 0, 12923 VK_RValue)); 12924 if (getLangOpts().CPlusPlus) 12925 // C++ [dcl.enum]p4: Following the closing brace of an 12926 // enum-specifier, each enumerator has the type of its 12927 // enumeration. 12928 ECD->setType(EnumType); 12929 else 12930 ECD->setType(NewTy); 12931 } 12932 12933 Enum->completeDefinition(BestType, BestPromotionType, 12934 NumPositiveBits, NumNegativeBits); 12935 12936 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 12937 12938 // Now that the enum type is defined, ensure it's not been underaligned. 12939 if (Enum->hasAttrs()) 12940 CheckAlignasUnderalignment(Enum); 12941 } 12942 12943 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 12944 SourceLocation StartLoc, 12945 SourceLocation EndLoc) { 12946 StringLiteral *AsmString = cast<StringLiteral>(expr); 12947 12948 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 12949 AsmString, StartLoc, 12950 EndLoc); 12951 CurContext->addDecl(New); 12952 return New; 12953 } 12954 12955 static void checkModuleImportContext(Sema &S, Module *M, 12956 SourceLocation ImportLoc, 12957 DeclContext *DC) { 12958 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 12959 switch (LSD->getLanguage()) { 12960 case LinkageSpecDecl::lang_c: 12961 if (!M->IsExternC) { 12962 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 12963 << M->getFullModuleName(); 12964 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 12965 return; 12966 } 12967 break; 12968 case LinkageSpecDecl::lang_cxx: 12969 break; 12970 } 12971 DC = LSD->getParent(); 12972 } 12973 12974 while (isa<LinkageSpecDecl>(DC)) 12975 DC = DC->getParent(); 12976 if (!isa<TranslationUnitDecl>(DC)) { 12977 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 12978 << M->getFullModuleName() << DC; 12979 S.Diag(cast<Decl>(DC)->getLocStart(), 12980 diag::note_module_import_not_at_top_level) 12981 << DC; 12982 } 12983 } 12984 12985 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 12986 SourceLocation ImportLoc, 12987 ModuleIdPath Path) { 12988 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 12989 Module::AllVisible, 12990 /*IsIncludeDirective=*/false); 12991 if (!Mod) 12992 return true; 12993 12994 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 12995 12996 SmallVector<SourceLocation, 2> IdentifierLocs; 12997 Module *ModCheck = Mod; 12998 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 12999 // If we've run out of module parents, just drop the remaining identifiers. 13000 // We need the length to be consistent. 13001 if (!ModCheck) 13002 break; 13003 ModCheck = ModCheck->Parent; 13004 13005 IdentifierLocs.push_back(Path[I].second); 13006 } 13007 13008 ImportDecl *Import = ImportDecl::Create(Context, 13009 Context.getTranslationUnitDecl(), 13010 AtLoc.isValid()? AtLoc : ImportLoc, 13011 Mod, IdentifierLocs); 13012 Context.getTranslationUnitDecl()->addDecl(Import); 13013 return Import; 13014 } 13015 13016 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13017 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13018 13019 // FIXME: Should we synthesize an ImportDecl here? 13020 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13021 /*Complain=*/true); 13022 } 13023 13024 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 13025 // Create the implicit import declaration. 13026 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13027 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13028 Loc, Mod, Loc); 13029 TU->addDecl(ImportD); 13030 Consumer.HandleImplicitImportDecl(ImportD); 13031 13032 // Make the module visible. 13033 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13034 /*Complain=*/false); 13035 } 13036 13037 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13038 IdentifierInfo* AliasName, 13039 SourceLocation PragmaLoc, 13040 SourceLocation NameLoc, 13041 SourceLocation AliasNameLoc) { 13042 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13043 LookupOrdinaryName); 13044 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13045 AliasName->getName(), 0); 13046 13047 if (PrevDecl) 13048 PrevDecl->addAttr(Attr); 13049 else 13050 (void)ExtnameUndeclaredIdentifiers.insert( 13051 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13052 } 13053 13054 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13055 SourceLocation PragmaLoc, 13056 SourceLocation NameLoc) { 13057 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13058 13059 if (PrevDecl) { 13060 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13061 } else { 13062 (void)WeakUndeclaredIdentifiers.insert( 13063 std::pair<IdentifierInfo*,WeakInfo> 13064 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 13065 } 13066 } 13067 13068 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13069 IdentifierInfo* AliasName, 13070 SourceLocation PragmaLoc, 13071 SourceLocation NameLoc, 13072 SourceLocation AliasNameLoc) { 13073 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13074 LookupOrdinaryName); 13075 WeakInfo W = WeakInfo(Name, NameLoc); 13076 13077 if (PrevDecl) { 13078 if (!PrevDecl->hasAttr<AliasAttr>()) 13079 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13080 DeclApplyPragmaWeak(TUScope, ND, W); 13081 } else { 13082 (void)WeakUndeclaredIdentifiers.insert( 13083 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13084 } 13085 } 13086 13087 Decl *Sema::getObjCDeclContext() const { 13088 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13089 } 13090 13091 AvailabilityResult Sema::getCurContextAvailability() const { 13092 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13093 // If we are within an Objective-C method, we should consult 13094 // both the availability of the method as well as the 13095 // enclosing class. If the class is (say) deprecated, 13096 // the entire method is considered deprecated from the 13097 // purpose of checking if the current context is deprecated. 13098 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13099 AvailabilityResult R = MD->getAvailability(); 13100 if (R != AR_Available) 13101 return R; 13102 D = MD->getClassInterface(); 13103 } 13104 // If we are within an Objective-c @implementation, it 13105 // gets the same availability context as the @interface. 13106 else if (const ObjCImplementationDecl *ID = 13107 dyn_cast<ObjCImplementationDecl>(D)) { 13108 D = ID->getClassInterface(); 13109 } 13110 return D->getAvailability(); 13111 } 13112