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 (auto *I : Old->specific_attrs<AlignedAttr>()) { 1829 // FIXME: We have no way of representing inherited dependent alignments 1830 // in a case like: 1831 // template<int A, int B> struct alignas(A) X; 1832 // template<int A, int B> struct alignas(B) X {}; 1833 // For now, we just ignore any alignas attributes which are not on the 1834 // definition in such a case. 1835 if (I->isAlignmentDependent()) 1836 return false; 1837 1838 if (I->isAlignas()) 1839 OldAlignasAttr = I; 1840 1841 unsigned Align = I->getAlignment(S.Context); 1842 if (Align > OldAlign) { 1843 OldAlign = Align; 1844 OldStrictestAlignAttr = I; 1845 } 1846 } 1847 1848 // Look for alignas attributes on New. 1849 AlignedAttr *NewAlignasAttr = 0; 1850 unsigned NewAlign = 0; 1851 for (auto *I : New->specific_attrs<AlignedAttr>()) { 1852 if (I->isAlignmentDependent()) 1853 return false; 1854 1855 if (I->isAlignas()) 1856 NewAlignasAttr = I; 1857 1858 unsigned Align = I->getAlignment(S.Context); 1859 if (Align > NewAlign) 1860 NewAlign = Align; 1861 } 1862 1863 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1864 // Both declarations have 'alignas' attributes. We require them to match. 1865 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1866 // fall short. (If two declarations both have alignas, they must both match 1867 // every definition, and so must match each other if there is a definition.) 1868 1869 // If either declaration only contains 'alignas(0)' specifiers, then it 1870 // specifies the natural alignment for the type. 1871 if (OldAlign == 0 || NewAlign == 0) { 1872 QualType Ty; 1873 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1874 Ty = VD->getType(); 1875 else 1876 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1877 1878 if (OldAlign == 0) 1879 OldAlign = S.Context.getTypeAlign(Ty); 1880 if (NewAlign == 0) 1881 NewAlign = S.Context.getTypeAlign(Ty); 1882 } 1883 1884 if (OldAlign != NewAlign) { 1885 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1886 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1887 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1888 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1889 } 1890 } 1891 1892 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1893 // C++11 [dcl.align]p6: 1894 // if any declaration of an entity has an alignment-specifier, 1895 // every defining declaration of that entity shall specify an 1896 // equivalent alignment. 1897 // C11 6.7.5/7: 1898 // If the definition of an object does not have an alignment 1899 // specifier, any other declaration of that object shall also 1900 // have no alignment specifier. 1901 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1902 << OldAlignasAttr; 1903 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1904 << OldAlignasAttr; 1905 } 1906 1907 bool AnyAdded = false; 1908 1909 // Ensure we have an attribute representing the strictest alignment. 1910 if (OldAlign > NewAlign) { 1911 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1912 Clone->setInherited(true); 1913 New->addAttr(Clone); 1914 AnyAdded = true; 1915 } 1916 1917 // Ensure we have an alignas attribute if the old declaration had one. 1918 if (OldAlignasAttr && !NewAlignasAttr && 1919 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1920 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1921 Clone->setInherited(true); 1922 New->addAttr(Clone); 1923 AnyAdded = true; 1924 } 1925 1926 return AnyAdded; 1927 } 1928 1929 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1930 bool Override) { 1931 InheritableAttr *NewAttr = NULL; 1932 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1933 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1934 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1935 AA->getIntroduced(), AA->getDeprecated(), 1936 AA->getObsoleted(), AA->getUnavailable(), 1937 AA->getMessage(), Override, 1938 AttrSpellingListIndex); 1939 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1940 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1941 AttrSpellingListIndex); 1942 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1943 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1944 AttrSpellingListIndex); 1945 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1946 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1947 AttrSpellingListIndex); 1948 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1949 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1950 AttrSpellingListIndex); 1951 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1952 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1953 FA->getFormatIdx(), FA->getFirstArg(), 1954 AttrSpellingListIndex); 1955 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1956 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1957 AttrSpellingListIndex); 1958 else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr)) 1959 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 1960 AttrSpellingListIndex, 1961 IA->getSemanticSpelling()); 1962 else if (isa<AlignedAttr>(Attr)) 1963 // AlignedAttrs are handled separately, because we need to handle all 1964 // such attributes on a declaration at the same time. 1965 NewAttr = 0; 1966 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 1967 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1968 1969 if (NewAttr) { 1970 NewAttr->setInherited(true); 1971 D->addAttr(NewAttr); 1972 return true; 1973 } 1974 1975 return false; 1976 } 1977 1978 static const Decl *getDefinition(const Decl *D) { 1979 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1980 return TD->getDefinition(); 1981 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1982 const VarDecl *Def = VD->getDefinition(); 1983 if (Def) 1984 return Def; 1985 return VD->getActingDefinition(); 1986 } 1987 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1988 const FunctionDecl* Def; 1989 if (FD->isDefined(Def)) 1990 return Def; 1991 } 1992 return NULL; 1993 } 1994 1995 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 1996 for (const auto *Attribute : D->attrs()) 1997 if (Attribute->getKind() == Kind) 1998 return true; 1999 return false; 2000 } 2001 2002 /// checkNewAttributesAfterDef - If we already have a definition, check that 2003 /// there are no new attributes in this declaration. 2004 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2005 if (!New->hasAttrs()) 2006 return; 2007 2008 const Decl *Def = getDefinition(Old); 2009 if (!Def || Def == New) 2010 return; 2011 2012 AttrVec &NewAttributes = New->getAttrs(); 2013 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2014 const Attr *NewAttribute = NewAttributes[I]; 2015 2016 if (isa<AliasAttr>(NewAttribute)) { 2017 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2018 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2019 else { 2020 VarDecl *VD = cast<VarDecl>(New); 2021 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2022 VarDecl::TentativeDefinition 2023 ? diag::err_alias_after_tentative 2024 : diag::err_redefinition; 2025 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2026 S.Diag(Def->getLocation(), diag::note_previous_definition); 2027 VD->setInvalidDecl(); 2028 } 2029 ++I; 2030 continue; 2031 } 2032 2033 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2034 // Tentative definitions are only interesting for the alias check above. 2035 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2036 ++I; 2037 continue; 2038 } 2039 } 2040 2041 if (hasAttribute(Def, NewAttribute->getKind())) { 2042 ++I; 2043 continue; // regular attr merging will take care of validating this. 2044 } 2045 2046 if (isa<C11NoReturnAttr>(NewAttribute)) { 2047 // C's _Noreturn is allowed to be added to a function after it is defined. 2048 ++I; 2049 continue; 2050 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2051 if (AA->isAlignas()) { 2052 // C++11 [dcl.align]p6: 2053 // if any declaration of an entity has an alignment-specifier, 2054 // every defining declaration of that entity shall specify an 2055 // equivalent alignment. 2056 // C11 6.7.5/7: 2057 // If the definition of an object does not have an alignment 2058 // specifier, any other declaration of that object shall also 2059 // have no alignment specifier. 2060 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2061 << AA; 2062 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2063 << AA; 2064 NewAttributes.erase(NewAttributes.begin() + I); 2065 --E; 2066 continue; 2067 } 2068 } 2069 2070 S.Diag(NewAttribute->getLocation(), 2071 diag::warn_attribute_precede_definition); 2072 S.Diag(Def->getLocation(), diag::note_previous_definition); 2073 NewAttributes.erase(NewAttributes.begin() + I); 2074 --E; 2075 } 2076 } 2077 2078 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2079 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2080 AvailabilityMergeKind AMK) { 2081 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2082 UsedAttr *NewAttr = OldAttr->clone(Context); 2083 NewAttr->setInherited(true); 2084 New->addAttr(NewAttr); 2085 } 2086 2087 if (!Old->hasAttrs() && !New->hasAttrs()) 2088 return; 2089 2090 // attributes declared post-definition are currently ignored 2091 checkNewAttributesAfterDef(*this, New, Old); 2092 2093 if (!Old->hasAttrs()) 2094 return; 2095 2096 bool foundAny = New->hasAttrs(); 2097 2098 // Ensure that any moving of objects within the allocated map is done before 2099 // we process them. 2100 if (!foundAny) New->setAttrs(AttrVec()); 2101 2102 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2103 bool Override = false; 2104 // Ignore deprecated/unavailable/availability attributes if requested. 2105 if (isa<DeprecatedAttr>(I) || 2106 isa<UnavailableAttr>(I) || 2107 isa<AvailabilityAttr>(I)) { 2108 switch (AMK) { 2109 case AMK_None: 2110 continue; 2111 2112 case AMK_Redeclaration: 2113 break; 2114 2115 case AMK_Override: 2116 Override = true; 2117 break; 2118 } 2119 } 2120 2121 // Already handled. 2122 if (isa<UsedAttr>(I)) 2123 continue; 2124 2125 if (mergeDeclAttribute(*this, New, I, Override)) 2126 foundAny = true; 2127 } 2128 2129 if (mergeAlignedAttrs(*this, New, Old)) 2130 foundAny = true; 2131 2132 if (!foundAny) New->dropAttrs(); 2133 } 2134 2135 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2136 /// to the new one. 2137 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2138 const ParmVarDecl *oldDecl, 2139 Sema &S) { 2140 // C++11 [dcl.attr.depend]p2: 2141 // The first declaration of a function shall specify the 2142 // carries_dependency attribute for its declarator-id if any declaration 2143 // of the function specifies the carries_dependency attribute. 2144 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2145 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2146 S.Diag(CDA->getLocation(), 2147 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2148 // Find the first declaration of the parameter. 2149 // FIXME: Should we build redeclaration chains for function parameters? 2150 const FunctionDecl *FirstFD = 2151 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2152 const ParmVarDecl *FirstVD = 2153 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2154 S.Diag(FirstVD->getLocation(), 2155 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2156 } 2157 2158 if (!oldDecl->hasAttrs()) 2159 return; 2160 2161 bool foundAny = newDecl->hasAttrs(); 2162 2163 // Ensure that any moving of objects within the allocated map is 2164 // done before we process them. 2165 if (!foundAny) newDecl->setAttrs(AttrVec()); 2166 2167 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2168 if (!DeclHasAttr(newDecl, I)) { 2169 InheritableAttr *newAttr = 2170 cast<InheritableParamAttr>(I->clone(S.Context)); 2171 newAttr->setInherited(true); 2172 newDecl->addAttr(newAttr); 2173 foundAny = true; 2174 } 2175 } 2176 2177 if (!foundAny) newDecl->dropAttrs(); 2178 } 2179 2180 namespace { 2181 2182 /// Used in MergeFunctionDecl to keep track of function parameters in 2183 /// C. 2184 struct GNUCompatibleParamWarning { 2185 ParmVarDecl *OldParm; 2186 ParmVarDecl *NewParm; 2187 QualType PromotedType; 2188 }; 2189 2190 } 2191 2192 /// getSpecialMember - get the special member enum for a method. 2193 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2194 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2195 if (Ctor->isDefaultConstructor()) 2196 return Sema::CXXDefaultConstructor; 2197 2198 if (Ctor->isCopyConstructor()) 2199 return Sema::CXXCopyConstructor; 2200 2201 if (Ctor->isMoveConstructor()) 2202 return Sema::CXXMoveConstructor; 2203 } else if (isa<CXXDestructorDecl>(MD)) { 2204 return Sema::CXXDestructor; 2205 } else if (MD->isCopyAssignmentOperator()) { 2206 return Sema::CXXCopyAssignment; 2207 } else if (MD->isMoveAssignmentOperator()) { 2208 return Sema::CXXMoveAssignment; 2209 } 2210 2211 return Sema::CXXInvalid; 2212 } 2213 2214 /// canRedefineFunction - checks if a function can be redefined. Currently, 2215 /// only extern inline functions can be redefined, and even then only in 2216 /// GNU89 mode. 2217 static bool canRedefineFunction(const FunctionDecl *FD, 2218 const LangOptions& LangOpts) { 2219 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2220 !LangOpts.CPlusPlus && 2221 FD->isInlineSpecified() && 2222 FD->getStorageClass() == SC_Extern); 2223 } 2224 2225 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2226 const AttributedType *AT = T->getAs<AttributedType>(); 2227 while (AT && !AT->isCallingConv()) 2228 AT = AT->getModifiedType()->getAs<AttributedType>(); 2229 return AT; 2230 } 2231 2232 template <typename T> 2233 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2234 const DeclContext *DC = Old->getDeclContext(); 2235 if (DC->isRecord()) 2236 return false; 2237 2238 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2239 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2240 return true; 2241 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2242 return true; 2243 return false; 2244 } 2245 2246 /// MergeFunctionDecl - We just parsed a function 'New' from 2247 /// declarator D which has the same name and scope as a previous 2248 /// declaration 'Old'. Figure out how to resolve this situation, 2249 /// merging decls or emitting diagnostics as appropriate. 2250 /// 2251 /// In C++, New and Old must be declarations that are not 2252 /// overloaded. Use IsOverload to determine whether New and Old are 2253 /// overloaded, and to select the Old declaration that New should be 2254 /// merged with. 2255 /// 2256 /// Returns true if there was an error, false otherwise. 2257 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2258 Scope *S, bool MergeTypeWithOld) { 2259 // Verify the old decl was also a function. 2260 FunctionDecl *Old = OldD->getAsFunction(); 2261 if (!Old) { 2262 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2263 if (New->getFriendObjectKind()) { 2264 Diag(New->getLocation(), diag::err_using_decl_friend); 2265 Diag(Shadow->getTargetDecl()->getLocation(), 2266 diag::note_using_decl_target); 2267 Diag(Shadow->getUsingDecl()->getLocation(), 2268 diag::note_using_decl) << 0; 2269 return true; 2270 } 2271 2272 // C++11 [namespace.udecl]p14: 2273 // If a function declaration in namespace scope or block scope has the 2274 // same name and the same parameter-type-list as a function introduced 2275 // by a using-declaration, and the declarations do not declare the same 2276 // function, the program is ill-formed. 2277 2278 // Check whether the two declarations might declare the same function. 2279 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2280 if (Old && 2281 !Old->getDeclContext()->getRedeclContext()->Equals( 2282 New->getDeclContext()->getRedeclContext()) && 2283 !(Old->isExternC() && New->isExternC())) 2284 Old = 0; 2285 2286 if (!Old) { 2287 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2288 Diag(Shadow->getTargetDecl()->getLocation(), 2289 diag::note_using_decl_target); 2290 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2291 return true; 2292 } 2293 OldD = Old; 2294 } else { 2295 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2296 << New->getDeclName(); 2297 Diag(OldD->getLocation(), diag::note_previous_definition); 2298 return true; 2299 } 2300 } 2301 2302 // If the old declaration is invalid, just give up here. 2303 if (Old->isInvalidDecl()) 2304 return true; 2305 2306 // Determine whether the previous declaration was a definition, 2307 // implicit declaration, or a declaration. 2308 diag::kind PrevDiag; 2309 SourceLocation OldLocation = Old->getLocation(); 2310 if (Old->isThisDeclarationADefinition()) 2311 PrevDiag = diag::note_previous_definition; 2312 else if (Old->isImplicit()) { 2313 PrevDiag = diag::note_previous_implicit_declaration; 2314 if (OldLocation.isInvalid()) 2315 OldLocation = New->getLocation(); 2316 } else 2317 PrevDiag = diag::note_previous_declaration; 2318 2319 // Don't complain about this if we're in GNU89 mode and the old function 2320 // is an extern inline function. 2321 // Don't complain about specializations. They are not supposed to have 2322 // storage classes. 2323 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2324 New->getStorageClass() == SC_Static && 2325 Old->hasExternalFormalLinkage() && 2326 !New->getTemplateSpecializationInfo() && 2327 !canRedefineFunction(Old, getLangOpts())) { 2328 if (getLangOpts().MicrosoftExt) { 2329 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2330 Diag(OldLocation, PrevDiag); 2331 } else { 2332 Diag(New->getLocation(), diag::err_static_non_static) << New; 2333 Diag(OldLocation, PrevDiag); 2334 return true; 2335 } 2336 } 2337 2338 2339 // If a function is first declared with a calling convention, but is later 2340 // declared or defined without one, all following decls assume the calling 2341 // convention of the first. 2342 // 2343 // It's OK if a function is first declared without a calling convention, 2344 // but is later declared or defined with the default calling convention. 2345 // 2346 // To test if either decl has an explicit calling convention, we look for 2347 // AttributedType sugar nodes on the type as written. If they are missing or 2348 // were canonicalized away, we assume the calling convention was implicit. 2349 // 2350 // Note also that we DO NOT return at this point, because we still have 2351 // other tests to run. 2352 QualType OldQType = Context.getCanonicalType(Old->getType()); 2353 QualType NewQType = Context.getCanonicalType(New->getType()); 2354 const FunctionType *OldType = cast<FunctionType>(OldQType); 2355 const FunctionType *NewType = cast<FunctionType>(NewQType); 2356 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2357 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2358 bool RequiresAdjustment = false; 2359 2360 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2361 FunctionDecl *First = Old->getFirstDecl(); 2362 const FunctionType *FT = 2363 First->getType().getCanonicalType()->castAs<FunctionType>(); 2364 FunctionType::ExtInfo FI = FT->getExtInfo(); 2365 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2366 if (!NewCCExplicit) { 2367 // Inherit the CC from the previous declaration if it was specified 2368 // there but not here. 2369 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2370 RequiresAdjustment = true; 2371 } else { 2372 // Calling conventions aren't compatible, so complain. 2373 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2374 Diag(New->getLocation(), diag::err_cconv_change) 2375 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2376 << !FirstCCExplicit 2377 << (!FirstCCExplicit ? "" : 2378 FunctionType::getNameForCallConv(FI.getCC())); 2379 2380 // Put the note on the first decl, since it is the one that matters. 2381 Diag(First->getLocation(), diag::note_previous_declaration); 2382 return true; 2383 } 2384 } 2385 2386 // FIXME: diagnose the other way around? 2387 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2388 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2389 RequiresAdjustment = true; 2390 } 2391 2392 // Merge regparm attribute. 2393 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2394 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2395 if (NewTypeInfo.getHasRegParm()) { 2396 Diag(New->getLocation(), diag::err_regparm_mismatch) 2397 << NewType->getRegParmType() 2398 << OldType->getRegParmType(); 2399 Diag(OldLocation, diag::note_previous_declaration); 2400 return true; 2401 } 2402 2403 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2404 RequiresAdjustment = true; 2405 } 2406 2407 // Merge ns_returns_retained attribute. 2408 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2409 if (NewTypeInfo.getProducesResult()) { 2410 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2411 Diag(OldLocation, diag::note_previous_declaration); 2412 return true; 2413 } 2414 2415 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2416 RequiresAdjustment = true; 2417 } 2418 2419 if (RequiresAdjustment) { 2420 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2421 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2422 New->setType(QualType(AdjustedType, 0)); 2423 NewQType = Context.getCanonicalType(New->getType()); 2424 NewType = cast<FunctionType>(NewQType); 2425 } 2426 2427 // If this redeclaration makes the function inline, we may need to add it to 2428 // UndefinedButUsed. 2429 if (!Old->isInlined() && New->isInlined() && 2430 !New->hasAttr<GNUInlineAttr>() && 2431 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2432 Old->isUsed(false) && 2433 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2434 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2435 SourceLocation())); 2436 2437 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2438 // about it. 2439 if (New->hasAttr<GNUInlineAttr>() && 2440 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2441 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2442 } 2443 2444 if (getLangOpts().CPlusPlus) { 2445 // (C++98 13.1p2): 2446 // Certain function declarations cannot be overloaded: 2447 // -- Function declarations that differ only in the return type 2448 // cannot be overloaded. 2449 2450 // Go back to the type source info to compare the declared return types, 2451 // per C++1y [dcl.type.auto]p13: 2452 // Redeclarations or specializations of a function or function template 2453 // with a declared return type that uses a placeholder type shall also 2454 // use that placeholder, not a deduced type. 2455 QualType OldDeclaredReturnType = 2456 (Old->getTypeSourceInfo() 2457 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2458 : OldType)->getReturnType(); 2459 QualType NewDeclaredReturnType = 2460 (New->getTypeSourceInfo() 2461 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2462 : NewType)->getReturnType(); 2463 QualType ResQT; 2464 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2465 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2466 New->isLocalExternDecl())) { 2467 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2468 OldDeclaredReturnType->isObjCObjectPointerType()) 2469 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2470 if (ResQT.isNull()) { 2471 if (New->isCXXClassMember() && New->isOutOfLine()) 2472 Diag(New->getLocation(), 2473 diag::err_member_def_does_not_match_ret_type) << New; 2474 else 2475 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2476 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2477 return true; 2478 } 2479 else 2480 NewQType = ResQT; 2481 } 2482 2483 QualType OldReturnType = OldType->getReturnType(); 2484 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2485 if (OldReturnType != NewReturnType) { 2486 // If this function has a deduced return type and has already been 2487 // defined, copy the deduced value from the old declaration. 2488 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2489 if (OldAT && OldAT->isDeduced()) { 2490 New->setType( 2491 SubstAutoType(New->getType(), 2492 OldAT->isDependentType() ? Context.DependentTy 2493 : OldAT->getDeducedType())); 2494 NewQType = Context.getCanonicalType( 2495 SubstAutoType(NewQType, 2496 OldAT->isDependentType() ? Context.DependentTy 2497 : OldAT->getDeducedType())); 2498 } 2499 } 2500 2501 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2502 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2503 if (OldMethod && NewMethod) { 2504 // Preserve triviality. 2505 NewMethod->setTrivial(OldMethod->isTrivial()); 2506 2507 // MSVC allows explicit template specialization at class scope: 2508 // 2 CXXMethodDecls referring to the same function will be injected. 2509 // We don't want a redeclaration error. 2510 bool IsClassScopeExplicitSpecialization = 2511 OldMethod->isFunctionTemplateSpecialization() && 2512 NewMethod->isFunctionTemplateSpecialization(); 2513 bool isFriend = NewMethod->getFriendObjectKind(); 2514 2515 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2516 !IsClassScopeExplicitSpecialization) { 2517 // -- Member function declarations with the same name and the 2518 // same parameter types cannot be overloaded if any of them 2519 // is a static member function declaration. 2520 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2521 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2522 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2523 return true; 2524 } 2525 2526 // C++ [class.mem]p1: 2527 // [...] A member shall not be declared twice in the 2528 // member-specification, except that a nested class or member 2529 // class template can be declared and then later defined. 2530 if (ActiveTemplateInstantiations.empty()) { 2531 unsigned NewDiag; 2532 if (isa<CXXConstructorDecl>(OldMethod)) 2533 NewDiag = diag::err_constructor_redeclared; 2534 else if (isa<CXXDestructorDecl>(NewMethod)) 2535 NewDiag = diag::err_destructor_redeclared; 2536 else if (isa<CXXConversionDecl>(NewMethod)) 2537 NewDiag = diag::err_conv_function_redeclared; 2538 else 2539 NewDiag = diag::err_member_redeclared; 2540 2541 Diag(New->getLocation(), NewDiag); 2542 } else { 2543 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2544 << New << New->getType(); 2545 } 2546 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2547 2548 // Complain if this is an explicit declaration of a special 2549 // member that was initially declared implicitly. 2550 // 2551 // As an exception, it's okay to befriend such methods in order 2552 // to permit the implicit constructor/destructor/operator calls. 2553 } else if (OldMethod->isImplicit()) { 2554 if (isFriend) { 2555 NewMethod->setImplicit(); 2556 } else { 2557 Diag(NewMethod->getLocation(), 2558 diag::err_definition_of_implicitly_declared_member) 2559 << New << getSpecialMember(OldMethod); 2560 return true; 2561 } 2562 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2563 Diag(NewMethod->getLocation(), 2564 diag::err_definition_of_explicitly_defaulted_member) 2565 << getSpecialMember(OldMethod); 2566 return true; 2567 } 2568 } 2569 2570 // C++11 [dcl.attr.noreturn]p1: 2571 // The first declaration of a function shall specify the noreturn 2572 // attribute if any declaration of that function specifies the noreturn 2573 // attribute. 2574 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2575 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2576 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2577 Diag(Old->getFirstDecl()->getLocation(), 2578 diag::note_noreturn_missing_first_decl); 2579 } 2580 2581 // C++11 [dcl.attr.depend]p2: 2582 // The first declaration of a function shall specify the 2583 // carries_dependency attribute for its declarator-id if any declaration 2584 // of the function specifies the carries_dependency attribute. 2585 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2586 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2587 Diag(CDA->getLocation(), 2588 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2589 Diag(Old->getFirstDecl()->getLocation(), 2590 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2591 } 2592 2593 // (C++98 8.3.5p3): 2594 // All declarations for a function shall agree exactly in both the 2595 // return type and the parameter-type-list. 2596 // We also want to respect all the extended bits except noreturn. 2597 2598 // noreturn should now match unless the old type info didn't have it. 2599 QualType OldQTypeForComparison = OldQType; 2600 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2601 assert(OldQType == QualType(OldType, 0)); 2602 const FunctionType *OldTypeForComparison 2603 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2604 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2605 assert(OldQTypeForComparison.isCanonical()); 2606 } 2607 2608 if (haveIncompatibleLanguageLinkages(Old, New)) { 2609 // As a special case, retain the language linkage from previous 2610 // declarations of a friend function as an extension. 2611 // 2612 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2613 // and is useful because there's otherwise no way to specify language 2614 // linkage within class scope. 2615 // 2616 // Check cautiously as the friend object kind isn't yet complete. 2617 if (New->getFriendObjectKind() != Decl::FOK_None) { 2618 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2619 Diag(OldLocation, PrevDiag); 2620 } else { 2621 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2622 Diag(OldLocation, PrevDiag); 2623 return true; 2624 } 2625 } 2626 2627 if (OldQTypeForComparison == NewQType) 2628 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2629 2630 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2631 New->isLocalExternDecl()) { 2632 // It's OK if we couldn't merge types for a local function declaraton 2633 // if either the old or new type is dependent. We'll merge the types 2634 // when we instantiate the function. 2635 return false; 2636 } 2637 2638 // Fall through for conflicting redeclarations and redefinitions. 2639 } 2640 2641 // C: Function types need to be compatible, not identical. This handles 2642 // duplicate function decls like "void f(int); void f(enum X);" properly. 2643 if (!getLangOpts().CPlusPlus && 2644 Context.typesAreCompatible(OldQType, NewQType)) { 2645 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2646 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2647 const FunctionProtoType *OldProto = 0; 2648 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2649 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2650 // The old declaration provided a function prototype, but the 2651 // new declaration does not. Merge in the prototype. 2652 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2653 SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(), 2654 OldProto->param_type_end()); 2655 NewQType = 2656 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2657 OldProto->getExtProtoInfo()); 2658 New->setType(NewQType); 2659 New->setHasInheritedPrototype(); 2660 2661 // Synthesize a parameter for each argument type. 2662 SmallVector<ParmVarDecl*, 16> Params; 2663 for (FunctionProtoType::param_type_iterator 2664 ParamType = OldProto->param_type_begin(), 2665 ParamEnd = OldProto->param_type_end(); 2666 ParamType != ParamEnd; ++ParamType) { 2667 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2668 SourceLocation(), 2669 SourceLocation(), 0, 2670 *ParamType, /*TInfo=*/0, 2671 SC_None, 2672 0); 2673 Param->setScopeInfo(0, Params.size()); 2674 Param->setImplicit(); 2675 Params.push_back(Param); 2676 } 2677 2678 New->setParams(Params); 2679 } 2680 2681 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2682 } 2683 2684 // GNU C permits a K&R definition to follow a prototype declaration 2685 // if the declared types of the parameters in the K&R definition 2686 // match the types in the prototype declaration, even when the 2687 // promoted types of the parameters from the K&R definition differ 2688 // from the types in the prototype. GCC then keeps the types from 2689 // the prototype. 2690 // 2691 // If a variadic prototype is followed by a non-variadic K&R definition, 2692 // the K&R definition becomes variadic. This is sort of an edge case, but 2693 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2694 // C99 6.9.1p8. 2695 if (!getLangOpts().CPlusPlus && 2696 Old->hasPrototype() && !New->hasPrototype() && 2697 New->getType()->getAs<FunctionProtoType>() && 2698 Old->getNumParams() == New->getNumParams()) { 2699 SmallVector<QualType, 16> ArgTypes; 2700 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2701 const FunctionProtoType *OldProto 2702 = Old->getType()->getAs<FunctionProtoType>(); 2703 const FunctionProtoType *NewProto 2704 = New->getType()->getAs<FunctionProtoType>(); 2705 2706 // Determine whether this is the GNU C extension. 2707 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2708 NewProto->getReturnType()); 2709 bool LooseCompatible = !MergedReturn.isNull(); 2710 for (unsigned Idx = 0, End = Old->getNumParams(); 2711 LooseCompatible && Idx != End; ++Idx) { 2712 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2713 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2714 if (Context.typesAreCompatible(OldParm->getType(), 2715 NewProto->getParamType(Idx))) { 2716 ArgTypes.push_back(NewParm->getType()); 2717 } else if (Context.typesAreCompatible(OldParm->getType(), 2718 NewParm->getType(), 2719 /*CompareUnqualified=*/true)) { 2720 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2721 NewProto->getParamType(Idx) }; 2722 Warnings.push_back(Warn); 2723 ArgTypes.push_back(NewParm->getType()); 2724 } else 2725 LooseCompatible = false; 2726 } 2727 2728 if (LooseCompatible) { 2729 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2730 Diag(Warnings[Warn].NewParm->getLocation(), 2731 diag::ext_param_promoted_not_compatible_with_prototype) 2732 << Warnings[Warn].PromotedType 2733 << Warnings[Warn].OldParm->getType(); 2734 if (Warnings[Warn].OldParm->getLocation().isValid()) 2735 Diag(Warnings[Warn].OldParm->getLocation(), 2736 diag::note_previous_declaration); 2737 } 2738 2739 if (MergeTypeWithOld) 2740 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2741 OldProto->getExtProtoInfo())); 2742 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2743 } 2744 2745 // Fall through to diagnose conflicting types. 2746 } 2747 2748 // A function that has already been declared has been redeclared or 2749 // defined with a different type; show an appropriate diagnostic. 2750 2751 // If the previous declaration was an implicitly-generated builtin 2752 // declaration, then at the very least we should use a specialized note. 2753 unsigned BuiltinID; 2754 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2755 // If it's actually a library-defined builtin function like 'malloc' 2756 // or 'printf', just warn about the incompatible redeclaration. 2757 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2758 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2759 Diag(OldLocation, diag::note_previous_builtin_declaration) 2760 << Old << Old->getType(); 2761 2762 // If this is a global redeclaration, just forget hereafter 2763 // about the "builtin-ness" of the function. 2764 // 2765 // Doing this for local extern declarations is problematic. If 2766 // the builtin declaration remains visible, a second invalid 2767 // local declaration will produce a hard error; if it doesn't 2768 // remain visible, a single bogus local redeclaration (which is 2769 // actually only a warning) could break all the downstream code. 2770 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2771 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2772 2773 return false; 2774 } 2775 2776 PrevDiag = diag::note_previous_builtin_declaration; 2777 } 2778 2779 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2780 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2781 return true; 2782 } 2783 2784 /// \brief Completes the merge of two function declarations that are 2785 /// known to be compatible. 2786 /// 2787 /// This routine handles the merging of attributes and other 2788 /// properties of function declarations from the old declaration to 2789 /// the new declaration, once we know that New is in fact a 2790 /// redeclaration of Old. 2791 /// 2792 /// \returns false 2793 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2794 Scope *S, bool MergeTypeWithOld) { 2795 // Merge the attributes 2796 mergeDeclAttributes(New, Old); 2797 2798 // Merge "pure" flag. 2799 if (Old->isPure()) 2800 New->setPure(); 2801 2802 // Merge "used" flag. 2803 if (Old->getMostRecentDecl()->isUsed(false)) 2804 New->setIsUsed(); 2805 2806 // Merge attributes from the parameters. These can mismatch with K&R 2807 // declarations. 2808 if (New->getNumParams() == Old->getNumParams()) 2809 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2810 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2811 *this); 2812 2813 if (getLangOpts().CPlusPlus) 2814 return MergeCXXFunctionDecl(New, Old, S); 2815 2816 // Merge the function types so the we get the composite types for the return 2817 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2818 // was visible. 2819 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2820 if (!Merged.isNull() && MergeTypeWithOld) 2821 New->setType(Merged); 2822 2823 return false; 2824 } 2825 2826 2827 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2828 ObjCMethodDecl *oldMethod) { 2829 2830 // Merge the attributes, including deprecated/unavailable 2831 AvailabilityMergeKind MergeKind = 2832 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2833 : AMK_Override; 2834 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2835 2836 // Merge attributes from the parameters. 2837 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2838 oe = oldMethod->param_end(); 2839 for (ObjCMethodDecl::param_iterator 2840 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2841 ni != ne && oi != oe; ++ni, ++oi) 2842 mergeParamDeclAttributes(*ni, *oi, *this); 2843 2844 CheckObjCMethodOverride(newMethod, oldMethod); 2845 } 2846 2847 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2848 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2849 /// emitting diagnostics as appropriate. 2850 /// 2851 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2852 /// to here in AddInitializerToDecl. We can't check them before the initializer 2853 /// is attached. 2854 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2855 bool MergeTypeWithOld) { 2856 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2857 return; 2858 2859 QualType MergedT; 2860 if (getLangOpts().CPlusPlus) { 2861 if (New->getType()->isUndeducedType()) { 2862 // We don't know what the new type is until the initializer is attached. 2863 return; 2864 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2865 // These could still be something that needs exception specs checked. 2866 return MergeVarDeclExceptionSpecs(New, Old); 2867 } 2868 // C++ [basic.link]p10: 2869 // [...] the types specified by all declarations referring to a given 2870 // object or function shall be identical, except that declarations for an 2871 // array object can specify array types that differ by the presence or 2872 // absence of a major array bound (8.3.4). 2873 else if (Old->getType()->isIncompleteArrayType() && 2874 New->getType()->isArrayType()) { 2875 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2876 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2877 if (Context.hasSameType(OldArray->getElementType(), 2878 NewArray->getElementType())) 2879 MergedT = New->getType(); 2880 } else if (Old->getType()->isArrayType() && 2881 New->getType()->isIncompleteArrayType()) { 2882 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2883 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2884 if (Context.hasSameType(OldArray->getElementType(), 2885 NewArray->getElementType())) 2886 MergedT = Old->getType(); 2887 } else if (New->getType()->isObjCObjectPointerType() && 2888 Old->getType()->isObjCObjectPointerType()) { 2889 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2890 Old->getType()); 2891 } 2892 } else { 2893 // C 6.2.7p2: 2894 // All declarations that refer to the same object or function shall have 2895 // compatible type. 2896 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2897 } 2898 if (MergedT.isNull()) { 2899 // It's OK if we couldn't merge types if either type is dependent, for a 2900 // block-scope variable. In other cases (static data members of class 2901 // templates, variable templates, ...), we require the types to be 2902 // equivalent. 2903 // FIXME: The C++ standard doesn't say anything about this. 2904 if ((New->getType()->isDependentType() || 2905 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2906 // If the old type was dependent, we can't merge with it, so the new type 2907 // becomes dependent for now. We'll reproduce the original type when we 2908 // instantiate the TypeSourceInfo for the variable. 2909 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2910 New->setType(Context.DependentTy); 2911 return; 2912 } 2913 2914 // FIXME: Even if this merging succeeds, some other non-visible declaration 2915 // of this variable might have an incompatible type. For instance: 2916 // 2917 // extern int arr[]; 2918 // void f() { extern int arr[2]; } 2919 // void g() { extern int arr[3]; } 2920 // 2921 // Neither C nor C++ requires a diagnostic for this, but we should still try 2922 // to diagnose it. 2923 Diag(New->getLocation(), diag::err_redefinition_different_type) 2924 << New->getDeclName() << New->getType() << Old->getType(); 2925 Diag(Old->getLocation(), diag::note_previous_definition); 2926 return New->setInvalidDecl(); 2927 } 2928 2929 // Don't actually update the type on the new declaration if the old 2930 // declaration was an extern declaration in a different scope. 2931 if (MergeTypeWithOld) 2932 New->setType(MergedT); 2933 } 2934 2935 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2936 LookupResult &Previous) { 2937 // C11 6.2.7p4: 2938 // For an identifier with internal or external linkage declared 2939 // in a scope in which a prior declaration of that identifier is 2940 // visible, if the prior declaration specifies internal or 2941 // external linkage, the type of the identifier at the later 2942 // declaration becomes the composite type. 2943 // 2944 // If the variable isn't visible, we do not merge with its type. 2945 if (Previous.isShadowed()) 2946 return false; 2947 2948 if (S.getLangOpts().CPlusPlus) { 2949 // C++11 [dcl.array]p3: 2950 // If there is a preceding declaration of the entity in the same 2951 // scope in which the bound was specified, an omitted array bound 2952 // is taken to be the same as in that earlier declaration. 2953 return NewVD->isPreviousDeclInSameBlockScope() || 2954 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2955 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2956 } else { 2957 // If the old declaration was function-local, don't merge with its 2958 // type unless we're in the same function. 2959 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2960 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2961 } 2962 } 2963 2964 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2965 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2966 /// situation, merging decls or emitting diagnostics as appropriate. 2967 /// 2968 /// Tentative definition rules (C99 6.9.2p2) are checked by 2969 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2970 /// definitions here, since the initializer hasn't been attached. 2971 /// 2972 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2973 // If the new decl is already invalid, don't do any other checking. 2974 if (New->isInvalidDecl()) 2975 return; 2976 2977 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 2978 2979 // Verify the old decl was also a variable or variable template. 2980 VarDecl *Old = 0; 2981 VarTemplateDecl *OldTemplate = 0; 2982 if (Previous.isSingleResult()) { 2983 if (NewTemplate) { 2984 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 2985 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0; 2986 } else 2987 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2988 } 2989 if (!Old) { 2990 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2991 << New->getDeclName(); 2992 Diag(Previous.getRepresentativeDecl()->getLocation(), 2993 diag::note_previous_definition); 2994 return New->setInvalidDecl(); 2995 } 2996 2997 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 2998 return; 2999 3000 // Ensure the template parameters are compatible. 3001 if (NewTemplate && 3002 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3003 OldTemplate->getTemplateParameters(), 3004 /*Complain=*/true, TPL_TemplateMatch)) 3005 return; 3006 3007 // C++ [class.mem]p1: 3008 // A member shall not be declared twice in the member-specification [...] 3009 // 3010 // Here, we need only consider static data members. 3011 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3012 Diag(New->getLocation(), diag::err_duplicate_member) 3013 << New->getIdentifier(); 3014 Diag(Old->getLocation(), diag::note_previous_declaration); 3015 New->setInvalidDecl(); 3016 } 3017 3018 mergeDeclAttributes(New, Old); 3019 // Warn if an already-declared variable is made a weak_import in a subsequent 3020 // declaration 3021 if (New->hasAttr<WeakImportAttr>() && 3022 Old->getStorageClass() == SC_None && 3023 !Old->hasAttr<WeakImportAttr>()) { 3024 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3025 Diag(Old->getLocation(), diag::note_previous_definition); 3026 // Remove weak_import attribute on new declaration. 3027 New->dropAttr<WeakImportAttr>(); 3028 } 3029 3030 // Merge the types. 3031 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3032 3033 if (New->isInvalidDecl()) 3034 return; 3035 3036 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3037 if (New->getStorageClass() == SC_Static && 3038 !New->isStaticDataMember() && 3039 Old->hasExternalFormalLinkage()) { 3040 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3041 Diag(Old->getLocation(), diag::note_previous_definition); 3042 return New->setInvalidDecl(); 3043 } 3044 // C99 6.2.2p4: 3045 // For an identifier declared with the storage-class specifier 3046 // extern in a scope in which a prior declaration of that 3047 // identifier is visible,23) if the prior declaration specifies 3048 // internal or external linkage, the linkage of the identifier at 3049 // the later declaration is the same as the linkage specified at 3050 // the prior declaration. If no prior declaration is visible, or 3051 // if the prior declaration specifies no linkage, then the 3052 // identifier has external linkage. 3053 if (New->hasExternalStorage() && Old->hasLinkage()) 3054 /* Okay */; 3055 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3056 !New->isStaticDataMember() && 3057 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3058 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3059 Diag(Old->getLocation(), diag::note_previous_definition); 3060 return New->setInvalidDecl(); 3061 } 3062 3063 // Check if extern is followed by non-extern and vice-versa. 3064 if (New->hasExternalStorage() && 3065 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3066 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3067 Diag(Old->getLocation(), diag::note_previous_definition); 3068 return New->setInvalidDecl(); 3069 } 3070 if (Old->hasLinkage() && New->isLocalVarDecl() && 3071 !New->hasExternalStorage()) { 3072 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3073 Diag(Old->getLocation(), diag::note_previous_definition); 3074 return New->setInvalidDecl(); 3075 } 3076 3077 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3078 3079 // FIXME: The test for external storage here seems wrong? We still 3080 // need to check for mismatches. 3081 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3082 // Don't complain about out-of-line definitions of static members. 3083 !(Old->getLexicalDeclContext()->isRecord() && 3084 !New->getLexicalDeclContext()->isRecord())) { 3085 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3086 Diag(Old->getLocation(), diag::note_previous_definition); 3087 return New->setInvalidDecl(); 3088 } 3089 3090 if (New->getTLSKind() != Old->getTLSKind()) { 3091 if (!Old->getTLSKind()) { 3092 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3093 Diag(Old->getLocation(), diag::note_previous_declaration); 3094 } else if (!New->getTLSKind()) { 3095 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3096 Diag(Old->getLocation(), diag::note_previous_declaration); 3097 } else { 3098 // Do not allow redeclaration to change the variable between requiring 3099 // static and dynamic initialization. 3100 // FIXME: GCC allows this, but uses the TLS keyword on the first 3101 // declaration to determine the kind. Do we need to be compatible here? 3102 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3103 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3104 Diag(Old->getLocation(), diag::note_previous_declaration); 3105 } 3106 } 3107 3108 // C++ doesn't have tentative definitions, so go right ahead and check here. 3109 const VarDecl *Def; 3110 if (getLangOpts().CPlusPlus && 3111 New->isThisDeclarationADefinition() == VarDecl::Definition && 3112 (Def = Old->getDefinition())) { 3113 Diag(New->getLocation(), diag::err_redefinition) << New; 3114 Diag(Def->getLocation(), diag::note_previous_definition); 3115 New->setInvalidDecl(); 3116 return; 3117 } 3118 3119 if (haveIncompatibleLanguageLinkages(Old, New)) { 3120 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3121 Diag(Old->getLocation(), diag::note_previous_definition); 3122 New->setInvalidDecl(); 3123 return; 3124 } 3125 3126 // Merge "used" flag. 3127 if (Old->getMostRecentDecl()->isUsed(false)) 3128 New->setIsUsed(); 3129 3130 // Keep a chain of previous declarations. 3131 New->setPreviousDecl(Old); 3132 if (NewTemplate) 3133 NewTemplate->setPreviousDecl(OldTemplate); 3134 3135 // Inherit access appropriately. 3136 New->setAccess(Old->getAccess()); 3137 if (NewTemplate) 3138 NewTemplate->setAccess(New->getAccess()); 3139 } 3140 3141 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3142 /// no declarator (e.g. "struct foo;") is parsed. 3143 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3144 DeclSpec &DS) { 3145 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3146 } 3147 3148 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3149 if (!S.Context.getLangOpts().CPlusPlus) 3150 return; 3151 3152 if (isa<CXXRecordDecl>(Tag->getParent())) { 3153 // If this tag is the direct child of a class, number it if 3154 // it is anonymous. 3155 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3156 return; 3157 MangleNumberingContext &MCtx = 3158 S.Context.getManglingNumberContext(Tag->getParent()); 3159 S.Context.setManglingNumber( 3160 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3161 return; 3162 } 3163 3164 // If this tag isn't a direct child of a class, number it if it is local. 3165 Decl *ManglingContextDecl; 3166 if (MangleNumberingContext *MCtx = 3167 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3168 ManglingContextDecl)) { 3169 S.Context.setManglingNumber( 3170 Tag, 3171 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3172 } 3173 } 3174 3175 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3176 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3177 /// parameters to cope with template friend declarations. 3178 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3179 DeclSpec &DS, 3180 MultiTemplateParamsArg TemplateParams, 3181 bool IsExplicitInstantiation) { 3182 Decl *TagD = 0; 3183 TagDecl *Tag = 0; 3184 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3185 DS.getTypeSpecType() == DeclSpec::TST_struct || 3186 DS.getTypeSpecType() == DeclSpec::TST_interface || 3187 DS.getTypeSpecType() == DeclSpec::TST_union || 3188 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3189 TagD = DS.getRepAsDecl(); 3190 3191 if (!TagD) // We probably had an error 3192 return 0; 3193 3194 // Note that the above type specs guarantee that the 3195 // type rep is a Decl, whereas in many of the others 3196 // it's a Type. 3197 if (isa<TagDecl>(TagD)) 3198 Tag = cast<TagDecl>(TagD); 3199 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3200 Tag = CTD->getTemplatedDecl(); 3201 } 3202 3203 if (Tag) { 3204 HandleTagNumbering(*this, Tag, S); 3205 Tag->setFreeStanding(); 3206 if (Tag->isInvalidDecl()) 3207 return Tag; 3208 } 3209 3210 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3211 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3212 // or incomplete types shall not be restrict-qualified." 3213 if (TypeQuals & DeclSpec::TQ_restrict) 3214 Diag(DS.getRestrictSpecLoc(), 3215 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3216 << DS.getSourceRange(); 3217 } 3218 3219 if (DS.isConstexprSpecified()) { 3220 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3221 // and definitions of functions and variables. 3222 if (Tag) 3223 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3224 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3225 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3226 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3227 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3228 else 3229 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3230 // Don't emit warnings after this error. 3231 return TagD; 3232 } 3233 3234 DiagnoseFunctionSpecifiers(DS); 3235 3236 if (DS.isFriendSpecified()) { 3237 // If we're dealing with a decl but not a TagDecl, assume that 3238 // whatever routines created it handled the friendship aspect. 3239 if (TagD && !Tag) 3240 return 0; 3241 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3242 } 3243 3244 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3245 bool IsExplicitSpecialization = 3246 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3247 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3248 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3249 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3250 // nested-name-specifier unless it is an explicit instantiation 3251 // or an explicit specialization. 3252 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3253 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3254 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3255 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3256 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3257 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3258 << SS.getRange(); 3259 return 0; 3260 } 3261 3262 // Track whether this decl-specifier declares anything. 3263 bool DeclaresAnything = true; 3264 3265 // Handle anonymous struct definitions. 3266 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3267 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3268 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3269 if (getLangOpts().CPlusPlus || 3270 Record->getDeclContext()->isRecord()) 3271 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3272 3273 DeclaresAnything = false; 3274 } 3275 } 3276 3277 // Check for Microsoft C extension: anonymous struct member. 3278 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3279 CurContext->isRecord() && 3280 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3281 // Handle 2 kinds of anonymous struct: 3282 // struct STRUCT; 3283 // and 3284 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3285 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3286 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3287 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3288 DS.getRepAsType().get()->isStructureType())) { 3289 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3290 << DS.getSourceRange(); 3291 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3292 } 3293 } 3294 3295 // Skip all the checks below if we have a type error. 3296 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3297 (TagD && TagD->isInvalidDecl())) 3298 return TagD; 3299 3300 if (getLangOpts().CPlusPlus && 3301 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3302 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3303 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3304 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3305 DeclaresAnything = false; 3306 3307 if (!DS.isMissingDeclaratorOk()) { 3308 // Customize diagnostic for a typedef missing a name. 3309 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3310 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3311 << DS.getSourceRange(); 3312 else 3313 DeclaresAnything = false; 3314 } 3315 3316 if (DS.isModulePrivateSpecified() && 3317 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3318 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3319 << Tag->getTagKind() 3320 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3321 3322 ActOnDocumentableDecl(TagD); 3323 3324 // C 6.7/2: 3325 // A declaration [...] shall declare at least a declarator [...], a tag, 3326 // or the members of an enumeration. 3327 // C++ [dcl.dcl]p3: 3328 // [If there are no declarators], and except for the declaration of an 3329 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3330 // names into the program, or shall redeclare a name introduced by a 3331 // previous declaration. 3332 if (!DeclaresAnything) { 3333 // In C, we allow this as a (popular) extension / bug. Don't bother 3334 // producing further diagnostics for redundant qualifiers after this. 3335 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3336 return TagD; 3337 } 3338 3339 // C++ [dcl.stc]p1: 3340 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3341 // init-declarator-list of the declaration shall not be empty. 3342 // C++ [dcl.fct.spec]p1: 3343 // If a cv-qualifier appears in a decl-specifier-seq, the 3344 // init-declarator-list of the declaration shall not be empty. 3345 // 3346 // Spurious qualifiers here appear to be valid in C. 3347 unsigned DiagID = diag::warn_standalone_specifier; 3348 if (getLangOpts().CPlusPlus) 3349 DiagID = diag::ext_standalone_specifier; 3350 3351 // Note that a linkage-specification sets a storage class, but 3352 // 'extern "C" struct foo;' is actually valid and not theoretically 3353 // useless. 3354 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3355 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3356 Diag(DS.getStorageClassSpecLoc(), DiagID) 3357 << DeclSpec::getSpecifierName(SCS); 3358 3359 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3360 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3361 << DeclSpec::getSpecifierName(TSCS); 3362 if (DS.getTypeQualifiers()) { 3363 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3364 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3365 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3366 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3367 // Restrict is covered above. 3368 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3369 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3370 } 3371 3372 // Warn about ignored type attributes, for example: 3373 // __attribute__((aligned)) struct A; 3374 // Attributes should be placed after tag to apply to type declaration. 3375 if (!DS.getAttributes().empty()) { 3376 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3377 if (TypeSpecType == DeclSpec::TST_class || 3378 TypeSpecType == DeclSpec::TST_struct || 3379 TypeSpecType == DeclSpec::TST_interface || 3380 TypeSpecType == DeclSpec::TST_union || 3381 TypeSpecType == DeclSpec::TST_enum) { 3382 AttributeList* attrs = DS.getAttributes().getList(); 3383 while (attrs) { 3384 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3385 << attrs->getName() 3386 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3387 TypeSpecType == DeclSpec::TST_struct ? 1 : 3388 TypeSpecType == DeclSpec::TST_union ? 2 : 3389 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3390 attrs = attrs->getNext(); 3391 } 3392 } 3393 } 3394 3395 return TagD; 3396 } 3397 3398 /// We are trying to inject an anonymous member into the given scope; 3399 /// check if there's an existing declaration that can't be overloaded. 3400 /// 3401 /// \return true if this is a forbidden redeclaration 3402 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3403 Scope *S, 3404 DeclContext *Owner, 3405 DeclarationName Name, 3406 SourceLocation NameLoc, 3407 unsigned diagnostic) { 3408 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3409 Sema::ForRedeclaration); 3410 if (!SemaRef.LookupName(R, S)) return false; 3411 3412 if (R.getAsSingle<TagDecl>()) 3413 return false; 3414 3415 // Pick a representative declaration. 3416 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3417 assert(PrevDecl && "Expected a non-null Decl"); 3418 3419 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3420 return false; 3421 3422 SemaRef.Diag(NameLoc, diagnostic) << Name; 3423 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3424 3425 return true; 3426 } 3427 3428 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3429 /// anonymous struct or union AnonRecord into the owning context Owner 3430 /// and scope S. This routine will be invoked just after we realize 3431 /// that an unnamed union or struct is actually an anonymous union or 3432 /// struct, e.g., 3433 /// 3434 /// @code 3435 /// union { 3436 /// int i; 3437 /// float f; 3438 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3439 /// // f into the surrounding scope.x 3440 /// @endcode 3441 /// 3442 /// This routine is recursive, injecting the names of nested anonymous 3443 /// structs/unions into the owning context and scope as well. 3444 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3445 DeclContext *Owner, 3446 RecordDecl *AnonRecord, 3447 AccessSpecifier AS, 3448 SmallVectorImpl<NamedDecl *> &Chaining, 3449 bool MSAnonStruct) { 3450 unsigned diagKind 3451 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3452 : diag::err_anonymous_struct_member_redecl; 3453 3454 bool Invalid = false; 3455 3456 // Look every FieldDecl and IndirectFieldDecl with a name. 3457 for (auto *D : AnonRecord->decls()) { 3458 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3459 cast<NamedDecl>(D)->getDeclName()) { 3460 ValueDecl *VD = cast<ValueDecl>(D); 3461 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3462 VD->getLocation(), diagKind)) { 3463 // C++ [class.union]p2: 3464 // The names of the members of an anonymous union shall be 3465 // distinct from the names of any other entity in the 3466 // scope in which the anonymous union is declared. 3467 Invalid = true; 3468 } else { 3469 // C++ [class.union]p2: 3470 // For the purpose of name lookup, after the anonymous union 3471 // definition, the members of the anonymous union are 3472 // considered to have been defined in the scope in which the 3473 // anonymous union is declared. 3474 unsigned OldChainingSize = Chaining.size(); 3475 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3476 for (auto *PI : IF->chain()) 3477 Chaining.push_back(PI); 3478 else 3479 Chaining.push_back(VD); 3480 3481 assert(Chaining.size() >= 2); 3482 NamedDecl **NamedChain = 3483 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3484 for (unsigned i = 0; i < Chaining.size(); i++) 3485 NamedChain[i] = Chaining[i]; 3486 3487 IndirectFieldDecl* IndirectField = 3488 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3489 VD->getIdentifier(), VD->getType(), 3490 NamedChain, Chaining.size()); 3491 3492 IndirectField->setAccess(AS); 3493 IndirectField->setImplicit(); 3494 SemaRef.PushOnScopeChains(IndirectField, S); 3495 3496 // That includes picking up the appropriate access specifier. 3497 if (AS != AS_none) IndirectField->setAccess(AS); 3498 3499 Chaining.resize(OldChainingSize); 3500 } 3501 } 3502 } 3503 3504 return Invalid; 3505 } 3506 3507 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3508 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3509 /// illegal input values are mapped to SC_None. 3510 static StorageClass 3511 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3512 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3513 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3514 "Parser allowed 'typedef' as storage class VarDecl."); 3515 switch (StorageClassSpec) { 3516 case DeclSpec::SCS_unspecified: return SC_None; 3517 case DeclSpec::SCS_extern: 3518 if (DS.isExternInLinkageSpec()) 3519 return SC_None; 3520 return SC_Extern; 3521 case DeclSpec::SCS_static: return SC_Static; 3522 case DeclSpec::SCS_auto: return SC_Auto; 3523 case DeclSpec::SCS_register: return SC_Register; 3524 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3525 // Illegal SCSs map to None: error reporting is up to the caller. 3526 case DeclSpec::SCS_mutable: // Fall through. 3527 case DeclSpec::SCS_typedef: return SC_None; 3528 } 3529 llvm_unreachable("unknown storage class specifier"); 3530 } 3531 3532 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3533 assert(Record->hasInClassInitializer()); 3534 3535 for (const auto *I : Record->decls()) { 3536 const auto *FD = dyn_cast<FieldDecl>(I); 3537 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3538 FD = IFD->getAnonField(); 3539 if (FD && FD->hasInClassInitializer()) 3540 return FD->getLocation(); 3541 } 3542 3543 llvm_unreachable("couldn't find in-class initializer"); 3544 } 3545 3546 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3547 SourceLocation DefaultInitLoc) { 3548 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3549 return; 3550 3551 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3552 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3553 } 3554 3555 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3556 CXXRecordDecl *AnonUnion) { 3557 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3558 return; 3559 3560 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3561 } 3562 3563 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3564 /// anonymous structure or union. Anonymous unions are a C++ feature 3565 /// (C++ [class.union]) and a C11 feature; anonymous structures 3566 /// are a C11 feature and GNU C++ extension. 3567 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3568 AccessSpecifier AS, 3569 RecordDecl *Record, 3570 const PrintingPolicy &Policy) { 3571 DeclContext *Owner = Record->getDeclContext(); 3572 3573 // Diagnose whether this anonymous struct/union is an extension. 3574 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3575 Diag(Record->getLocation(), diag::ext_anonymous_union); 3576 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3577 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3578 else if (!Record->isUnion() && !getLangOpts().C11) 3579 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3580 3581 // C and C++ require different kinds of checks for anonymous 3582 // structs/unions. 3583 bool Invalid = false; 3584 if (getLangOpts().CPlusPlus) { 3585 const char* PrevSpec = 0; 3586 unsigned DiagID; 3587 if (Record->isUnion()) { 3588 // C++ [class.union]p6: 3589 // Anonymous unions declared in a named namespace or in the 3590 // global namespace shall be declared static. 3591 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3592 (isa<TranslationUnitDecl>(Owner) || 3593 (isa<NamespaceDecl>(Owner) && 3594 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3595 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3596 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3597 3598 // Recover by adding 'static'. 3599 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3600 PrevSpec, DiagID, Policy); 3601 } 3602 // C++ [class.union]p6: 3603 // A storage class is not allowed in a declaration of an 3604 // anonymous union in a class scope. 3605 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3606 isa<RecordDecl>(Owner)) { 3607 Diag(DS.getStorageClassSpecLoc(), 3608 diag::err_anonymous_union_with_storage_spec) 3609 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3610 3611 // Recover by removing the storage specifier. 3612 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3613 SourceLocation(), 3614 PrevSpec, DiagID, Context.getPrintingPolicy()); 3615 } 3616 } 3617 3618 // Ignore const/volatile/restrict qualifiers. 3619 if (DS.getTypeQualifiers()) { 3620 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3621 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3622 << Record->isUnion() << "const" 3623 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3624 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3625 Diag(DS.getVolatileSpecLoc(), 3626 diag::ext_anonymous_struct_union_qualified) 3627 << Record->isUnion() << "volatile" 3628 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3629 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3630 Diag(DS.getRestrictSpecLoc(), 3631 diag::ext_anonymous_struct_union_qualified) 3632 << Record->isUnion() << "restrict" 3633 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3634 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3635 Diag(DS.getAtomicSpecLoc(), 3636 diag::ext_anonymous_struct_union_qualified) 3637 << Record->isUnion() << "_Atomic" 3638 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3639 3640 DS.ClearTypeQualifiers(); 3641 } 3642 3643 // C++ [class.union]p2: 3644 // The member-specification of an anonymous union shall only 3645 // define non-static data members. [Note: nested types and 3646 // functions cannot be declared within an anonymous union. ] 3647 for (auto *Mem : Record->decls()) { 3648 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3649 // C++ [class.union]p3: 3650 // An anonymous union shall not have private or protected 3651 // members (clause 11). 3652 assert(FD->getAccess() != AS_none); 3653 if (FD->getAccess() != AS_public) { 3654 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3655 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3656 Invalid = true; 3657 } 3658 3659 // C++ [class.union]p1 3660 // An object of a class with a non-trivial constructor, a non-trivial 3661 // copy constructor, a non-trivial destructor, or a non-trivial copy 3662 // assignment operator cannot be a member of a union, nor can an 3663 // array of such objects. 3664 if (CheckNontrivialField(FD)) 3665 Invalid = true; 3666 } else if (Mem->isImplicit()) { 3667 // Any implicit members are fine. 3668 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3669 // This is a type that showed up in an 3670 // elaborated-type-specifier inside the anonymous struct or 3671 // union, but which actually declares a type outside of the 3672 // anonymous struct or union. It's okay. 3673 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3674 if (!MemRecord->isAnonymousStructOrUnion() && 3675 MemRecord->getDeclName()) { 3676 // Visual C++ allows type definition in anonymous struct or union. 3677 if (getLangOpts().MicrosoftExt) 3678 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3679 << (int)Record->isUnion(); 3680 else { 3681 // This is a nested type declaration. 3682 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3683 << (int)Record->isUnion(); 3684 Invalid = true; 3685 } 3686 } else { 3687 // This is an anonymous type definition within another anonymous type. 3688 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3689 // not part of standard C++. 3690 Diag(MemRecord->getLocation(), 3691 diag::ext_anonymous_record_with_anonymous_type) 3692 << (int)Record->isUnion(); 3693 } 3694 } else if (isa<AccessSpecDecl>(Mem)) { 3695 // Any access specifier is fine. 3696 } else { 3697 // We have something that isn't a non-static data 3698 // member. Complain about it. 3699 unsigned DK = diag::err_anonymous_record_bad_member; 3700 if (isa<TypeDecl>(Mem)) 3701 DK = diag::err_anonymous_record_with_type; 3702 else if (isa<FunctionDecl>(Mem)) 3703 DK = diag::err_anonymous_record_with_function; 3704 else if (isa<VarDecl>(Mem)) 3705 DK = diag::err_anonymous_record_with_static; 3706 3707 // Visual C++ allows type definition in anonymous struct or union. 3708 if (getLangOpts().MicrosoftExt && 3709 DK == diag::err_anonymous_record_with_type) 3710 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3711 << (int)Record->isUnion(); 3712 else { 3713 Diag(Mem->getLocation(), DK) 3714 << (int)Record->isUnion(); 3715 Invalid = true; 3716 } 3717 } 3718 } 3719 3720 // C++11 [class.union]p8 (DR1460): 3721 // At most one variant member of a union may have a 3722 // brace-or-equal-initializer. 3723 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3724 Owner->isRecord()) 3725 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3726 cast<CXXRecordDecl>(Record)); 3727 } 3728 3729 if (!Record->isUnion() && !Owner->isRecord()) { 3730 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3731 << (int)getLangOpts().CPlusPlus; 3732 Invalid = true; 3733 } 3734 3735 // Mock up a declarator. 3736 Declarator Dc(DS, Declarator::MemberContext); 3737 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3738 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3739 3740 // Create a declaration for this anonymous struct/union. 3741 NamedDecl *Anon = 0; 3742 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3743 Anon = FieldDecl::Create(Context, OwningClass, 3744 DS.getLocStart(), 3745 Record->getLocation(), 3746 /*IdentifierInfo=*/0, 3747 Context.getTypeDeclType(Record), 3748 TInfo, 3749 /*BitWidth=*/0, /*Mutable=*/false, 3750 /*InitStyle=*/ICIS_NoInit); 3751 Anon->setAccess(AS); 3752 if (getLangOpts().CPlusPlus) 3753 FieldCollector->Add(cast<FieldDecl>(Anon)); 3754 } else { 3755 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3756 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3757 if (SCSpec == DeclSpec::SCS_mutable) { 3758 // mutable can only appear on non-static class members, so it's always 3759 // an error here 3760 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3761 Invalid = true; 3762 SC = SC_None; 3763 } 3764 3765 Anon = VarDecl::Create(Context, Owner, 3766 DS.getLocStart(), 3767 Record->getLocation(), /*IdentifierInfo=*/0, 3768 Context.getTypeDeclType(Record), 3769 TInfo, SC); 3770 3771 // Default-initialize the implicit variable. This initialization will be 3772 // trivial in almost all cases, except if a union member has an in-class 3773 // initializer: 3774 // union { int n = 0; }; 3775 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3776 } 3777 Anon->setImplicit(); 3778 3779 // Mark this as an anonymous struct/union type. 3780 Record->setAnonymousStructOrUnion(true); 3781 3782 // Add the anonymous struct/union object to the current 3783 // context. We'll be referencing this object when we refer to one of 3784 // its members. 3785 Owner->addDecl(Anon); 3786 3787 // Inject the members of the anonymous struct/union into the owning 3788 // context and into the identifier resolver chain for name lookup 3789 // purposes. 3790 SmallVector<NamedDecl*, 2> Chain; 3791 Chain.push_back(Anon); 3792 3793 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3794 Chain, false)) 3795 Invalid = true; 3796 3797 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 3798 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 3799 Decl *ManglingContextDecl; 3800 if (MangleNumberingContext *MCtx = 3801 getCurrentMangleNumberContext(NewVD->getDeclContext(), 3802 ManglingContextDecl)) { 3803 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 3804 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 3805 } 3806 } 3807 } 3808 3809 if (Invalid) 3810 Anon->setInvalidDecl(); 3811 3812 return Anon; 3813 } 3814 3815 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3816 /// Microsoft C anonymous structure. 3817 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3818 /// Example: 3819 /// 3820 /// struct A { int a; }; 3821 /// struct B { struct A; int b; }; 3822 /// 3823 /// void foo() { 3824 /// B var; 3825 /// var.a = 3; 3826 /// } 3827 /// 3828 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3829 RecordDecl *Record) { 3830 3831 // If there is no Record, get the record via the typedef. 3832 if (!Record) 3833 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3834 3835 // Mock up a declarator. 3836 Declarator Dc(DS, Declarator::TypeNameContext); 3837 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3838 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3839 3840 // Create a declaration for this anonymous struct. 3841 NamedDecl* Anon = FieldDecl::Create(Context, 3842 cast<RecordDecl>(CurContext), 3843 DS.getLocStart(), 3844 DS.getLocStart(), 3845 /*IdentifierInfo=*/0, 3846 Context.getTypeDeclType(Record), 3847 TInfo, 3848 /*BitWidth=*/0, /*Mutable=*/false, 3849 /*InitStyle=*/ICIS_NoInit); 3850 Anon->setImplicit(); 3851 3852 // Add the anonymous struct object to the current context. 3853 CurContext->addDecl(Anon); 3854 3855 // Inject the members of the anonymous struct into the current 3856 // context and into the identifier resolver chain for name lookup 3857 // purposes. 3858 SmallVector<NamedDecl*, 2> Chain; 3859 Chain.push_back(Anon); 3860 3861 RecordDecl *RecordDef = Record->getDefinition(); 3862 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3863 RecordDef, AS_none, 3864 Chain, true)) 3865 Anon->setInvalidDecl(); 3866 3867 return Anon; 3868 } 3869 3870 /// GetNameForDeclarator - Determine the full declaration name for the 3871 /// given Declarator. 3872 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3873 return GetNameFromUnqualifiedId(D.getName()); 3874 } 3875 3876 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3877 DeclarationNameInfo 3878 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3879 DeclarationNameInfo NameInfo; 3880 NameInfo.setLoc(Name.StartLocation); 3881 3882 switch (Name.getKind()) { 3883 3884 case UnqualifiedId::IK_ImplicitSelfParam: 3885 case UnqualifiedId::IK_Identifier: 3886 NameInfo.setName(Name.Identifier); 3887 NameInfo.setLoc(Name.StartLocation); 3888 return NameInfo; 3889 3890 case UnqualifiedId::IK_OperatorFunctionId: 3891 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3892 Name.OperatorFunctionId.Operator)); 3893 NameInfo.setLoc(Name.StartLocation); 3894 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3895 = Name.OperatorFunctionId.SymbolLocations[0]; 3896 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3897 = Name.EndLocation.getRawEncoding(); 3898 return NameInfo; 3899 3900 case UnqualifiedId::IK_LiteralOperatorId: 3901 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3902 Name.Identifier)); 3903 NameInfo.setLoc(Name.StartLocation); 3904 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3905 return NameInfo; 3906 3907 case UnqualifiedId::IK_ConversionFunctionId: { 3908 TypeSourceInfo *TInfo; 3909 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3910 if (Ty.isNull()) 3911 return DeclarationNameInfo(); 3912 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3913 Context.getCanonicalType(Ty))); 3914 NameInfo.setLoc(Name.StartLocation); 3915 NameInfo.setNamedTypeInfo(TInfo); 3916 return NameInfo; 3917 } 3918 3919 case UnqualifiedId::IK_ConstructorName: { 3920 TypeSourceInfo *TInfo; 3921 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3922 if (Ty.isNull()) 3923 return DeclarationNameInfo(); 3924 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3925 Context.getCanonicalType(Ty))); 3926 NameInfo.setLoc(Name.StartLocation); 3927 NameInfo.setNamedTypeInfo(TInfo); 3928 return NameInfo; 3929 } 3930 3931 case UnqualifiedId::IK_ConstructorTemplateId: { 3932 // In well-formed code, we can only have a constructor 3933 // template-id that refers to the current context, so go there 3934 // to find the actual type being constructed. 3935 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3936 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3937 return DeclarationNameInfo(); 3938 3939 // Determine the type of the class being constructed. 3940 QualType CurClassType = Context.getTypeDeclType(CurClass); 3941 3942 // FIXME: Check two things: that the template-id names the same type as 3943 // CurClassType, and that the template-id does not occur when the name 3944 // was qualified. 3945 3946 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3947 Context.getCanonicalType(CurClassType))); 3948 NameInfo.setLoc(Name.StartLocation); 3949 // FIXME: should we retrieve TypeSourceInfo? 3950 NameInfo.setNamedTypeInfo(0); 3951 return NameInfo; 3952 } 3953 3954 case UnqualifiedId::IK_DestructorName: { 3955 TypeSourceInfo *TInfo; 3956 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3957 if (Ty.isNull()) 3958 return DeclarationNameInfo(); 3959 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3960 Context.getCanonicalType(Ty))); 3961 NameInfo.setLoc(Name.StartLocation); 3962 NameInfo.setNamedTypeInfo(TInfo); 3963 return NameInfo; 3964 } 3965 3966 case UnqualifiedId::IK_TemplateId: { 3967 TemplateName TName = Name.TemplateId->Template.get(); 3968 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3969 return Context.getNameForTemplate(TName, TNameLoc); 3970 } 3971 3972 } // switch (Name.getKind()) 3973 3974 llvm_unreachable("Unknown name kind"); 3975 } 3976 3977 static QualType getCoreType(QualType Ty) { 3978 do { 3979 if (Ty->isPointerType() || Ty->isReferenceType()) 3980 Ty = Ty->getPointeeType(); 3981 else if (Ty->isArrayType()) 3982 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3983 else 3984 return Ty.withoutLocalFastQualifiers(); 3985 } while (true); 3986 } 3987 3988 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3989 /// and Definition have "nearly" matching parameters. This heuristic is 3990 /// used to improve diagnostics in the case where an out-of-line function 3991 /// definition doesn't match any declaration within the class or namespace. 3992 /// Also sets Params to the list of indices to the parameters that differ 3993 /// between the declaration and the definition. If hasSimilarParameters 3994 /// returns true and Params is empty, then all of the parameters match. 3995 static bool hasSimilarParameters(ASTContext &Context, 3996 FunctionDecl *Declaration, 3997 FunctionDecl *Definition, 3998 SmallVectorImpl<unsigned> &Params) { 3999 Params.clear(); 4000 if (Declaration->param_size() != Definition->param_size()) 4001 return false; 4002 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4003 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4004 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4005 4006 // The parameter types are identical 4007 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4008 continue; 4009 4010 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4011 QualType DefParamBaseTy = getCoreType(DefParamTy); 4012 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4013 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4014 4015 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4016 (DeclTyName && DeclTyName == DefTyName)) 4017 Params.push_back(Idx); 4018 else // The two parameters aren't even close 4019 return false; 4020 } 4021 4022 return true; 4023 } 4024 4025 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4026 /// declarator needs to be rebuilt in the current instantiation. 4027 /// Any bits of declarator which appear before the name are valid for 4028 /// consideration here. That's specifically the type in the decl spec 4029 /// and the base type in any member-pointer chunks. 4030 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4031 DeclarationName Name) { 4032 // The types we specifically need to rebuild are: 4033 // - typenames, typeofs, and decltypes 4034 // - types which will become injected class names 4035 // Of course, we also need to rebuild any type referencing such a 4036 // type. It's safest to just say "dependent", but we call out a 4037 // few cases here. 4038 4039 DeclSpec &DS = D.getMutableDeclSpec(); 4040 switch (DS.getTypeSpecType()) { 4041 case DeclSpec::TST_typename: 4042 case DeclSpec::TST_typeofType: 4043 case DeclSpec::TST_underlyingType: 4044 case DeclSpec::TST_atomic: { 4045 // Grab the type from the parser. 4046 TypeSourceInfo *TSI = 0; 4047 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4048 if (T.isNull() || !T->isDependentType()) break; 4049 4050 // Make sure there's a type source info. This isn't really much 4051 // of a waste; most dependent types should have type source info 4052 // attached already. 4053 if (!TSI) 4054 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4055 4056 // Rebuild the type in the current instantiation. 4057 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4058 if (!TSI) return true; 4059 4060 // Store the new type back in the decl spec. 4061 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4062 DS.UpdateTypeRep(LocType); 4063 break; 4064 } 4065 4066 case DeclSpec::TST_decltype: 4067 case DeclSpec::TST_typeofExpr: { 4068 Expr *E = DS.getRepAsExpr(); 4069 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4070 if (Result.isInvalid()) return true; 4071 DS.UpdateExprRep(Result.get()); 4072 break; 4073 } 4074 4075 default: 4076 // Nothing to do for these decl specs. 4077 break; 4078 } 4079 4080 // It doesn't matter what order we do this in. 4081 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4082 DeclaratorChunk &Chunk = D.getTypeObject(I); 4083 4084 // The only type information in the declarator which can come 4085 // before the declaration name is the base type of a member 4086 // pointer. 4087 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4088 continue; 4089 4090 // Rebuild the scope specifier in-place. 4091 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4092 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4093 return true; 4094 } 4095 4096 return false; 4097 } 4098 4099 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4100 D.setFunctionDefinitionKind(FDK_Declaration); 4101 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4102 4103 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4104 Dcl && Dcl->getDeclContext()->isFileContext()) 4105 Dcl->setTopLevelDeclInObjCContainer(); 4106 4107 return Dcl; 4108 } 4109 4110 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4111 /// If T is the name of a class, then each of the following shall have a 4112 /// name different from T: 4113 /// - every static data member of class T; 4114 /// - every member function of class T 4115 /// - every member of class T that is itself a type; 4116 /// \returns true if the declaration name violates these rules. 4117 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4118 DeclarationNameInfo NameInfo) { 4119 DeclarationName Name = NameInfo.getName(); 4120 4121 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4122 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4123 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4124 return true; 4125 } 4126 4127 return false; 4128 } 4129 4130 /// \brief Diagnose a declaration whose declarator-id has the given 4131 /// nested-name-specifier. 4132 /// 4133 /// \param SS The nested-name-specifier of the declarator-id. 4134 /// 4135 /// \param DC The declaration context to which the nested-name-specifier 4136 /// resolves. 4137 /// 4138 /// \param Name The name of the entity being declared. 4139 /// 4140 /// \param Loc The location of the name of the entity being declared. 4141 /// 4142 /// \returns true if we cannot safely recover from this error, false otherwise. 4143 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4144 DeclarationName Name, 4145 SourceLocation Loc) { 4146 DeclContext *Cur = CurContext; 4147 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4148 Cur = Cur->getParent(); 4149 4150 // If the user provided a superfluous scope specifier that refers back to the 4151 // class in which the entity is already declared, diagnose and ignore it. 4152 // 4153 // class X { 4154 // void X::f(); 4155 // }; 4156 // 4157 // Note, it was once ill-formed to give redundant qualification in all 4158 // contexts, but that rule was removed by DR482. 4159 if (Cur->Equals(DC)) { 4160 if (Cur->isRecord()) { 4161 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4162 : diag::err_member_extra_qualification) 4163 << Name << FixItHint::CreateRemoval(SS.getRange()); 4164 SS.clear(); 4165 } else { 4166 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4167 } 4168 return false; 4169 } 4170 4171 // Check whether the qualifying scope encloses the scope of the original 4172 // declaration. 4173 if (!Cur->Encloses(DC)) { 4174 if (Cur->isRecord()) 4175 Diag(Loc, diag::err_member_qualification) 4176 << Name << SS.getRange(); 4177 else if (isa<TranslationUnitDecl>(DC)) 4178 Diag(Loc, diag::err_invalid_declarator_global_scope) 4179 << Name << SS.getRange(); 4180 else if (isa<FunctionDecl>(Cur)) 4181 Diag(Loc, diag::err_invalid_declarator_in_function) 4182 << Name << SS.getRange(); 4183 else if (isa<BlockDecl>(Cur)) 4184 Diag(Loc, diag::err_invalid_declarator_in_block) 4185 << Name << SS.getRange(); 4186 else 4187 Diag(Loc, diag::err_invalid_declarator_scope) 4188 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4189 4190 return true; 4191 } 4192 4193 if (Cur->isRecord()) { 4194 // Cannot qualify members within a class. 4195 Diag(Loc, diag::err_member_qualification) 4196 << Name << SS.getRange(); 4197 SS.clear(); 4198 4199 // C++ constructors and destructors with incorrect scopes can break 4200 // our AST invariants by having the wrong underlying types. If 4201 // that's the case, then drop this declaration entirely. 4202 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4203 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4204 !Context.hasSameType(Name.getCXXNameType(), 4205 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4206 return true; 4207 4208 return false; 4209 } 4210 4211 // C++11 [dcl.meaning]p1: 4212 // [...] "The nested-name-specifier of the qualified declarator-id shall 4213 // not begin with a decltype-specifer" 4214 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4215 while (SpecLoc.getPrefix()) 4216 SpecLoc = SpecLoc.getPrefix(); 4217 if (dyn_cast_or_null<DecltypeType>( 4218 SpecLoc.getNestedNameSpecifier()->getAsType())) 4219 Diag(Loc, diag::err_decltype_in_declarator) 4220 << SpecLoc.getTypeLoc().getSourceRange(); 4221 4222 return false; 4223 } 4224 4225 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4226 MultiTemplateParamsArg TemplateParamLists) { 4227 // TODO: consider using NameInfo for diagnostic. 4228 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4229 DeclarationName Name = NameInfo.getName(); 4230 4231 // All of these full declarators require an identifier. If it doesn't have 4232 // one, the ParsedFreeStandingDeclSpec action should be used. 4233 if (!Name) { 4234 if (!D.isInvalidType()) // Reject this if we think it is valid. 4235 Diag(D.getDeclSpec().getLocStart(), 4236 diag::err_declarator_need_ident) 4237 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4238 return 0; 4239 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4240 return 0; 4241 4242 // The scope passed in may not be a decl scope. Zip up the scope tree until 4243 // we find one that is. 4244 while ((S->getFlags() & Scope::DeclScope) == 0 || 4245 (S->getFlags() & Scope::TemplateParamScope) != 0) 4246 S = S->getParent(); 4247 4248 DeclContext *DC = CurContext; 4249 if (D.getCXXScopeSpec().isInvalid()) 4250 D.setInvalidType(); 4251 else if (D.getCXXScopeSpec().isSet()) { 4252 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4253 UPPC_DeclarationQualifier)) 4254 return 0; 4255 4256 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4257 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4258 if (!DC || isa<EnumDecl>(DC)) { 4259 // If we could not compute the declaration context, it's because the 4260 // declaration context is dependent but does not refer to a class, 4261 // class template, or class template partial specialization. Complain 4262 // and return early, to avoid the coming semantic disaster. 4263 Diag(D.getIdentifierLoc(), 4264 diag::err_template_qualified_declarator_no_match) 4265 << D.getCXXScopeSpec().getScopeRep() 4266 << D.getCXXScopeSpec().getRange(); 4267 return 0; 4268 } 4269 bool IsDependentContext = DC->isDependentContext(); 4270 4271 if (!IsDependentContext && 4272 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4273 return 0; 4274 4275 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4276 Diag(D.getIdentifierLoc(), 4277 diag::err_member_def_undefined_record) 4278 << Name << DC << D.getCXXScopeSpec().getRange(); 4279 D.setInvalidType(); 4280 } else if (!D.getDeclSpec().isFriendSpecified()) { 4281 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4282 Name, D.getIdentifierLoc())) { 4283 if (DC->isRecord()) 4284 return 0; 4285 4286 D.setInvalidType(); 4287 } 4288 } 4289 4290 // Check whether we need to rebuild the type of the given 4291 // declaration in the current instantiation. 4292 if (EnteringContext && IsDependentContext && 4293 TemplateParamLists.size() != 0) { 4294 ContextRAII SavedContext(*this, DC); 4295 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4296 D.setInvalidType(); 4297 } 4298 } 4299 4300 if (DiagnoseClassNameShadow(DC, NameInfo)) 4301 // If this is a typedef, we'll end up spewing multiple diagnostics. 4302 // Just return early; it's safer. 4303 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4304 return 0; 4305 4306 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4307 QualType R = TInfo->getType(); 4308 4309 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4310 UPPC_DeclarationType)) 4311 D.setInvalidType(); 4312 4313 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4314 ForRedeclaration); 4315 4316 // See if this is a redefinition of a variable in the same scope. 4317 if (!D.getCXXScopeSpec().isSet()) { 4318 bool IsLinkageLookup = false; 4319 bool CreateBuiltins = false; 4320 4321 // If the declaration we're planning to build will be a function 4322 // or object with linkage, then look for another declaration with 4323 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4324 // 4325 // If the declaration we're planning to build will be declared with 4326 // external linkage in the translation unit, create any builtin with 4327 // the same name. 4328 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4329 /* Do nothing*/; 4330 else if (CurContext->isFunctionOrMethod() && 4331 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4332 R->isFunctionType())) { 4333 IsLinkageLookup = true; 4334 CreateBuiltins = 4335 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4336 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4337 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4338 CreateBuiltins = true; 4339 4340 if (IsLinkageLookup) 4341 Previous.clear(LookupRedeclarationWithLinkage); 4342 4343 LookupName(Previous, S, CreateBuiltins); 4344 } else { // Something like "int foo::x;" 4345 LookupQualifiedName(Previous, DC); 4346 4347 // C++ [dcl.meaning]p1: 4348 // When the declarator-id is qualified, the declaration shall refer to a 4349 // previously declared member of the class or namespace to which the 4350 // qualifier refers (or, in the case of a namespace, of an element of the 4351 // inline namespace set of that namespace (7.3.1)) or to a specialization 4352 // thereof; [...] 4353 // 4354 // Note that we already checked the context above, and that we do not have 4355 // enough information to make sure that Previous contains the declaration 4356 // we want to match. For example, given: 4357 // 4358 // class X { 4359 // void f(); 4360 // void f(float); 4361 // }; 4362 // 4363 // void X::f(int) { } // ill-formed 4364 // 4365 // In this case, Previous will point to the overload set 4366 // containing the two f's declared in X, but neither of them 4367 // matches. 4368 4369 // C++ [dcl.meaning]p1: 4370 // [...] the member shall not merely have been introduced by a 4371 // using-declaration in the scope of the class or namespace nominated by 4372 // the nested-name-specifier of the declarator-id. 4373 RemoveUsingDecls(Previous); 4374 } 4375 4376 if (Previous.isSingleResult() && 4377 Previous.getFoundDecl()->isTemplateParameter()) { 4378 // Maybe we will complain about the shadowed template parameter. 4379 if (!D.isInvalidType()) 4380 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4381 Previous.getFoundDecl()); 4382 4383 // Just pretend that we didn't see the previous declaration. 4384 Previous.clear(); 4385 } 4386 4387 // In C++, the previous declaration we find might be a tag type 4388 // (class or enum). In this case, the new declaration will hide the 4389 // tag type. Note that this does does not apply if we're declaring a 4390 // typedef (C++ [dcl.typedef]p4). 4391 if (Previous.isSingleTagDecl() && 4392 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4393 Previous.clear(); 4394 4395 // Check that there are no default arguments other than in the parameters 4396 // of a function declaration (C++ only). 4397 if (getLangOpts().CPlusPlus) 4398 CheckExtraCXXDefaultArguments(D); 4399 4400 NamedDecl *New; 4401 4402 bool AddToScope = true; 4403 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4404 if (TemplateParamLists.size()) { 4405 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4406 return 0; 4407 } 4408 4409 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4410 } else if (R->isFunctionType()) { 4411 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4412 TemplateParamLists, 4413 AddToScope); 4414 } else { 4415 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4416 AddToScope); 4417 } 4418 4419 if (New == 0) 4420 return 0; 4421 4422 // If this has an identifier and is not an invalid redeclaration or 4423 // function template specialization, add it to the scope stack. 4424 if (New->getDeclName() && AddToScope && 4425 !(D.isRedeclaration() && New->isInvalidDecl())) { 4426 // Only make a locally-scoped extern declaration visible if it is the first 4427 // declaration of this entity. Qualified lookup for such an entity should 4428 // only find this declaration if there is no visible declaration of it. 4429 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4430 PushOnScopeChains(New, S, AddToContext); 4431 if (!AddToContext) 4432 CurContext->addHiddenDecl(New); 4433 } 4434 4435 return New; 4436 } 4437 4438 /// Helper method to turn variable array types into constant array 4439 /// types in certain situations which would otherwise be errors (for 4440 /// GCC compatibility). 4441 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4442 ASTContext &Context, 4443 bool &SizeIsNegative, 4444 llvm::APSInt &Oversized) { 4445 // This method tries to turn a variable array into a constant 4446 // array even when the size isn't an ICE. This is necessary 4447 // for compatibility with code that depends on gcc's buggy 4448 // constant expression folding, like struct {char x[(int)(char*)2];} 4449 SizeIsNegative = false; 4450 Oversized = 0; 4451 4452 if (T->isDependentType()) 4453 return QualType(); 4454 4455 QualifierCollector Qs; 4456 const Type *Ty = Qs.strip(T); 4457 4458 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4459 QualType Pointee = PTy->getPointeeType(); 4460 QualType FixedType = 4461 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4462 Oversized); 4463 if (FixedType.isNull()) return FixedType; 4464 FixedType = Context.getPointerType(FixedType); 4465 return Qs.apply(Context, FixedType); 4466 } 4467 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4468 QualType Inner = PTy->getInnerType(); 4469 QualType FixedType = 4470 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4471 Oversized); 4472 if (FixedType.isNull()) return FixedType; 4473 FixedType = Context.getParenType(FixedType); 4474 return Qs.apply(Context, FixedType); 4475 } 4476 4477 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4478 if (!VLATy) 4479 return QualType(); 4480 // FIXME: We should probably handle this case 4481 if (VLATy->getElementType()->isVariablyModifiedType()) 4482 return QualType(); 4483 4484 llvm::APSInt Res; 4485 if (!VLATy->getSizeExpr() || 4486 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4487 return QualType(); 4488 4489 // Check whether the array size is negative. 4490 if (Res.isSigned() && Res.isNegative()) { 4491 SizeIsNegative = true; 4492 return QualType(); 4493 } 4494 4495 // Check whether the array is too large to be addressed. 4496 unsigned ActiveSizeBits 4497 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4498 Res); 4499 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4500 Oversized = Res; 4501 return QualType(); 4502 } 4503 4504 return Context.getConstantArrayType(VLATy->getElementType(), 4505 Res, ArrayType::Normal, 0); 4506 } 4507 4508 static void 4509 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4510 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4511 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4512 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4513 DstPTL.getPointeeLoc()); 4514 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4515 return; 4516 } 4517 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4518 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4519 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4520 DstPTL.getInnerLoc()); 4521 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4522 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4523 return; 4524 } 4525 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4526 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4527 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4528 TypeLoc DstElemTL = DstATL.getElementLoc(); 4529 DstElemTL.initializeFullCopy(SrcElemTL); 4530 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4531 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4532 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4533 } 4534 4535 /// Helper method to turn variable array types into constant array 4536 /// types in certain situations which would otherwise be errors (for 4537 /// GCC compatibility). 4538 static TypeSourceInfo* 4539 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4540 ASTContext &Context, 4541 bool &SizeIsNegative, 4542 llvm::APSInt &Oversized) { 4543 QualType FixedTy 4544 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4545 SizeIsNegative, Oversized); 4546 if (FixedTy.isNull()) 4547 return 0; 4548 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4549 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4550 FixedTInfo->getTypeLoc()); 4551 return FixedTInfo; 4552 } 4553 4554 /// \brief Register the given locally-scoped extern "C" declaration so 4555 /// that it can be found later for redeclarations. We include any extern "C" 4556 /// declaration that is not visible in the translation unit here, not just 4557 /// function-scope declarations. 4558 void 4559 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4560 if (!getLangOpts().CPlusPlus && 4561 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4562 // Don't need to track declarations in the TU in C. 4563 return; 4564 4565 // Note that we have a locally-scoped external with this name. 4566 // FIXME: There can be multiple such declarations if they are functions marked 4567 // __attribute__((overloadable)) declared in function scope in C. 4568 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4569 } 4570 4571 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4572 if (ExternalSource) { 4573 // Load locally-scoped external decls from the external source. 4574 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4575 SmallVector<NamedDecl *, 4> Decls; 4576 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4577 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4578 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4579 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4580 if (Pos == LocallyScopedExternCDecls.end()) 4581 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4582 } 4583 } 4584 4585 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4586 return D ? D->getMostRecentDecl() : 0; 4587 } 4588 4589 /// \brief Diagnose function specifiers on a declaration of an identifier that 4590 /// does not identify a function. 4591 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4592 // FIXME: We should probably indicate the identifier in question to avoid 4593 // confusion for constructs like "inline int a(), b;" 4594 if (DS.isInlineSpecified()) 4595 Diag(DS.getInlineSpecLoc(), 4596 diag::err_inline_non_function); 4597 4598 if (DS.isVirtualSpecified()) 4599 Diag(DS.getVirtualSpecLoc(), 4600 diag::err_virtual_non_function); 4601 4602 if (DS.isExplicitSpecified()) 4603 Diag(DS.getExplicitSpecLoc(), 4604 diag::err_explicit_non_function); 4605 4606 if (DS.isNoreturnSpecified()) 4607 Diag(DS.getNoreturnSpecLoc(), 4608 diag::err_noreturn_non_function); 4609 } 4610 4611 NamedDecl* 4612 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4613 TypeSourceInfo *TInfo, LookupResult &Previous) { 4614 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4615 if (D.getCXXScopeSpec().isSet()) { 4616 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4617 << D.getCXXScopeSpec().getRange(); 4618 D.setInvalidType(); 4619 // Pretend we didn't see the scope specifier. 4620 DC = CurContext; 4621 Previous.clear(); 4622 } 4623 4624 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4625 4626 if (D.getDeclSpec().isConstexprSpecified()) 4627 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4628 << 1; 4629 4630 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4631 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4632 << D.getName().getSourceRange(); 4633 return 0; 4634 } 4635 4636 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4637 if (!NewTD) return 0; 4638 4639 // Handle attributes prior to checking for duplicates in MergeVarDecl 4640 ProcessDeclAttributes(S, NewTD, D); 4641 4642 CheckTypedefForVariablyModifiedType(S, NewTD); 4643 4644 bool Redeclaration = D.isRedeclaration(); 4645 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4646 D.setRedeclaration(Redeclaration); 4647 return ND; 4648 } 4649 4650 void 4651 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4652 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4653 // then it shall have block scope. 4654 // Note that variably modified types must be fixed before merging the decl so 4655 // that redeclarations will match. 4656 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4657 QualType T = TInfo->getType(); 4658 if (T->isVariablyModifiedType()) { 4659 getCurFunction()->setHasBranchProtectedScope(); 4660 4661 if (S->getFnParent() == 0) { 4662 bool SizeIsNegative; 4663 llvm::APSInt Oversized; 4664 TypeSourceInfo *FixedTInfo = 4665 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4666 SizeIsNegative, 4667 Oversized); 4668 if (FixedTInfo) { 4669 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4670 NewTD->setTypeSourceInfo(FixedTInfo); 4671 } else { 4672 if (SizeIsNegative) 4673 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4674 else if (T->isVariableArrayType()) 4675 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4676 else if (Oversized.getBoolValue()) 4677 Diag(NewTD->getLocation(), diag::err_array_too_large) 4678 << Oversized.toString(10); 4679 else 4680 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4681 NewTD->setInvalidDecl(); 4682 } 4683 } 4684 } 4685 } 4686 4687 4688 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4689 /// declares a typedef-name, either using the 'typedef' type specifier or via 4690 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4691 NamedDecl* 4692 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4693 LookupResult &Previous, bool &Redeclaration) { 4694 // Merge the decl with the existing one if appropriate. If the decl is 4695 // in an outer scope, it isn't the same thing. 4696 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4697 /*AllowInlineNamespace*/false); 4698 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4699 if (!Previous.empty()) { 4700 Redeclaration = true; 4701 MergeTypedefNameDecl(NewTD, Previous); 4702 } 4703 4704 // If this is the C FILE type, notify the AST context. 4705 if (IdentifierInfo *II = NewTD->getIdentifier()) 4706 if (!NewTD->isInvalidDecl() && 4707 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4708 if (II->isStr("FILE")) 4709 Context.setFILEDecl(NewTD); 4710 else if (II->isStr("jmp_buf")) 4711 Context.setjmp_bufDecl(NewTD); 4712 else if (II->isStr("sigjmp_buf")) 4713 Context.setsigjmp_bufDecl(NewTD); 4714 else if (II->isStr("ucontext_t")) 4715 Context.setucontext_tDecl(NewTD); 4716 } 4717 4718 return NewTD; 4719 } 4720 4721 /// \brief Determines whether the given declaration is an out-of-scope 4722 /// previous declaration. 4723 /// 4724 /// This routine should be invoked when name lookup has found a 4725 /// previous declaration (PrevDecl) that is not in the scope where a 4726 /// new declaration by the same name is being introduced. If the new 4727 /// declaration occurs in a local scope, previous declarations with 4728 /// linkage may still be considered previous declarations (C99 4729 /// 6.2.2p4-5, C++ [basic.link]p6). 4730 /// 4731 /// \param PrevDecl the previous declaration found by name 4732 /// lookup 4733 /// 4734 /// \param DC the context in which the new declaration is being 4735 /// declared. 4736 /// 4737 /// \returns true if PrevDecl is an out-of-scope previous declaration 4738 /// for a new delcaration with the same name. 4739 static bool 4740 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4741 ASTContext &Context) { 4742 if (!PrevDecl) 4743 return false; 4744 4745 if (!PrevDecl->hasLinkage()) 4746 return false; 4747 4748 if (Context.getLangOpts().CPlusPlus) { 4749 // C++ [basic.link]p6: 4750 // If there is a visible declaration of an entity with linkage 4751 // having the same name and type, ignoring entities declared 4752 // outside the innermost enclosing namespace scope, the block 4753 // scope declaration declares that same entity and receives the 4754 // linkage of the previous declaration. 4755 DeclContext *OuterContext = DC->getRedeclContext(); 4756 if (!OuterContext->isFunctionOrMethod()) 4757 // This rule only applies to block-scope declarations. 4758 return false; 4759 4760 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4761 if (PrevOuterContext->isRecord()) 4762 // We found a member function: ignore it. 4763 return false; 4764 4765 // Find the innermost enclosing namespace for the new and 4766 // previous declarations. 4767 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4768 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4769 4770 // The previous declaration is in a different namespace, so it 4771 // isn't the same function. 4772 if (!OuterContext->Equals(PrevOuterContext)) 4773 return false; 4774 } 4775 4776 return true; 4777 } 4778 4779 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4780 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4781 if (!SS.isSet()) return; 4782 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4783 } 4784 4785 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4786 QualType type = decl->getType(); 4787 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4788 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4789 // Various kinds of declaration aren't allowed to be __autoreleasing. 4790 unsigned kind = -1U; 4791 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4792 if (var->hasAttr<BlocksAttr>()) 4793 kind = 0; // __block 4794 else if (!var->hasLocalStorage()) 4795 kind = 1; // global 4796 } else if (isa<ObjCIvarDecl>(decl)) { 4797 kind = 3; // ivar 4798 } else if (isa<FieldDecl>(decl)) { 4799 kind = 2; // field 4800 } 4801 4802 if (kind != -1U) { 4803 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4804 << kind; 4805 } 4806 } else if (lifetime == Qualifiers::OCL_None) { 4807 // Try to infer lifetime. 4808 if (!type->isObjCLifetimeType()) 4809 return false; 4810 4811 lifetime = type->getObjCARCImplicitLifetime(); 4812 type = Context.getLifetimeQualifiedType(type, lifetime); 4813 decl->setType(type); 4814 } 4815 4816 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4817 // Thread-local variables cannot have lifetime. 4818 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4819 var->getTLSKind()) { 4820 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4821 << var->getType(); 4822 return true; 4823 } 4824 } 4825 4826 return false; 4827 } 4828 4829 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4830 // Ensure that an auto decl is deduced otherwise the checks below might cache 4831 // the wrong linkage. 4832 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4833 4834 // 'weak' only applies to declarations with external linkage. 4835 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4836 if (!ND.isExternallyVisible()) { 4837 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4838 ND.dropAttr<WeakAttr>(); 4839 } 4840 } 4841 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4842 if (ND.isExternallyVisible()) { 4843 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4844 ND.dropAttr<WeakRefAttr>(); 4845 } 4846 } 4847 4848 // 'selectany' only applies to externally visible varable declarations. 4849 // It does not apply to functions. 4850 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4851 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4852 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4853 ND.dropAttr<SelectAnyAttr>(); 4854 } 4855 } 4856 } 4857 4858 /// Given that we are within the definition of the given function, 4859 /// will that definition behave like C99's 'inline', where the 4860 /// definition is discarded except for optimization purposes? 4861 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4862 // Try to avoid calling GetGVALinkageForFunction. 4863 4864 // All cases of this require the 'inline' keyword. 4865 if (!FD->isInlined()) return false; 4866 4867 // This is only possible in C++ with the gnu_inline attribute. 4868 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4869 return false; 4870 4871 // Okay, go ahead and call the relatively-more-expensive function. 4872 4873 #ifndef NDEBUG 4874 // AST quite reasonably asserts that it's working on a function 4875 // definition. We don't really have a way to tell it that we're 4876 // currently defining the function, so just lie to it in +Asserts 4877 // builds. This is an awful hack. 4878 FD->setLazyBody(1); 4879 #endif 4880 4881 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4882 4883 #ifndef NDEBUG 4884 FD->setLazyBody(0); 4885 #endif 4886 4887 return isC99Inline; 4888 } 4889 4890 /// Determine whether a variable is extern "C" prior to attaching 4891 /// an initializer. We can't just call isExternC() here, because that 4892 /// will also compute and cache whether the declaration is externally 4893 /// visible, which might change when we attach the initializer. 4894 /// 4895 /// This can only be used if the declaration is known to not be a 4896 /// redeclaration of an internal linkage declaration. 4897 /// 4898 /// For instance: 4899 /// 4900 /// auto x = []{}; 4901 /// 4902 /// Attaching the initializer here makes this declaration not externally 4903 /// visible, because its type has internal linkage. 4904 /// 4905 /// FIXME: This is a hack. 4906 template<typename T> 4907 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4908 if (S.getLangOpts().CPlusPlus) { 4909 // In C++, the overloadable attribute negates the effects of extern "C". 4910 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4911 return false; 4912 } 4913 return D->isExternC(); 4914 } 4915 4916 static bool shouldConsiderLinkage(const VarDecl *VD) { 4917 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4918 if (DC->isFunctionOrMethod()) 4919 return VD->hasExternalStorage(); 4920 if (DC->isFileContext()) 4921 return true; 4922 if (DC->isRecord()) 4923 return false; 4924 llvm_unreachable("Unexpected context"); 4925 } 4926 4927 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4928 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4929 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4930 return true; 4931 if (DC->isRecord()) 4932 return false; 4933 llvm_unreachable("Unexpected context"); 4934 } 4935 4936 /// Adjust the \c DeclContext for a function or variable that might be a 4937 /// function-local external declaration. 4938 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 4939 if (!DC->isFunctionOrMethod()) 4940 return false; 4941 4942 // If this is a local extern function or variable declared within a function 4943 // template, don't add it into the enclosing namespace scope until it is 4944 // instantiated; it might have a dependent type right now. 4945 if (DC->isDependentContext()) 4946 return true; 4947 4948 // C++11 [basic.link]p7: 4949 // When a block scope declaration of an entity with linkage is not found to 4950 // refer to some other declaration, then that entity is a member of the 4951 // innermost enclosing namespace. 4952 // 4953 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 4954 // semantically-enclosing namespace, not a lexically-enclosing one. 4955 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 4956 DC = DC->getParent(); 4957 return true; 4958 } 4959 4960 NamedDecl * 4961 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4962 TypeSourceInfo *TInfo, LookupResult &Previous, 4963 MultiTemplateParamsArg TemplateParamLists, 4964 bool &AddToScope) { 4965 QualType R = TInfo->getType(); 4966 DeclarationName Name = GetNameForDeclarator(D).getName(); 4967 4968 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4969 VarDecl::StorageClass SC = 4970 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 4971 4972 DeclContext *OriginalDC = DC; 4973 bool IsLocalExternDecl = SC == SC_Extern && 4974 adjustContextForLocalExternDecl(DC); 4975 4976 if (getLangOpts().OpenCL) { 4977 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 4978 QualType NR = R; 4979 while (NR->isPointerType()) { 4980 if (NR->isFunctionPointerType()) { 4981 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 4982 D.setInvalidType(); 4983 break; 4984 } 4985 NR = NR->getPointeeType(); 4986 } 4987 4988 if (!getOpenCLOptions().cl_khr_fp16) { 4989 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4990 // half array type (unless the cl_khr_fp16 extension is enabled). 4991 if (Context.getBaseElementType(R)->isHalfType()) { 4992 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4993 D.setInvalidType(); 4994 } 4995 } 4996 } 4997 4998 if (SCSpec == DeclSpec::SCS_mutable) { 4999 // mutable can only appear on non-static class members, so it's always 5000 // an error here 5001 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5002 D.setInvalidType(); 5003 SC = SC_None; 5004 } 5005 5006 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5007 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5008 D.getDeclSpec().getStorageClassSpecLoc())) { 5009 // In C++11, the 'register' storage class specifier is deprecated. 5010 // Suppress the warning in system macros, it's used in macros in some 5011 // popular C system headers, such as in glibc's htonl() macro. 5012 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5013 diag::warn_deprecated_register) 5014 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5015 } 5016 5017 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5018 if (!II) { 5019 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5020 << Name; 5021 return 0; 5022 } 5023 5024 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5025 5026 if (!DC->isRecord() && S->getFnParent() == 0) { 5027 // C99 6.9p2: The storage-class specifiers auto and register shall not 5028 // appear in the declaration specifiers in an external declaration. 5029 if (SC == SC_Auto || SC == SC_Register) { 5030 // If this is a register variable with an asm label specified, then this 5031 // is a GNU extension. 5032 if (SC == SC_Register && D.getAsmLabel()) 5033 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 5034 else 5035 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5036 D.setInvalidType(); 5037 } 5038 } 5039 5040 if (getLangOpts().OpenCL) { 5041 // Set up the special work-group-local storage class for variables in the 5042 // OpenCL __local address space. 5043 if (R.getAddressSpace() == LangAS::opencl_local) { 5044 SC = SC_OpenCLWorkGroupLocal; 5045 } 5046 5047 // OpenCL v1.2 s6.9.b p4: 5048 // The sampler type cannot be used with the __local and __global address 5049 // space qualifiers. 5050 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5051 R.getAddressSpace() == LangAS::opencl_global)) { 5052 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5053 } 5054 5055 // OpenCL 1.2 spec, p6.9 r: 5056 // The event type cannot be used to declare a program scope variable. 5057 // The event type cannot be used with the __local, __constant and __global 5058 // address space qualifiers. 5059 if (R->isEventT()) { 5060 if (S->getParent() == 0) { 5061 Diag(D.getLocStart(), diag::err_event_t_global_var); 5062 D.setInvalidType(); 5063 } 5064 5065 if (R.getAddressSpace()) { 5066 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5067 D.setInvalidType(); 5068 } 5069 } 5070 } 5071 5072 bool IsExplicitSpecialization = false; 5073 bool IsVariableTemplateSpecialization = false; 5074 bool IsPartialSpecialization = false; 5075 bool IsVariableTemplate = false; 5076 VarDecl *NewVD = 0; 5077 VarTemplateDecl *NewTemplate = 0; 5078 TemplateParameterList *TemplateParams = 0; 5079 if (!getLangOpts().CPlusPlus) { 5080 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5081 D.getIdentifierLoc(), II, 5082 R, TInfo, SC); 5083 5084 if (D.isInvalidType()) 5085 NewVD->setInvalidDecl(); 5086 } else { 5087 bool Invalid = false; 5088 5089 if (DC->isRecord() && !CurContext->isRecord()) { 5090 // This is an out-of-line definition of a static data member. 5091 switch (SC) { 5092 case SC_None: 5093 break; 5094 case SC_Static: 5095 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5096 diag::err_static_out_of_line) 5097 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5098 break; 5099 case SC_Auto: 5100 case SC_Register: 5101 case SC_Extern: 5102 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5103 // to names of variables declared in a block or to function parameters. 5104 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5105 // of class members 5106 5107 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5108 diag::err_storage_class_for_static_member) 5109 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5110 break; 5111 case SC_PrivateExtern: 5112 llvm_unreachable("C storage class in c++!"); 5113 case SC_OpenCLWorkGroupLocal: 5114 llvm_unreachable("OpenCL storage class in c++!"); 5115 } 5116 } 5117 5118 if (SC == SC_Static && CurContext->isRecord()) { 5119 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5120 if (RD->isLocalClass()) 5121 Diag(D.getIdentifierLoc(), 5122 diag::err_static_data_member_not_allowed_in_local_class) 5123 << Name << RD->getDeclName(); 5124 5125 // C++98 [class.union]p1: If a union contains a static data member, 5126 // the program is ill-formed. C++11 drops this restriction. 5127 if (RD->isUnion()) 5128 Diag(D.getIdentifierLoc(), 5129 getLangOpts().CPlusPlus11 5130 ? diag::warn_cxx98_compat_static_data_member_in_union 5131 : diag::ext_static_data_member_in_union) << Name; 5132 // We conservatively disallow static data members in anonymous structs. 5133 else if (!RD->getDeclName()) 5134 Diag(D.getIdentifierLoc(), 5135 diag::err_static_data_member_not_allowed_in_anon_struct) 5136 << Name << RD->isUnion(); 5137 } 5138 } 5139 5140 // Match up the template parameter lists with the scope specifier, then 5141 // determine whether we have a template or a template specialization. 5142 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5143 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5144 D.getCXXScopeSpec(), TemplateParamLists, 5145 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5146 5147 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId && 5148 !TemplateParams) { 5149 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5150 5151 // We have encountered something that the user meant to be a 5152 // specialization (because it has explicitly-specified template 5153 // arguments) but that was not introduced with a "template<>" (or had 5154 // too few of them). 5155 // FIXME: Differentiate between attempts for explicit instantiations 5156 // (starting with "template") and the rest. 5157 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5158 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5159 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5160 "template<> "); 5161 IsExplicitSpecialization = true; 5162 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(), 5163 SourceLocation(), 0, 0, 5164 SourceLocation()); 5165 } 5166 5167 if (TemplateParams) { 5168 if (!TemplateParams->size() && 5169 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5170 // There is an extraneous 'template<>' for this variable. Complain 5171 // about it, but allow the declaration of the variable. 5172 Diag(TemplateParams->getTemplateLoc(), 5173 diag::err_template_variable_noparams) 5174 << II 5175 << SourceRange(TemplateParams->getTemplateLoc(), 5176 TemplateParams->getRAngleLoc()); 5177 TemplateParams = 0; 5178 } else { 5179 // Only C++1y supports variable templates (N3651). 5180 Diag(D.getIdentifierLoc(), 5181 getLangOpts().CPlusPlus1y 5182 ? diag::warn_cxx11_compat_variable_template 5183 : diag::ext_variable_template); 5184 5185 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5186 // This is an explicit specialization or a partial specialization. 5187 // FIXME: Check that we can declare a specialization here. 5188 IsVariableTemplateSpecialization = true; 5189 IsPartialSpecialization = TemplateParams->size() > 0; 5190 } else { // if (TemplateParams->size() > 0) 5191 // This is a template declaration. 5192 IsVariableTemplate = true; 5193 5194 // Check that we can declare a template here. 5195 if (CheckTemplateDeclScope(S, TemplateParams)) 5196 return 0; 5197 } 5198 } 5199 } 5200 5201 if (IsVariableTemplateSpecialization) { 5202 SourceLocation TemplateKWLoc = 5203 TemplateParamLists.size() > 0 5204 ? TemplateParamLists[0]->getTemplateLoc() 5205 : SourceLocation(); 5206 DeclResult Res = ActOnVarTemplateSpecialization( 5207 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5208 IsPartialSpecialization); 5209 if (Res.isInvalid()) 5210 return 0; 5211 NewVD = cast<VarDecl>(Res.get()); 5212 AddToScope = false; 5213 } else 5214 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5215 D.getIdentifierLoc(), II, R, TInfo, SC); 5216 5217 // If this is supposed to be a variable template, create it as such. 5218 if (IsVariableTemplate) { 5219 NewTemplate = 5220 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5221 TemplateParams, NewVD); 5222 NewVD->setDescribedVarTemplate(NewTemplate); 5223 } 5224 5225 // If this decl has an auto type in need of deduction, make a note of the 5226 // Decl so we can diagnose uses of it in its own initializer. 5227 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5228 ParsingInitForAutoVars.insert(NewVD); 5229 5230 if (D.isInvalidType() || Invalid) { 5231 NewVD->setInvalidDecl(); 5232 if (NewTemplate) 5233 NewTemplate->setInvalidDecl(); 5234 } 5235 5236 SetNestedNameSpecifier(NewVD, D); 5237 5238 // If we have any template parameter lists that don't directly belong to 5239 // the variable (matching the scope specifier), store them. 5240 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5241 if (TemplateParamLists.size() > VDTemplateParamLists) 5242 NewVD->setTemplateParameterListsInfo( 5243 Context, TemplateParamLists.size() - VDTemplateParamLists, 5244 TemplateParamLists.data()); 5245 5246 if (D.getDeclSpec().isConstexprSpecified()) 5247 NewVD->setConstexpr(true); 5248 } 5249 5250 // Set the lexical context. If the declarator has a C++ scope specifier, the 5251 // lexical context will be different from the semantic context. 5252 NewVD->setLexicalDeclContext(CurContext); 5253 if (NewTemplate) 5254 NewTemplate->setLexicalDeclContext(CurContext); 5255 5256 if (IsLocalExternDecl) 5257 NewVD->setLocalExternDecl(); 5258 5259 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5260 if (NewVD->hasLocalStorage()) { 5261 // C++11 [dcl.stc]p4: 5262 // When thread_local is applied to a variable of block scope the 5263 // storage-class-specifier static is implied if it does not appear 5264 // explicitly. 5265 // Core issue: 'static' is not implied if the variable is declared 5266 // 'extern'. 5267 if (SCSpec == DeclSpec::SCS_unspecified && 5268 TSCS == DeclSpec::TSCS_thread_local && 5269 DC->isFunctionOrMethod()) 5270 NewVD->setTSCSpec(TSCS); 5271 else 5272 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5273 diag::err_thread_non_global) 5274 << DeclSpec::getSpecifierName(TSCS); 5275 } else if (!Context.getTargetInfo().isTLSSupported()) 5276 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5277 diag::err_thread_unsupported); 5278 else 5279 NewVD->setTSCSpec(TSCS); 5280 } 5281 5282 // C99 6.7.4p3 5283 // An inline definition of a function with external linkage shall 5284 // not contain a definition of a modifiable object with static or 5285 // thread storage duration... 5286 // We only apply this when the function is required to be defined 5287 // elsewhere, i.e. when the function is not 'extern inline'. Note 5288 // that a local variable with thread storage duration still has to 5289 // be marked 'static'. Also note that it's possible to get these 5290 // semantics in C++ using __attribute__((gnu_inline)). 5291 if (SC == SC_Static && S->getFnParent() != 0 && 5292 !NewVD->getType().isConstQualified()) { 5293 FunctionDecl *CurFD = getCurFunctionDecl(); 5294 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5295 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5296 diag::warn_static_local_in_extern_inline); 5297 MaybeSuggestAddingStaticToDecl(CurFD); 5298 } 5299 } 5300 5301 if (D.getDeclSpec().isModulePrivateSpecified()) { 5302 if (IsVariableTemplateSpecialization) 5303 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5304 << (IsPartialSpecialization ? 1 : 0) 5305 << FixItHint::CreateRemoval( 5306 D.getDeclSpec().getModulePrivateSpecLoc()); 5307 else if (IsExplicitSpecialization) 5308 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5309 << 2 5310 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5311 else if (NewVD->hasLocalStorage()) 5312 Diag(NewVD->getLocation(), diag::err_module_private_local) 5313 << 0 << NewVD->getDeclName() 5314 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5315 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5316 else { 5317 NewVD->setModulePrivate(); 5318 if (NewTemplate) 5319 NewTemplate->setModulePrivate(); 5320 } 5321 } 5322 5323 // Handle attributes prior to checking for duplicates in MergeVarDecl 5324 ProcessDeclAttributes(S, NewVD, D); 5325 5326 if (NewVD->hasAttrs()) 5327 CheckAlignasUnderalignment(NewVD); 5328 5329 if (getLangOpts().CUDA) { 5330 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5331 // storage [duration]." 5332 if (SC == SC_None && S->getFnParent() != 0 && 5333 (NewVD->hasAttr<CUDASharedAttr>() || 5334 NewVD->hasAttr<CUDAConstantAttr>())) { 5335 NewVD->setStorageClass(SC_Static); 5336 } 5337 } 5338 5339 // In auto-retain/release, infer strong retension for variables of 5340 // retainable type. 5341 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5342 NewVD->setInvalidDecl(); 5343 5344 // Handle GNU asm-label extension (encoded as an attribute). 5345 if (Expr *E = (Expr*)D.getAsmLabel()) { 5346 // The parser guarantees this is a string. 5347 StringLiteral *SE = cast<StringLiteral>(E); 5348 StringRef Label = SE->getString(); 5349 if (S->getFnParent() != 0) { 5350 switch (SC) { 5351 case SC_None: 5352 case SC_Auto: 5353 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5354 break; 5355 case SC_Register: 5356 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5357 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5358 break; 5359 case SC_Static: 5360 case SC_Extern: 5361 case SC_PrivateExtern: 5362 case SC_OpenCLWorkGroupLocal: 5363 break; 5364 } 5365 } 5366 5367 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5368 Context, Label, 0)); 5369 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5370 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5371 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5372 if (I != ExtnameUndeclaredIdentifiers.end()) { 5373 NewVD->addAttr(I->second); 5374 ExtnameUndeclaredIdentifiers.erase(I); 5375 } 5376 } 5377 5378 // Diagnose shadowed variables before filtering for scope. 5379 if (D.getCXXScopeSpec().isEmpty()) 5380 CheckShadow(S, NewVD, Previous); 5381 5382 // Don't consider existing declarations that are in a different 5383 // scope and are out-of-semantic-context declarations (if the new 5384 // declaration has linkage). 5385 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5386 D.getCXXScopeSpec().isNotEmpty() || 5387 IsExplicitSpecialization || 5388 IsVariableTemplateSpecialization); 5389 5390 // Check whether the previous declaration is in the same block scope. This 5391 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5392 if (getLangOpts().CPlusPlus && 5393 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5394 NewVD->setPreviousDeclInSameBlockScope( 5395 Previous.isSingleResult() && !Previous.isShadowed() && 5396 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5397 5398 if (!getLangOpts().CPlusPlus) { 5399 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5400 } else { 5401 // If this is an explicit specialization of a static data member, check it. 5402 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5403 CheckMemberSpecialization(NewVD, Previous)) 5404 NewVD->setInvalidDecl(); 5405 5406 // Merge the decl with the existing one if appropriate. 5407 if (!Previous.empty()) { 5408 if (Previous.isSingleResult() && 5409 isa<FieldDecl>(Previous.getFoundDecl()) && 5410 D.getCXXScopeSpec().isSet()) { 5411 // The user tried to define a non-static data member 5412 // out-of-line (C++ [dcl.meaning]p1). 5413 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5414 << D.getCXXScopeSpec().getRange(); 5415 Previous.clear(); 5416 NewVD->setInvalidDecl(); 5417 } 5418 } else if (D.getCXXScopeSpec().isSet()) { 5419 // No previous declaration in the qualifying scope. 5420 Diag(D.getIdentifierLoc(), diag::err_no_member) 5421 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5422 << D.getCXXScopeSpec().getRange(); 5423 NewVD->setInvalidDecl(); 5424 } 5425 5426 if (!IsVariableTemplateSpecialization) 5427 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5428 5429 if (NewTemplate) { 5430 VarTemplateDecl *PrevVarTemplate = 5431 NewVD->getPreviousDecl() 5432 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5433 : 0; 5434 5435 // Check the template parameter list of this declaration, possibly 5436 // merging in the template parameter list from the previous variable 5437 // template declaration. 5438 if (CheckTemplateParameterList( 5439 TemplateParams, 5440 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5441 : 0, 5442 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5443 DC->isDependentContext()) 5444 ? TPC_ClassTemplateMember 5445 : TPC_VarTemplate)) 5446 NewVD->setInvalidDecl(); 5447 5448 // If we are providing an explicit specialization of a static variable 5449 // template, make a note of that. 5450 if (PrevVarTemplate && 5451 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5452 PrevVarTemplate->setMemberSpecialization(); 5453 } 5454 } 5455 5456 ProcessPragmaWeak(S, NewVD); 5457 5458 // If this is the first declaration of an extern C variable, update 5459 // the map of such variables. 5460 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5461 isIncompleteDeclExternC(*this, NewVD)) 5462 RegisterLocallyScopedExternCDecl(NewVD, S); 5463 5464 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5465 Decl *ManglingContextDecl; 5466 if (MangleNumberingContext *MCtx = 5467 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5468 ManglingContextDecl)) { 5469 Context.setManglingNumber( 5470 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5471 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5472 } 5473 } 5474 5475 if (NewTemplate) { 5476 if (NewVD->isInvalidDecl()) 5477 NewTemplate->setInvalidDecl(); 5478 ActOnDocumentableDecl(NewTemplate); 5479 return NewTemplate; 5480 } 5481 5482 return NewVD; 5483 } 5484 5485 /// \brief Diagnose variable or built-in function shadowing. Implements 5486 /// -Wshadow. 5487 /// 5488 /// This method is called whenever a VarDecl is added to a "useful" 5489 /// scope. 5490 /// 5491 /// \param S the scope in which the shadowing name is being declared 5492 /// \param R the lookup of the name 5493 /// 5494 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5495 // Return if warning is ignored. 5496 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5497 DiagnosticsEngine::Ignored) 5498 return; 5499 5500 // Don't diagnose declarations at file scope. 5501 if (D->hasGlobalStorage()) 5502 return; 5503 5504 DeclContext *NewDC = D->getDeclContext(); 5505 5506 // Only diagnose if we're shadowing an unambiguous field or variable. 5507 if (R.getResultKind() != LookupResult::Found) 5508 return; 5509 5510 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5511 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5512 return; 5513 5514 // Fields are not shadowed by variables in C++ static methods. 5515 if (isa<FieldDecl>(ShadowedDecl)) 5516 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5517 if (MD->isStatic()) 5518 return; 5519 5520 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5521 if (shadowedVar->isExternC()) { 5522 // For shadowing external vars, make sure that we point to the global 5523 // declaration, not a locally scoped extern declaration. 5524 for (auto I : shadowedVar->redecls()) 5525 if (I->isFileVarDecl()) { 5526 ShadowedDecl = I; 5527 break; 5528 } 5529 } 5530 5531 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5532 5533 // Only warn about certain kinds of shadowing for class members. 5534 if (NewDC && NewDC->isRecord()) { 5535 // In particular, don't warn about shadowing non-class members. 5536 if (!OldDC->isRecord()) 5537 return; 5538 5539 // TODO: should we warn about static data members shadowing 5540 // static data members from base classes? 5541 5542 // TODO: don't diagnose for inaccessible shadowed members. 5543 // This is hard to do perfectly because we might friend the 5544 // shadowing context, but that's just a false negative. 5545 } 5546 5547 // Determine what kind of declaration we're shadowing. 5548 unsigned Kind; 5549 if (isa<RecordDecl>(OldDC)) { 5550 if (isa<FieldDecl>(ShadowedDecl)) 5551 Kind = 3; // field 5552 else 5553 Kind = 2; // static data member 5554 } else if (OldDC->isFileContext()) 5555 Kind = 1; // global 5556 else 5557 Kind = 0; // local 5558 5559 DeclarationName Name = R.getLookupName(); 5560 5561 // Emit warning and note. 5562 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5563 return; 5564 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5565 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5566 } 5567 5568 /// \brief Check -Wshadow without the advantage of a previous lookup. 5569 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5570 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5571 DiagnosticsEngine::Ignored) 5572 return; 5573 5574 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5575 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5576 LookupName(R, S); 5577 CheckShadow(S, D, R); 5578 } 5579 5580 /// Check for conflict between this global or extern "C" declaration and 5581 /// previous global or extern "C" declarations. This is only used in C++. 5582 template<typename T> 5583 static bool checkGlobalOrExternCConflict( 5584 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5585 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5586 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5587 5588 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5589 // The common case: this global doesn't conflict with any extern "C" 5590 // declaration. 5591 return false; 5592 } 5593 5594 if (Prev) { 5595 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5596 // Both the old and new declarations have C language linkage. This is a 5597 // redeclaration. 5598 Previous.clear(); 5599 Previous.addDecl(Prev); 5600 return true; 5601 } 5602 5603 // This is a global, non-extern "C" declaration, and there is a previous 5604 // non-global extern "C" declaration. Diagnose if this is a variable 5605 // declaration. 5606 if (!isa<VarDecl>(ND)) 5607 return false; 5608 } else { 5609 // The declaration is extern "C". Check for any declaration in the 5610 // translation unit which might conflict. 5611 if (IsGlobal) { 5612 // We have already performed the lookup into the translation unit. 5613 IsGlobal = false; 5614 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5615 I != E; ++I) { 5616 if (isa<VarDecl>(*I)) { 5617 Prev = *I; 5618 break; 5619 } 5620 } 5621 } else { 5622 DeclContext::lookup_result R = 5623 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5624 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5625 I != E; ++I) { 5626 if (isa<VarDecl>(*I)) { 5627 Prev = *I; 5628 break; 5629 } 5630 // FIXME: If we have any other entity with this name in global scope, 5631 // the declaration is ill-formed, but that is a defect: it breaks the 5632 // 'stat' hack, for instance. Only variables can have mangled name 5633 // clashes with extern "C" declarations, so only they deserve a 5634 // diagnostic. 5635 } 5636 } 5637 5638 if (!Prev) 5639 return false; 5640 } 5641 5642 // Use the first declaration's location to ensure we point at something which 5643 // is lexically inside an extern "C" linkage-spec. 5644 assert(Prev && "should have found a previous declaration to diagnose"); 5645 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5646 Prev = FD->getFirstDecl(); 5647 else 5648 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5649 5650 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5651 << IsGlobal << ND; 5652 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5653 << IsGlobal; 5654 return false; 5655 } 5656 5657 /// Apply special rules for handling extern "C" declarations. Returns \c true 5658 /// if we have found that this is a redeclaration of some prior entity. 5659 /// 5660 /// Per C++ [dcl.link]p6: 5661 /// Two declarations [for a function or variable] with C language linkage 5662 /// with the same name that appear in different scopes refer to the same 5663 /// [entity]. An entity with C language linkage shall not be declared with 5664 /// the same name as an entity in global scope. 5665 template<typename T> 5666 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5667 LookupResult &Previous) { 5668 if (!S.getLangOpts().CPlusPlus) { 5669 // In C, when declaring a global variable, look for a corresponding 'extern' 5670 // variable declared in function scope. We don't need this in C++, because 5671 // we find local extern decls in the surrounding file-scope DeclContext. 5672 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5673 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5674 Previous.clear(); 5675 Previous.addDecl(Prev); 5676 return true; 5677 } 5678 } 5679 return false; 5680 } 5681 5682 // A declaration in the translation unit can conflict with an extern "C" 5683 // declaration. 5684 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5685 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5686 5687 // An extern "C" declaration can conflict with a declaration in the 5688 // translation unit or can be a redeclaration of an extern "C" declaration 5689 // in another scope. 5690 if (isIncompleteDeclExternC(S,ND)) 5691 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5692 5693 // Neither global nor extern "C": nothing to do. 5694 return false; 5695 } 5696 5697 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5698 // If the decl is already known invalid, don't check it. 5699 if (NewVD->isInvalidDecl()) 5700 return; 5701 5702 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5703 QualType T = TInfo->getType(); 5704 5705 // Defer checking an 'auto' type until its initializer is attached. 5706 if (T->isUndeducedType()) 5707 return; 5708 5709 if (T->isObjCObjectType()) { 5710 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5711 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5712 T = Context.getObjCObjectPointerType(T); 5713 NewVD->setType(T); 5714 } 5715 5716 // Emit an error if an address space was applied to decl with local storage. 5717 // This includes arrays of objects with address space qualifiers, but not 5718 // automatic variables that point to other address spaces. 5719 // ISO/IEC TR 18037 S5.1.2 5720 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5721 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5722 NewVD->setInvalidDecl(); 5723 return; 5724 } 5725 5726 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5727 // __constant address space. 5728 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5729 && T.getAddressSpace() != LangAS::opencl_constant 5730 && !T->isSamplerT()){ 5731 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5732 NewVD->setInvalidDecl(); 5733 return; 5734 } 5735 5736 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5737 // scope. 5738 if ((getLangOpts().OpenCLVersion >= 120) 5739 && NewVD->isStaticLocal()) { 5740 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5741 NewVD->setInvalidDecl(); 5742 return; 5743 } 5744 5745 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5746 && !NewVD->hasAttr<BlocksAttr>()) { 5747 if (getLangOpts().getGC() != LangOptions::NonGC) 5748 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5749 else { 5750 assert(!getLangOpts().ObjCAutoRefCount); 5751 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5752 } 5753 } 5754 5755 bool isVM = T->isVariablyModifiedType(); 5756 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5757 NewVD->hasAttr<BlocksAttr>()) 5758 getCurFunction()->setHasBranchProtectedScope(); 5759 5760 if ((isVM && NewVD->hasLinkage()) || 5761 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5762 bool SizeIsNegative; 5763 llvm::APSInt Oversized; 5764 TypeSourceInfo *FixedTInfo = 5765 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5766 SizeIsNegative, Oversized); 5767 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5768 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5769 // FIXME: This won't give the correct result for 5770 // int a[10][n]; 5771 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5772 5773 if (NewVD->isFileVarDecl()) 5774 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5775 << SizeRange; 5776 else if (NewVD->isStaticLocal()) 5777 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5778 << SizeRange; 5779 else 5780 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5781 << SizeRange; 5782 NewVD->setInvalidDecl(); 5783 return; 5784 } 5785 5786 if (FixedTInfo == 0) { 5787 if (NewVD->isFileVarDecl()) 5788 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5789 else 5790 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5791 NewVD->setInvalidDecl(); 5792 return; 5793 } 5794 5795 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5796 NewVD->setType(FixedTInfo->getType()); 5797 NewVD->setTypeSourceInfo(FixedTInfo); 5798 } 5799 5800 if (T->isVoidType()) { 5801 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5802 // of objects and functions. 5803 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5804 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5805 << T; 5806 NewVD->setInvalidDecl(); 5807 return; 5808 } 5809 } 5810 5811 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5812 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5813 NewVD->setInvalidDecl(); 5814 return; 5815 } 5816 5817 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5818 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5819 NewVD->setInvalidDecl(); 5820 return; 5821 } 5822 5823 if (NewVD->isConstexpr() && !T->isDependentType() && 5824 RequireLiteralType(NewVD->getLocation(), T, 5825 diag::err_constexpr_var_non_literal)) { 5826 // Can't perform this check until the type is deduced. 5827 NewVD->setInvalidDecl(); 5828 return; 5829 } 5830 } 5831 5832 /// \brief Perform semantic checking on a newly-created variable 5833 /// declaration. 5834 /// 5835 /// This routine performs all of the type-checking required for a 5836 /// variable declaration once it has been built. It is used both to 5837 /// check variables after they have been parsed and their declarators 5838 /// have been translated into a declaration, and to check variables 5839 /// that have been instantiated from a template. 5840 /// 5841 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5842 /// 5843 /// Returns true if the variable declaration is a redeclaration. 5844 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5845 CheckVariableDeclarationType(NewVD); 5846 5847 // If the decl is already known invalid, don't check it. 5848 if (NewVD->isInvalidDecl()) 5849 return false; 5850 5851 // If we did not find anything by this name, look for a non-visible 5852 // extern "C" declaration with the same name. 5853 if (Previous.empty() && 5854 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5855 Previous.setShadowed(); 5856 5857 // Filter out any non-conflicting previous declarations. 5858 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5859 5860 if (!Previous.empty()) { 5861 MergeVarDecl(NewVD, Previous); 5862 return true; 5863 } 5864 return false; 5865 } 5866 5867 /// \brief Data used with FindOverriddenMethod 5868 struct FindOverriddenMethodData { 5869 Sema *S; 5870 CXXMethodDecl *Method; 5871 }; 5872 5873 /// \brief Member lookup function that determines whether a given C++ 5874 /// method overrides a method in a base class, to be used with 5875 /// CXXRecordDecl::lookupInBases(). 5876 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5877 CXXBasePath &Path, 5878 void *UserData) { 5879 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5880 5881 FindOverriddenMethodData *Data 5882 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5883 5884 DeclarationName Name = Data->Method->getDeclName(); 5885 5886 // FIXME: Do we care about other names here too? 5887 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5888 // We really want to find the base class destructor here. 5889 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5890 CanQualType CT = Data->S->Context.getCanonicalType(T); 5891 5892 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5893 } 5894 5895 for (Path.Decls = BaseRecord->lookup(Name); 5896 !Path.Decls.empty(); 5897 Path.Decls = Path.Decls.slice(1)) { 5898 NamedDecl *D = Path.Decls.front(); 5899 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5900 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5901 return true; 5902 } 5903 } 5904 5905 return false; 5906 } 5907 5908 namespace { 5909 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5910 } 5911 /// \brief Report an error regarding overriding, along with any relevant 5912 /// overriden methods. 5913 /// 5914 /// \param DiagID the primary error to report. 5915 /// \param MD the overriding method. 5916 /// \param OEK which overrides to include as notes. 5917 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5918 OverrideErrorKind OEK = OEK_All) { 5919 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5920 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5921 E = MD->end_overridden_methods(); 5922 I != E; ++I) { 5923 // This check (& the OEK parameter) could be replaced by a predicate, but 5924 // without lambdas that would be overkill. This is still nicer than writing 5925 // out the diag loop 3 times. 5926 if ((OEK == OEK_All) || 5927 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5928 (OEK == OEK_Deleted && (*I)->isDeleted())) 5929 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5930 } 5931 } 5932 5933 /// AddOverriddenMethods - See if a method overrides any in the base classes, 5934 /// and if so, check that it's a valid override and remember it. 5935 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5936 // Look for virtual methods in base classes that this method might override. 5937 CXXBasePaths Paths; 5938 FindOverriddenMethodData Data; 5939 Data.Method = MD; 5940 Data.S = this; 5941 bool hasDeletedOverridenMethods = false; 5942 bool hasNonDeletedOverridenMethods = false; 5943 bool AddedAny = false; 5944 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5945 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5946 E = Paths.found_decls_end(); I != E; ++I) { 5947 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5948 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5949 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5950 !CheckOverridingFunctionAttributes(MD, OldMD) && 5951 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5952 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5953 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5954 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5955 AddedAny = true; 5956 } 5957 } 5958 } 5959 } 5960 5961 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5962 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5963 } 5964 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5965 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5966 } 5967 5968 return AddedAny; 5969 } 5970 5971 namespace { 5972 // Struct for holding all of the extra arguments needed by 5973 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5974 struct ActOnFDArgs { 5975 Scope *S; 5976 Declarator &D; 5977 MultiTemplateParamsArg TemplateParamLists; 5978 bool AddToScope; 5979 }; 5980 } 5981 5982 namespace { 5983 5984 // Callback to only accept typo corrections that have a non-zero edit distance. 5985 // Also only accept corrections that have the same parent decl. 5986 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5987 public: 5988 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5989 CXXRecordDecl *Parent) 5990 : Context(Context), OriginalFD(TypoFD), 5991 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5992 5993 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5994 if (candidate.getEditDistance() == 0) 5995 return false; 5996 5997 SmallVector<unsigned, 1> MismatchedParams; 5998 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5999 CDeclEnd = candidate.end(); 6000 CDecl != CDeclEnd; ++CDecl) { 6001 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6002 6003 if (FD && !FD->hasBody() && 6004 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6005 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6006 CXXRecordDecl *Parent = MD->getParent(); 6007 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6008 return true; 6009 } else if (!ExpectedParent) { 6010 return true; 6011 } 6012 } 6013 } 6014 6015 return false; 6016 } 6017 6018 private: 6019 ASTContext &Context; 6020 FunctionDecl *OriginalFD; 6021 CXXRecordDecl *ExpectedParent; 6022 }; 6023 6024 } 6025 6026 /// \brief Generate diagnostics for an invalid function redeclaration. 6027 /// 6028 /// This routine handles generating the diagnostic messages for an invalid 6029 /// function redeclaration, including finding possible similar declarations 6030 /// or performing typo correction if there are no previous declarations with 6031 /// the same name. 6032 /// 6033 /// Returns a NamedDecl iff typo correction was performed and substituting in 6034 /// the new declaration name does not cause new errors. 6035 static NamedDecl *DiagnoseInvalidRedeclaration( 6036 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6037 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6038 DeclarationName Name = NewFD->getDeclName(); 6039 DeclContext *NewDC = NewFD->getDeclContext(); 6040 SmallVector<unsigned, 1> MismatchedParams; 6041 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6042 TypoCorrection Correction; 6043 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6044 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6045 : diag::err_member_decl_does_not_match; 6046 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6047 IsLocalFriend ? Sema::LookupLocalFriendName 6048 : Sema::LookupOrdinaryName, 6049 Sema::ForRedeclaration); 6050 6051 NewFD->setInvalidDecl(); 6052 if (IsLocalFriend) 6053 SemaRef.LookupName(Prev, S); 6054 else 6055 SemaRef.LookupQualifiedName(Prev, NewDC); 6056 assert(!Prev.isAmbiguous() && 6057 "Cannot have an ambiguity in previous-declaration lookup"); 6058 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6059 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6060 MD ? MD->getParent() : 0); 6061 if (!Prev.empty()) { 6062 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6063 Func != FuncEnd; ++Func) { 6064 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6065 if (FD && 6066 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6067 // Add 1 to the index so that 0 can mean the mismatch didn't 6068 // involve a parameter 6069 unsigned ParamNum = 6070 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6071 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6072 } 6073 } 6074 // If the qualified name lookup yielded nothing, try typo correction 6075 } else if ((Correction = SemaRef.CorrectTypo( 6076 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6077 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6078 IsLocalFriend ? 0 : NewDC))) { 6079 // Set up everything for the call to ActOnFunctionDeclarator 6080 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6081 ExtraArgs.D.getIdentifierLoc()); 6082 Previous.clear(); 6083 Previous.setLookupName(Correction.getCorrection()); 6084 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6085 CDeclEnd = Correction.end(); 6086 CDecl != CDeclEnd; ++CDecl) { 6087 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6088 if (FD && !FD->hasBody() && 6089 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6090 Previous.addDecl(FD); 6091 } 6092 } 6093 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6094 6095 NamedDecl *Result; 6096 // Retry building the function declaration with the new previous 6097 // declarations, and with errors suppressed. 6098 { 6099 // Trap errors. 6100 Sema::SFINAETrap Trap(SemaRef); 6101 6102 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6103 // pieces need to verify the typo-corrected C++ declaration and hopefully 6104 // eliminate the need for the parameter pack ExtraArgs. 6105 Result = SemaRef.ActOnFunctionDeclarator( 6106 ExtraArgs.S, ExtraArgs.D, 6107 Correction.getCorrectionDecl()->getDeclContext(), 6108 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6109 ExtraArgs.AddToScope); 6110 6111 if (Trap.hasErrorOccurred()) 6112 Result = 0; 6113 } 6114 6115 if (Result) { 6116 // Determine which correction we picked. 6117 Decl *Canonical = Result->getCanonicalDecl(); 6118 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6119 I != E; ++I) 6120 if ((*I)->getCanonicalDecl() == Canonical) 6121 Correction.setCorrectionDecl(*I); 6122 6123 SemaRef.diagnoseTypo( 6124 Correction, 6125 SemaRef.PDiag(IsLocalFriend 6126 ? diag::err_no_matching_local_friend_suggest 6127 : diag::err_member_decl_does_not_match_suggest) 6128 << Name << NewDC << IsDefinition); 6129 return Result; 6130 } 6131 6132 // Pretend the typo correction never occurred 6133 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6134 ExtraArgs.D.getIdentifierLoc()); 6135 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6136 Previous.clear(); 6137 Previous.setLookupName(Name); 6138 } 6139 6140 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6141 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6142 6143 bool NewFDisConst = false; 6144 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6145 NewFDisConst = NewMD->isConst(); 6146 6147 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6148 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6149 NearMatch != NearMatchEnd; ++NearMatch) { 6150 FunctionDecl *FD = NearMatch->first; 6151 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6152 bool FDisConst = MD && MD->isConst(); 6153 bool IsMember = MD || !IsLocalFriend; 6154 6155 // FIXME: These notes are poorly worded for the local friend case. 6156 if (unsigned Idx = NearMatch->second) { 6157 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6158 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6159 if (Loc.isInvalid()) Loc = FD->getLocation(); 6160 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6161 : diag::note_local_decl_close_param_match) 6162 << Idx << FDParam->getType() 6163 << NewFD->getParamDecl(Idx - 1)->getType(); 6164 } else if (FDisConst != NewFDisConst) { 6165 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6166 << NewFDisConst << FD->getSourceRange().getEnd(); 6167 } else 6168 SemaRef.Diag(FD->getLocation(), 6169 IsMember ? diag::note_member_def_close_match 6170 : diag::note_local_decl_close_match); 6171 } 6172 return 0; 6173 } 6174 6175 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6176 Declarator &D) { 6177 switch (D.getDeclSpec().getStorageClassSpec()) { 6178 default: llvm_unreachable("Unknown storage class!"); 6179 case DeclSpec::SCS_auto: 6180 case DeclSpec::SCS_register: 6181 case DeclSpec::SCS_mutable: 6182 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6183 diag::err_typecheck_sclass_func); 6184 D.setInvalidType(); 6185 break; 6186 case DeclSpec::SCS_unspecified: break; 6187 case DeclSpec::SCS_extern: 6188 if (D.getDeclSpec().isExternInLinkageSpec()) 6189 return SC_None; 6190 return SC_Extern; 6191 case DeclSpec::SCS_static: { 6192 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6193 // C99 6.7.1p5: 6194 // The declaration of an identifier for a function that has 6195 // block scope shall have no explicit storage-class specifier 6196 // other than extern 6197 // See also (C++ [dcl.stc]p4). 6198 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6199 diag::err_static_block_func); 6200 break; 6201 } else 6202 return SC_Static; 6203 } 6204 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6205 } 6206 6207 // No explicit storage class has already been returned 6208 return SC_None; 6209 } 6210 6211 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6212 DeclContext *DC, QualType &R, 6213 TypeSourceInfo *TInfo, 6214 FunctionDecl::StorageClass SC, 6215 bool &IsVirtualOkay) { 6216 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6217 DeclarationName Name = NameInfo.getName(); 6218 6219 FunctionDecl *NewFD = 0; 6220 bool isInline = D.getDeclSpec().isInlineSpecified(); 6221 6222 if (!SemaRef.getLangOpts().CPlusPlus) { 6223 // Determine whether the function was written with a 6224 // prototype. This true when: 6225 // - there is a prototype in the declarator, or 6226 // - the type R of the function is some kind of typedef or other reference 6227 // to a type name (which eventually refers to a function type). 6228 bool HasPrototype = 6229 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6230 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6231 6232 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6233 D.getLocStart(), NameInfo, R, 6234 TInfo, SC, isInline, 6235 HasPrototype, false); 6236 if (D.isInvalidType()) 6237 NewFD->setInvalidDecl(); 6238 6239 // Set the lexical context. 6240 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6241 6242 return NewFD; 6243 } 6244 6245 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6246 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6247 6248 // Check that the return type is not an abstract class type. 6249 // For record types, this is done by the AbstractClassUsageDiagnoser once 6250 // the class has been completely parsed. 6251 if (!DC->isRecord() && 6252 SemaRef.RequireNonAbstractType( 6253 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6254 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6255 D.setInvalidType(); 6256 6257 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6258 // This is a C++ constructor declaration. 6259 assert(DC->isRecord() && 6260 "Constructors can only be declared in a member context"); 6261 6262 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6263 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6264 D.getLocStart(), NameInfo, 6265 R, TInfo, isExplicit, isInline, 6266 /*isImplicitlyDeclared=*/false, 6267 isConstexpr); 6268 6269 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6270 // This is a C++ destructor declaration. 6271 if (DC->isRecord()) { 6272 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6273 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6274 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6275 SemaRef.Context, Record, 6276 D.getLocStart(), 6277 NameInfo, R, TInfo, isInline, 6278 /*isImplicitlyDeclared=*/false); 6279 6280 // If the class is complete, then we now create the implicit exception 6281 // specification. If the class is incomplete or dependent, we can't do 6282 // it yet. 6283 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6284 Record->getDefinition() && !Record->isBeingDefined() && 6285 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6286 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6287 } 6288 6289 IsVirtualOkay = true; 6290 return NewDD; 6291 6292 } else { 6293 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6294 D.setInvalidType(); 6295 6296 // Create a FunctionDecl to satisfy the function definition parsing 6297 // code path. 6298 return FunctionDecl::Create(SemaRef.Context, DC, 6299 D.getLocStart(), 6300 D.getIdentifierLoc(), Name, R, TInfo, 6301 SC, isInline, 6302 /*hasPrototype=*/true, isConstexpr); 6303 } 6304 6305 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6306 if (!DC->isRecord()) { 6307 SemaRef.Diag(D.getIdentifierLoc(), 6308 diag::err_conv_function_not_member); 6309 return 0; 6310 } 6311 6312 SemaRef.CheckConversionDeclarator(D, R, SC); 6313 IsVirtualOkay = true; 6314 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6315 D.getLocStart(), NameInfo, 6316 R, TInfo, isInline, isExplicit, 6317 isConstexpr, SourceLocation()); 6318 6319 } else if (DC->isRecord()) { 6320 // If the name of the function is the same as the name of the record, 6321 // then this must be an invalid constructor that has a return type. 6322 // (The parser checks for a return type and makes the declarator a 6323 // constructor if it has no return type). 6324 if (Name.getAsIdentifierInfo() && 6325 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6326 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6327 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6328 << SourceRange(D.getIdentifierLoc()); 6329 return 0; 6330 } 6331 6332 // This is a C++ method declaration. 6333 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6334 cast<CXXRecordDecl>(DC), 6335 D.getLocStart(), NameInfo, R, 6336 TInfo, SC, isInline, 6337 isConstexpr, SourceLocation()); 6338 IsVirtualOkay = !Ret->isStatic(); 6339 return Ret; 6340 } else { 6341 // Determine whether the function was written with a 6342 // prototype. This true when: 6343 // - we're in C++ (where every function has a prototype), 6344 return FunctionDecl::Create(SemaRef.Context, DC, 6345 D.getLocStart(), 6346 NameInfo, R, TInfo, SC, isInline, 6347 true/*HasPrototype*/, isConstexpr); 6348 } 6349 } 6350 6351 enum OpenCLParamType { 6352 ValidKernelParam, 6353 PtrPtrKernelParam, 6354 PtrKernelParam, 6355 InvalidKernelParam, 6356 RecordKernelParam 6357 }; 6358 6359 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6360 if (PT->isPointerType()) { 6361 QualType PointeeType = PT->getPointeeType(); 6362 return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam; 6363 } 6364 6365 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6366 // be used as builtin types. 6367 6368 if (PT->isImageType()) 6369 return PtrKernelParam; 6370 6371 if (PT->isBooleanType()) 6372 return InvalidKernelParam; 6373 6374 if (PT->isEventT()) 6375 return InvalidKernelParam; 6376 6377 if (PT->isHalfType()) 6378 return InvalidKernelParam; 6379 6380 if (PT->isRecordType()) 6381 return RecordKernelParam; 6382 6383 return ValidKernelParam; 6384 } 6385 6386 static void checkIsValidOpenCLKernelParameter( 6387 Sema &S, 6388 Declarator &D, 6389 ParmVarDecl *Param, 6390 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6391 QualType PT = Param->getType(); 6392 6393 // Cache the valid types we encounter to avoid rechecking structs that are 6394 // used again 6395 if (ValidTypes.count(PT.getTypePtr())) 6396 return; 6397 6398 switch (getOpenCLKernelParameterType(PT)) { 6399 case PtrPtrKernelParam: 6400 // OpenCL v1.2 s6.9.a: 6401 // A kernel function argument cannot be declared as a 6402 // pointer to a pointer type. 6403 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6404 D.setInvalidType(); 6405 return; 6406 6407 // OpenCL v1.2 s6.9.k: 6408 // Arguments to kernel functions in a program cannot be declared with the 6409 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6410 // uintptr_t or a struct and/or union that contain fields declared to be 6411 // one of these built-in scalar types. 6412 6413 case InvalidKernelParam: 6414 // OpenCL v1.2 s6.8 n: 6415 // A kernel function argument cannot be declared 6416 // of event_t type. 6417 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6418 D.setInvalidType(); 6419 return; 6420 6421 case PtrKernelParam: 6422 case ValidKernelParam: 6423 ValidTypes.insert(PT.getTypePtr()); 6424 return; 6425 6426 case RecordKernelParam: 6427 break; 6428 } 6429 6430 // Track nested structs we will inspect 6431 SmallVector<const Decl *, 4> VisitStack; 6432 6433 // Track where we are in the nested structs. Items will migrate from 6434 // VisitStack to HistoryStack as we do the DFS for bad field. 6435 SmallVector<const FieldDecl *, 4> HistoryStack; 6436 HistoryStack.push_back((const FieldDecl *) 0); 6437 6438 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6439 VisitStack.push_back(PD); 6440 6441 assert(VisitStack.back() && "First decl null?"); 6442 6443 do { 6444 const Decl *Next = VisitStack.pop_back_val(); 6445 if (!Next) { 6446 assert(!HistoryStack.empty()); 6447 // Found a marker, we have gone up a level 6448 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6449 ValidTypes.insert(Hist->getType().getTypePtr()); 6450 6451 continue; 6452 } 6453 6454 // Adds everything except the original parameter declaration (which is not a 6455 // field itself) to the history stack. 6456 const RecordDecl *RD; 6457 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6458 HistoryStack.push_back(Field); 6459 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6460 } else { 6461 RD = cast<RecordDecl>(Next); 6462 } 6463 6464 // Add a null marker so we know when we've gone back up a level 6465 VisitStack.push_back((const Decl *) 0); 6466 6467 for (const auto *FD : RD->fields()) { 6468 QualType QT = FD->getType(); 6469 6470 if (ValidTypes.count(QT.getTypePtr())) 6471 continue; 6472 6473 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6474 if (ParamType == ValidKernelParam) 6475 continue; 6476 6477 if (ParamType == RecordKernelParam) { 6478 VisitStack.push_back(FD); 6479 continue; 6480 } 6481 6482 // OpenCL v1.2 s6.9.p: 6483 // Arguments to kernel functions that are declared to be a struct or union 6484 // do not allow OpenCL objects to be passed as elements of the struct or 6485 // union. 6486 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) { 6487 S.Diag(Param->getLocation(), 6488 diag::err_record_with_pointers_kernel_param) 6489 << PT->isUnionType() 6490 << PT; 6491 } else { 6492 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6493 } 6494 6495 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6496 << PD->getDeclName(); 6497 6498 // We have an error, now let's go back up through history and show where 6499 // the offending field came from 6500 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6501 E = HistoryStack.end(); I != E; ++I) { 6502 const FieldDecl *OuterField = *I; 6503 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6504 << OuterField->getType(); 6505 } 6506 6507 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6508 << QT->isPointerType() 6509 << QT; 6510 D.setInvalidType(); 6511 return; 6512 } 6513 } while (!VisitStack.empty()); 6514 } 6515 6516 NamedDecl* 6517 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6518 TypeSourceInfo *TInfo, LookupResult &Previous, 6519 MultiTemplateParamsArg TemplateParamLists, 6520 bool &AddToScope) { 6521 QualType R = TInfo->getType(); 6522 6523 assert(R.getTypePtr()->isFunctionType()); 6524 6525 // TODO: consider using NameInfo for diagnostic. 6526 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6527 DeclarationName Name = NameInfo.getName(); 6528 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6529 6530 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6531 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6532 diag::err_invalid_thread) 6533 << DeclSpec::getSpecifierName(TSCS); 6534 6535 if (D.isFirstDeclarationOfMember()) 6536 adjustMemberFunctionCC(R, D.isStaticMember()); 6537 6538 bool isFriend = false; 6539 FunctionTemplateDecl *FunctionTemplate = 0; 6540 bool isExplicitSpecialization = false; 6541 bool isFunctionTemplateSpecialization = false; 6542 6543 bool isDependentClassScopeExplicitSpecialization = false; 6544 bool HasExplicitTemplateArgs = false; 6545 TemplateArgumentListInfo TemplateArgs; 6546 6547 bool isVirtualOkay = false; 6548 6549 DeclContext *OriginalDC = DC; 6550 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6551 6552 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6553 isVirtualOkay); 6554 if (!NewFD) return 0; 6555 6556 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6557 NewFD->setTopLevelDeclInObjCContainer(); 6558 6559 // Set the lexical context. If this is a function-scope declaration, or has a 6560 // C++ scope specifier, or is the object of a friend declaration, the lexical 6561 // context will be different from the semantic context. 6562 NewFD->setLexicalDeclContext(CurContext); 6563 6564 if (IsLocalExternDecl) 6565 NewFD->setLocalExternDecl(); 6566 6567 if (getLangOpts().CPlusPlus) { 6568 bool isInline = D.getDeclSpec().isInlineSpecified(); 6569 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6570 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6571 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6572 isFriend = D.getDeclSpec().isFriendSpecified(); 6573 if (isFriend && !isInline && D.isFunctionDefinition()) { 6574 // C++ [class.friend]p5 6575 // A function can be defined in a friend declaration of a 6576 // class . . . . Such a function is implicitly inline. 6577 NewFD->setImplicitlyInline(); 6578 } 6579 6580 // If this is a method defined in an __interface, and is not a constructor 6581 // or an overloaded operator, then set the pure flag (isVirtual will already 6582 // return true). 6583 if (const CXXRecordDecl *Parent = 6584 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6585 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6586 NewFD->setPure(true); 6587 } 6588 6589 SetNestedNameSpecifier(NewFD, D); 6590 isExplicitSpecialization = false; 6591 isFunctionTemplateSpecialization = false; 6592 if (D.isInvalidType()) 6593 NewFD->setInvalidDecl(); 6594 6595 // Match up the template parameter lists with the scope specifier, then 6596 // determine whether we have a template or a template specialization. 6597 bool Invalid = false; 6598 if (TemplateParameterList *TemplateParams = 6599 MatchTemplateParametersToScopeSpecifier( 6600 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6601 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6602 isExplicitSpecialization, Invalid)) { 6603 if (TemplateParams->size() > 0) { 6604 // This is a function template 6605 6606 // Check that we can declare a template here. 6607 if (CheckTemplateDeclScope(S, TemplateParams)) 6608 return 0; 6609 6610 // A destructor cannot be a template. 6611 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6612 Diag(NewFD->getLocation(), diag::err_destructor_template); 6613 return 0; 6614 } 6615 6616 // If we're adding a template to a dependent context, we may need to 6617 // rebuilding some of the types used within the template parameter list, 6618 // now that we know what the current instantiation is. 6619 if (DC->isDependentContext()) { 6620 ContextRAII SavedContext(*this, DC); 6621 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6622 Invalid = true; 6623 } 6624 6625 6626 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6627 NewFD->getLocation(), 6628 Name, TemplateParams, 6629 NewFD); 6630 FunctionTemplate->setLexicalDeclContext(CurContext); 6631 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6632 6633 // For source fidelity, store the other template param lists. 6634 if (TemplateParamLists.size() > 1) { 6635 NewFD->setTemplateParameterListsInfo(Context, 6636 TemplateParamLists.size() - 1, 6637 TemplateParamLists.data()); 6638 } 6639 } else { 6640 // This is a function template specialization. 6641 isFunctionTemplateSpecialization = true; 6642 // For source fidelity, store all the template param lists. 6643 NewFD->setTemplateParameterListsInfo(Context, 6644 TemplateParamLists.size(), 6645 TemplateParamLists.data()); 6646 6647 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6648 if (isFriend) { 6649 // We want to remove the "template<>", found here. 6650 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6651 6652 // If we remove the template<> and the name is not a 6653 // template-id, we're actually silently creating a problem: 6654 // the friend declaration will refer to an untemplated decl, 6655 // and clearly the user wants a template specialization. So 6656 // we need to insert '<>' after the name. 6657 SourceLocation InsertLoc; 6658 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6659 InsertLoc = D.getName().getSourceRange().getEnd(); 6660 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6661 } 6662 6663 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6664 << Name << RemoveRange 6665 << FixItHint::CreateRemoval(RemoveRange) 6666 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6667 } 6668 } 6669 } 6670 else { 6671 // All template param lists were matched against the scope specifier: 6672 // this is NOT (an explicit specialization of) a template. 6673 if (TemplateParamLists.size() > 0) 6674 // For source fidelity, store all the template param lists. 6675 NewFD->setTemplateParameterListsInfo(Context, 6676 TemplateParamLists.size(), 6677 TemplateParamLists.data()); 6678 } 6679 6680 if (Invalid) { 6681 NewFD->setInvalidDecl(); 6682 if (FunctionTemplate) 6683 FunctionTemplate->setInvalidDecl(); 6684 } 6685 6686 // C++ [dcl.fct.spec]p5: 6687 // The virtual specifier shall only be used in declarations of 6688 // nonstatic class member functions that appear within a 6689 // member-specification of a class declaration; see 10.3. 6690 // 6691 if (isVirtual && !NewFD->isInvalidDecl()) { 6692 if (!isVirtualOkay) { 6693 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6694 diag::err_virtual_non_function); 6695 } else if (!CurContext->isRecord()) { 6696 // 'virtual' was specified outside of the class. 6697 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6698 diag::err_virtual_out_of_class) 6699 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6700 } else if (NewFD->getDescribedFunctionTemplate()) { 6701 // C++ [temp.mem]p3: 6702 // A member function template shall not be virtual. 6703 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6704 diag::err_virtual_member_function_template) 6705 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6706 } else { 6707 // Okay: Add virtual to the method. 6708 NewFD->setVirtualAsWritten(true); 6709 } 6710 6711 if (getLangOpts().CPlusPlus1y && 6712 NewFD->getReturnType()->isUndeducedType()) 6713 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6714 } 6715 6716 if (getLangOpts().CPlusPlus1y && 6717 (NewFD->isDependentContext() || 6718 (isFriend && CurContext->isDependentContext())) && 6719 NewFD->getReturnType()->isUndeducedType()) { 6720 // If the function template is referenced directly (for instance, as a 6721 // member of the current instantiation), pretend it has a dependent type. 6722 // This is not really justified by the standard, but is the only sane 6723 // thing to do. 6724 // FIXME: For a friend function, we have not marked the function as being 6725 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6726 const FunctionProtoType *FPT = 6727 NewFD->getType()->castAs<FunctionProtoType>(); 6728 QualType Result = 6729 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6730 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6731 FPT->getExtProtoInfo())); 6732 } 6733 6734 // C++ [dcl.fct.spec]p3: 6735 // The inline specifier shall not appear on a block scope function 6736 // declaration. 6737 if (isInline && !NewFD->isInvalidDecl()) { 6738 if (CurContext->isFunctionOrMethod()) { 6739 // 'inline' is not allowed on block scope function declaration. 6740 Diag(D.getDeclSpec().getInlineSpecLoc(), 6741 diag::err_inline_declaration_block_scope) << Name 6742 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6743 } 6744 } 6745 6746 // C++ [dcl.fct.spec]p6: 6747 // The explicit specifier shall be used only in the declaration of a 6748 // constructor or conversion function within its class definition; 6749 // see 12.3.1 and 12.3.2. 6750 if (isExplicit && !NewFD->isInvalidDecl()) { 6751 if (!CurContext->isRecord()) { 6752 // 'explicit' was specified outside of the class. 6753 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6754 diag::err_explicit_out_of_class) 6755 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6756 } else if (!isa<CXXConstructorDecl>(NewFD) && 6757 !isa<CXXConversionDecl>(NewFD)) { 6758 // 'explicit' was specified on a function that wasn't a constructor 6759 // or conversion function. 6760 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6761 diag::err_explicit_non_ctor_or_conv_function) 6762 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6763 } 6764 } 6765 6766 if (isConstexpr) { 6767 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6768 // are implicitly inline. 6769 NewFD->setImplicitlyInline(); 6770 6771 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6772 // be either constructors or to return a literal type. Therefore, 6773 // destructors cannot be declared constexpr. 6774 if (isa<CXXDestructorDecl>(NewFD)) 6775 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6776 } 6777 6778 // If __module_private__ was specified, mark the function accordingly. 6779 if (D.getDeclSpec().isModulePrivateSpecified()) { 6780 if (isFunctionTemplateSpecialization) { 6781 SourceLocation ModulePrivateLoc 6782 = D.getDeclSpec().getModulePrivateSpecLoc(); 6783 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6784 << 0 6785 << FixItHint::CreateRemoval(ModulePrivateLoc); 6786 } else { 6787 NewFD->setModulePrivate(); 6788 if (FunctionTemplate) 6789 FunctionTemplate->setModulePrivate(); 6790 } 6791 } 6792 6793 if (isFriend) { 6794 if (FunctionTemplate) { 6795 FunctionTemplate->setObjectOfFriendDecl(); 6796 FunctionTemplate->setAccess(AS_public); 6797 } 6798 NewFD->setObjectOfFriendDecl(); 6799 NewFD->setAccess(AS_public); 6800 } 6801 6802 // If a function is defined as defaulted or deleted, mark it as such now. 6803 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6804 // definition kind to FDK_Definition. 6805 switch (D.getFunctionDefinitionKind()) { 6806 case FDK_Declaration: 6807 case FDK_Definition: 6808 break; 6809 6810 case FDK_Defaulted: 6811 NewFD->setDefaulted(); 6812 break; 6813 6814 case FDK_Deleted: 6815 NewFD->setDeletedAsWritten(); 6816 break; 6817 } 6818 6819 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6820 D.isFunctionDefinition()) { 6821 // C++ [class.mfct]p2: 6822 // A member function may be defined (8.4) in its class definition, in 6823 // which case it is an inline member function (7.1.2) 6824 NewFD->setImplicitlyInline(); 6825 } 6826 6827 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6828 !CurContext->isRecord()) { 6829 // C++ [class.static]p1: 6830 // A data or function member of a class may be declared static 6831 // in a class definition, in which case it is a static member of 6832 // the class. 6833 6834 // Complain about the 'static' specifier if it's on an out-of-line 6835 // member function definition. 6836 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6837 diag::err_static_out_of_line) 6838 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6839 } 6840 6841 // C++11 [except.spec]p15: 6842 // A deallocation function with no exception-specification is treated 6843 // as if it were specified with noexcept(true). 6844 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6845 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6846 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6847 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6848 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6849 EPI.ExceptionSpecType = EST_BasicNoexcept; 6850 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 6851 FPT->getParamTypes(), EPI)); 6852 } 6853 } 6854 6855 // Filter out previous declarations that don't match the scope. 6856 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6857 D.getCXXScopeSpec().isNotEmpty() || 6858 isExplicitSpecialization || 6859 isFunctionTemplateSpecialization); 6860 6861 // Handle GNU asm-label extension (encoded as an attribute). 6862 if (Expr *E = (Expr*) D.getAsmLabel()) { 6863 // The parser guarantees this is a string. 6864 StringLiteral *SE = cast<StringLiteral>(E); 6865 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6866 SE->getString(), 0)); 6867 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6868 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6869 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6870 if (I != ExtnameUndeclaredIdentifiers.end()) { 6871 NewFD->addAttr(I->second); 6872 ExtnameUndeclaredIdentifiers.erase(I); 6873 } 6874 } 6875 6876 // Copy the parameter declarations from the declarator D to the function 6877 // declaration NewFD, if they are available. First scavenge them into Params. 6878 SmallVector<ParmVarDecl*, 16> Params; 6879 if (D.isFunctionDeclarator()) { 6880 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6881 6882 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6883 // function that takes no arguments, not a function that takes a 6884 // single void argument. 6885 // We let through "const void" here because Sema::GetTypeForDeclarator 6886 // already checks for that case. 6887 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 && 6888 FTI.Params[0].Param && 6889 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) { 6890 // Empty arg list, don't push any params. 6891 } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) { 6892 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 6893 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 6894 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6895 Param->setDeclContext(NewFD); 6896 Params.push_back(Param); 6897 6898 if (Param->isInvalidDecl()) 6899 NewFD->setInvalidDecl(); 6900 } 6901 } 6902 6903 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6904 // When we're declaring a function with a typedef, typeof, etc as in the 6905 // following example, we'll need to synthesize (unnamed) 6906 // parameters for use in the declaration. 6907 // 6908 // @code 6909 // typedef void fn(int); 6910 // fn f; 6911 // @endcode 6912 6913 // Synthesize a parameter for each argument type. 6914 for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(), 6915 AE = FT->param_type_end(); 6916 AI != AE; ++AI) { 6917 ParmVarDecl *Param = 6918 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6919 Param->setScopeInfo(0, Params.size()); 6920 Params.push_back(Param); 6921 } 6922 } else { 6923 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6924 "Should not need args for typedef of non-prototype fn"); 6925 } 6926 6927 // Finally, we know we have the right number of parameters, install them. 6928 NewFD->setParams(Params); 6929 6930 // Find all anonymous symbols defined during the declaration of this function 6931 // and add to NewFD. This lets us track decls such 'enum Y' in: 6932 // 6933 // void f(enum Y {AA} x) {} 6934 // 6935 // which would otherwise incorrectly end up in the translation unit scope. 6936 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6937 DeclsInPrototypeScope.clear(); 6938 6939 if (D.getDeclSpec().isNoreturnSpecified()) 6940 NewFD->addAttr( 6941 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6942 Context, 0)); 6943 6944 // Functions returning a variably modified type violate C99 6.7.5.2p2 6945 // because all functions have linkage. 6946 if (!NewFD->isInvalidDecl() && 6947 NewFD->getReturnType()->isVariablyModifiedType()) { 6948 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6949 NewFD->setInvalidDecl(); 6950 } 6951 6952 // Handle attributes. 6953 ProcessDeclAttributes(S, NewFD, D); 6954 6955 QualType RetType = NewFD->getReturnType(); 6956 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6957 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6958 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6959 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6960 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6961 // Attach WarnUnusedResult to functions returning types with that attribute. 6962 // Don't apply the attribute to that type's own non-static member functions 6963 // (to avoid warning on things like assignment operators) 6964 if (!MD || MD->getParent() != Ret) 6965 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 6966 } 6967 6968 if (getLangOpts().OpenCL) { 6969 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 6970 // type declaration will generate a compilation error. 6971 unsigned AddressSpace = RetType.getAddressSpace(); 6972 if (AddressSpace == LangAS::opencl_local || 6973 AddressSpace == LangAS::opencl_global || 6974 AddressSpace == LangAS::opencl_constant) { 6975 Diag(NewFD->getLocation(), 6976 diag::err_opencl_return_value_with_address_space); 6977 NewFD->setInvalidDecl(); 6978 } 6979 } 6980 6981 if (!getLangOpts().CPlusPlus) { 6982 // Perform semantic checking on the function declaration. 6983 bool isExplicitSpecialization=false; 6984 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 6985 CheckMain(NewFD, D.getDeclSpec()); 6986 6987 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 6988 CheckMSVCRTEntryPoint(NewFD); 6989 6990 if (!NewFD->isInvalidDecl()) 6991 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 6992 isExplicitSpecialization)); 6993 else if (!Previous.empty()) 6994 // Make graceful recovery from an invalid redeclaration. 6995 D.setRedeclaration(true); 6996 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 6997 Previous.getResultKind() != LookupResult::FoundOverloaded) && 6998 "previous declaration set still overloaded"); 6999 } else { 7000 // C++11 [replacement.functions]p3: 7001 // The program's definitions shall not be specified as inline. 7002 // 7003 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7004 // 7005 // Suppress the diagnostic if the function is __attribute__((used)), since 7006 // that forces an external definition to be emitted. 7007 if (D.getDeclSpec().isInlineSpecified() && 7008 NewFD->isReplaceableGlobalAllocationFunction() && 7009 !NewFD->hasAttr<UsedAttr>()) 7010 Diag(D.getDeclSpec().getInlineSpecLoc(), 7011 diag::ext_operator_new_delete_declared_inline) 7012 << NewFD->getDeclName(); 7013 7014 // If the declarator is a template-id, translate the parser's template 7015 // argument list into our AST format. 7016 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7017 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7018 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7019 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7020 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7021 TemplateId->NumArgs); 7022 translateTemplateArguments(TemplateArgsPtr, 7023 TemplateArgs); 7024 7025 HasExplicitTemplateArgs = true; 7026 7027 if (NewFD->isInvalidDecl()) { 7028 HasExplicitTemplateArgs = false; 7029 } else if (FunctionTemplate) { 7030 // Function template with explicit template arguments. 7031 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7032 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7033 7034 HasExplicitTemplateArgs = false; 7035 } else if (!isFunctionTemplateSpecialization && 7036 !D.getDeclSpec().isFriendSpecified()) { 7037 // We have encountered something that the user meant to be a 7038 // specialization (because it has explicitly-specified template 7039 // arguments) but that was not introduced with a "template<>" (or had 7040 // too few of them). 7041 // FIXME: Differentiate between attempts for explicit instantiations 7042 // (starting with "template") and the rest. 7043 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7044 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7045 << FixItHint::CreateInsertion( 7046 D.getDeclSpec().getLocStart(), 7047 "template<> "); 7048 isFunctionTemplateSpecialization = true; 7049 } else { 7050 // "friend void foo<>(int);" is an implicit specialization decl. 7051 isFunctionTemplateSpecialization = true; 7052 } 7053 } else if (isFriend && isFunctionTemplateSpecialization) { 7054 // This combination is only possible in a recovery case; the user 7055 // wrote something like: 7056 // template <> friend void foo(int); 7057 // which we're recovering from as if the user had written: 7058 // friend void foo<>(int); 7059 // Go ahead and fake up a template id. 7060 HasExplicitTemplateArgs = true; 7061 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7062 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7063 } 7064 7065 // If it's a friend (and only if it's a friend), it's possible 7066 // that either the specialized function type or the specialized 7067 // template is dependent, and therefore matching will fail. In 7068 // this case, don't check the specialization yet. 7069 bool InstantiationDependent = false; 7070 if (isFunctionTemplateSpecialization && isFriend && 7071 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7072 TemplateSpecializationType::anyDependentTemplateArguments( 7073 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7074 InstantiationDependent))) { 7075 assert(HasExplicitTemplateArgs && 7076 "friend function specialization without template args"); 7077 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7078 Previous)) 7079 NewFD->setInvalidDecl(); 7080 } else if (isFunctionTemplateSpecialization) { 7081 if (CurContext->isDependentContext() && CurContext->isRecord() 7082 && !isFriend) { 7083 isDependentClassScopeExplicitSpecialization = true; 7084 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7085 diag::ext_function_specialization_in_class : 7086 diag::err_function_specialization_in_class) 7087 << NewFD->getDeclName(); 7088 } else if (CheckFunctionTemplateSpecialization(NewFD, 7089 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7090 Previous)) 7091 NewFD->setInvalidDecl(); 7092 7093 // C++ [dcl.stc]p1: 7094 // A storage-class-specifier shall not be specified in an explicit 7095 // specialization (14.7.3) 7096 FunctionTemplateSpecializationInfo *Info = 7097 NewFD->getTemplateSpecializationInfo(); 7098 if (Info && SC != SC_None) { 7099 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7100 Diag(NewFD->getLocation(), 7101 diag::err_explicit_specialization_inconsistent_storage_class) 7102 << SC 7103 << FixItHint::CreateRemoval( 7104 D.getDeclSpec().getStorageClassSpecLoc()); 7105 7106 else 7107 Diag(NewFD->getLocation(), 7108 diag::ext_explicit_specialization_storage_class) 7109 << FixItHint::CreateRemoval( 7110 D.getDeclSpec().getStorageClassSpecLoc()); 7111 } 7112 7113 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7114 if (CheckMemberSpecialization(NewFD, Previous)) 7115 NewFD->setInvalidDecl(); 7116 } 7117 7118 // Perform semantic checking on the function declaration. 7119 if (!isDependentClassScopeExplicitSpecialization) { 7120 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7121 CheckMain(NewFD, D.getDeclSpec()); 7122 7123 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7124 CheckMSVCRTEntryPoint(NewFD); 7125 7126 if (!NewFD->isInvalidDecl()) 7127 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7128 isExplicitSpecialization)); 7129 } 7130 7131 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7132 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7133 "previous declaration set still overloaded"); 7134 7135 NamedDecl *PrincipalDecl = (FunctionTemplate 7136 ? cast<NamedDecl>(FunctionTemplate) 7137 : NewFD); 7138 7139 if (isFriend && D.isRedeclaration()) { 7140 AccessSpecifier Access = AS_public; 7141 if (!NewFD->isInvalidDecl()) 7142 Access = NewFD->getPreviousDecl()->getAccess(); 7143 7144 NewFD->setAccess(Access); 7145 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7146 } 7147 7148 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7149 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7150 PrincipalDecl->setNonMemberOperator(); 7151 7152 // If we have a function template, check the template parameter 7153 // list. This will check and merge default template arguments. 7154 if (FunctionTemplate) { 7155 FunctionTemplateDecl *PrevTemplate = 7156 FunctionTemplate->getPreviousDecl(); 7157 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7158 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7159 D.getDeclSpec().isFriendSpecified() 7160 ? (D.isFunctionDefinition() 7161 ? TPC_FriendFunctionTemplateDefinition 7162 : TPC_FriendFunctionTemplate) 7163 : (D.getCXXScopeSpec().isSet() && 7164 DC && DC->isRecord() && 7165 DC->isDependentContext()) 7166 ? TPC_ClassTemplateMember 7167 : TPC_FunctionTemplate); 7168 } 7169 7170 if (NewFD->isInvalidDecl()) { 7171 // Ignore all the rest of this. 7172 } else if (!D.isRedeclaration()) { 7173 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7174 AddToScope }; 7175 // Fake up an access specifier if it's supposed to be a class member. 7176 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7177 NewFD->setAccess(AS_public); 7178 7179 // Qualified decls generally require a previous declaration. 7180 if (D.getCXXScopeSpec().isSet()) { 7181 // ...with the major exception of templated-scope or 7182 // dependent-scope friend declarations. 7183 7184 // TODO: we currently also suppress this check in dependent 7185 // contexts because (1) the parameter depth will be off when 7186 // matching friend templates and (2) we might actually be 7187 // selecting a friend based on a dependent factor. But there 7188 // are situations where these conditions don't apply and we 7189 // can actually do this check immediately. 7190 if (isFriend && 7191 (TemplateParamLists.size() || 7192 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7193 CurContext->isDependentContext())) { 7194 // ignore these 7195 } else { 7196 // The user tried to provide an out-of-line definition for a 7197 // function that is a member of a class or namespace, but there 7198 // was no such member function declared (C++ [class.mfct]p2, 7199 // C++ [namespace.memdef]p2). For example: 7200 // 7201 // class X { 7202 // void f() const; 7203 // }; 7204 // 7205 // void X::f() { } // ill-formed 7206 // 7207 // Complain about this problem, and attempt to suggest close 7208 // matches (e.g., those that differ only in cv-qualifiers and 7209 // whether the parameter types are references). 7210 7211 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7212 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7213 AddToScope = ExtraArgs.AddToScope; 7214 return Result; 7215 } 7216 } 7217 7218 // Unqualified local friend declarations are required to resolve 7219 // to something. 7220 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7221 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7222 *this, Previous, NewFD, ExtraArgs, true, S)) { 7223 AddToScope = ExtraArgs.AddToScope; 7224 return Result; 7225 } 7226 } 7227 7228 } else if (!D.isFunctionDefinition() && 7229 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7230 !isFriend && !isFunctionTemplateSpecialization && 7231 !isExplicitSpecialization) { 7232 // An out-of-line member function declaration must also be a 7233 // definition (C++ [class.mfct]p2). 7234 // Note that this is not the case for explicit specializations of 7235 // function templates or member functions of class templates, per 7236 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7237 // extension for compatibility with old SWIG code which likes to 7238 // generate them. 7239 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7240 << D.getCXXScopeSpec().getRange(); 7241 } 7242 } 7243 7244 ProcessPragmaWeak(S, NewFD); 7245 checkAttributesAfterMerging(*this, *NewFD); 7246 7247 AddKnownFunctionAttributes(NewFD); 7248 7249 if (NewFD->hasAttr<OverloadableAttr>() && 7250 !NewFD->getType()->getAs<FunctionProtoType>()) { 7251 Diag(NewFD->getLocation(), 7252 diag::err_attribute_overloadable_no_prototype) 7253 << NewFD; 7254 7255 // Turn this into a variadic function with no parameters. 7256 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7257 FunctionProtoType::ExtProtoInfo EPI( 7258 Context.getDefaultCallingConvention(true, false)); 7259 EPI.Variadic = true; 7260 EPI.ExtInfo = FT->getExtInfo(); 7261 7262 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7263 NewFD->setType(R); 7264 } 7265 7266 // If there's a #pragma GCC visibility in scope, and this isn't a class 7267 // member, set the visibility of this function. 7268 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7269 AddPushedVisibilityAttribute(NewFD); 7270 7271 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7272 // marking the function. 7273 AddCFAuditedAttribute(NewFD); 7274 7275 // If this is the first declaration of an extern C variable, update 7276 // the map of such variables. 7277 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7278 isIncompleteDeclExternC(*this, NewFD)) 7279 RegisterLocallyScopedExternCDecl(NewFD, S); 7280 7281 // Set this FunctionDecl's range up to the right paren. 7282 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7283 7284 if (getLangOpts().CPlusPlus) { 7285 if (FunctionTemplate) { 7286 if (NewFD->isInvalidDecl()) 7287 FunctionTemplate->setInvalidDecl(); 7288 return FunctionTemplate; 7289 } 7290 } 7291 7292 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7293 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7294 if ((getLangOpts().OpenCLVersion >= 120) 7295 && (SC == SC_Static)) { 7296 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7297 D.setInvalidType(); 7298 } 7299 7300 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7301 if (!NewFD->getReturnType()->isVoidType()) { 7302 Diag(D.getIdentifierLoc(), 7303 diag::err_expected_kernel_void_return_type); 7304 D.setInvalidType(); 7305 } 7306 7307 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7308 for (auto Param : NewFD->params()) 7309 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7310 } 7311 7312 MarkUnusedFileScopedDecl(NewFD); 7313 7314 if (getLangOpts().CUDA) 7315 if (IdentifierInfo *II = NewFD->getIdentifier()) 7316 if (!NewFD->isInvalidDecl() && 7317 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7318 if (II->isStr("cudaConfigureCall")) { 7319 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7320 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7321 7322 Context.setcudaConfigureCallDecl(NewFD); 7323 } 7324 } 7325 7326 // Here we have an function template explicit specialization at class scope. 7327 // The actually specialization will be postponed to template instatiation 7328 // time via the ClassScopeFunctionSpecializationDecl node. 7329 if (isDependentClassScopeExplicitSpecialization) { 7330 ClassScopeFunctionSpecializationDecl *NewSpec = 7331 ClassScopeFunctionSpecializationDecl::Create( 7332 Context, CurContext, SourceLocation(), 7333 cast<CXXMethodDecl>(NewFD), 7334 HasExplicitTemplateArgs, TemplateArgs); 7335 CurContext->addDecl(NewSpec); 7336 AddToScope = false; 7337 } 7338 7339 return NewFD; 7340 } 7341 7342 /// \brief Perform semantic checking of a new function declaration. 7343 /// 7344 /// Performs semantic analysis of the new function declaration 7345 /// NewFD. This routine performs all semantic checking that does not 7346 /// require the actual declarator involved in the declaration, and is 7347 /// used both for the declaration of functions as they are parsed 7348 /// (called via ActOnDeclarator) and for the declaration of functions 7349 /// that have been instantiated via C++ template instantiation (called 7350 /// via InstantiateDecl). 7351 /// 7352 /// \param IsExplicitSpecialization whether this new function declaration is 7353 /// an explicit specialization of the previous declaration. 7354 /// 7355 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7356 /// 7357 /// \returns true if the function declaration is a redeclaration. 7358 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7359 LookupResult &Previous, 7360 bool IsExplicitSpecialization) { 7361 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7362 "Variably modified return types are not handled here"); 7363 7364 // Determine whether the type of this function should be merged with 7365 // a previous visible declaration. This never happens for functions in C++, 7366 // and always happens in C if the previous declaration was visible. 7367 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7368 !Previous.isShadowed(); 7369 7370 // Filter out any non-conflicting previous declarations. 7371 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7372 7373 bool Redeclaration = false; 7374 NamedDecl *OldDecl = 0; 7375 7376 // Merge or overload the declaration with an existing declaration of 7377 // the same name, if appropriate. 7378 if (!Previous.empty()) { 7379 // Determine whether NewFD is an overload of PrevDecl or 7380 // a declaration that requires merging. If it's an overload, 7381 // there's no more work to do here; we'll just add the new 7382 // function to the scope. 7383 if (!AllowOverloadingOfFunction(Previous, Context)) { 7384 NamedDecl *Candidate = Previous.getFoundDecl(); 7385 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7386 Redeclaration = true; 7387 OldDecl = Candidate; 7388 } 7389 } else { 7390 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7391 /*NewIsUsingDecl*/ false)) { 7392 case Ovl_Match: 7393 Redeclaration = true; 7394 break; 7395 7396 case Ovl_NonFunction: 7397 Redeclaration = true; 7398 break; 7399 7400 case Ovl_Overload: 7401 Redeclaration = false; 7402 break; 7403 } 7404 7405 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7406 // If a function name is overloadable in C, then every function 7407 // with that name must be marked "overloadable". 7408 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7409 << Redeclaration << NewFD; 7410 NamedDecl *OverloadedDecl = 0; 7411 if (Redeclaration) 7412 OverloadedDecl = OldDecl; 7413 else if (!Previous.empty()) 7414 OverloadedDecl = Previous.getRepresentativeDecl(); 7415 if (OverloadedDecl) 7416 Diag(OverloadedDecl->getLocation(), 7417 diag::note_attribute_overloadable_prev_overload); 7418 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7419 } 7420 } 7421 } 7422 7423 // Check for a previous extern "C" declaration with this name. 7424 if (!Redeclaration && 7425 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7426 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7427 if (!Previous.empty()) { 7428 // This is an extern "C" declaration with the same name as a previous 7429 // declaration, and thus redeclares that entity... 7430 Redeclaration = true; 7431 OldDecl = Previous.getFoundDecl(); 7432 MergeTypeWithPrevious = false; 7433 7434 // ... except in the presence of __attribute__((overloadable)). 7435 if (OldDecl->hasAttr<OverloadableAttr>()) { 7436 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7437 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7438 << Redeclaration << NewFD; 7439 Diag(Previous.getFoundDecl()->getLocation(), 7440 diag::note_attribute_overloadable_prev_overload); 7441 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7442 } 7443 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7444 Redeclaration = false; 7445 OldDecl = 0; 7446 } 7447 } 7448 } 7449 } 7450 7451 // C++11 [dcl.constexpr]p8: 7452 // A constexpr specifier for a non-static member function that is not 7453 // a constructor declares that member function to be const. 7454 // 7455 // This needs to be delayed until we know whether this is an out-of-line 7456 // definition of a static member function. 7457 // 7458 // This rule is not present in C++1y, so we produce a backwards 7459 // compatibility warning whenever it happens in C++11. 7460 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7461 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7462 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7463 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7464 CXXMethodDecl *OldMD = 0; 7465 if (OldDecl) 7466 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7467 if (!OldMD || !OldMD->isStatic()) { 7468 const FunctionProtoType *FPT = 7469 MD->getType()->castAs<FunctionProtoType>(); 7470 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7471 EPI.TypeQuals |= Qualifiers::Const; 7472 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7473 FPT->getParamTypes(), EPI)); 7474 7475 // Warn that we did this, if we're not performing template instantiation. 7476 // In that case, we'll have warned already when the template was defined. 7477 if (ActiveTemplateInstantiations.empty()) { 7478 SourceLocation AddConstLoc; 7479 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7480 .IgnoreParens().getAs<FunctionTypeLoc>()) 7481 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7482 7483 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7484 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7485 } 7486 } 7487 } 7488 7489 if (Redeclaration) { 7490 // NewFD and OldDecl represent declarations that need to be 7491 // merged. 7492 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7493 NewFD->setInvalidDecl(); 7494 return Redeclaration; 7495 } 7496 7497 Previous.clear(); 7498 Previous.addDecl(OldDecl); 7499 7500 if (FunctionTemplateDecl *OldTemplateDecl 7501 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7502 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7503 FunctionTemplateDecl *NewTemplateDecl 7504 = NewFD->getDescribedFunctionTemplate(); 7505 assert(NewTemplateDecl && "Template/non-template mismatch"); 7506 if (CXXMethodDecl *Method 7507 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7508 Method->setAccess(OldTemplateDecl->getAccess()); 7509 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7510 } 7511 7512 // If this is an explicit specialization of a member that is a function 7513 // template, mark it as a member specialization. 7514 if (IsExplicitSpecialization && 7515 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7516 NewTemplateDecl->setMemberSpecialization(); 7517 assert(OldTemplateDecl->isMemberSpecialization()); 7518 } 7519 7520 } else { 7521 // This needs to happen first so that 'inline' propagates. 7522 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7523 7524 if (isa<CXXMethodDecl>(NewFD)) { 7525 // A valid redeclaration of a C++ method must be out-of-line, 7526 // but (unfortunately) it's not necessarily a definition 7527 // because of templates, which means that the previous 7528 // declaration is not necessarily from the class definition. 7529 7530 // For just setting the access, that doesn't matter. 7531 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7532 NewFD->setAccess(oldMethod->getAccess()); 7533 7534 // Update the key-function state if necessary for this ABI. 7535 if (NewFD->isInlined() && 7536 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7537 // setNonKeyFunction needs to work with the original 7538 // declaration from the class definition, and isVirtual() is 7539 // just faster in that case, so map back to that now. 7540 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7541 if (oldMethod->isVirtual()) { 7542 Context.setNonKeyFunction(oldMethod); 7543 } 7544 } 7545 } 7546 } 7547 } 7548 7549 // Semantic checking for this function declaration (in isolation). 7550 if (getLangOpts().CPlusPlus) { 7551 // C++-specific checks. 7552 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7553 CheckConstructor(Constructor); 7554 } else if (CXXDestructorDecl *Destructor = 7555 dyn_cast<CXXDestructorDecl>(NewFD)) { 7556 CXXRecordDecl *Record = Destructor->getParent(); 7557 QualType ClassType = Context.getTypeDeclType(Record); 7558 7559 // FIXME: Shouldn't we be able to perform this check even when the class 7560 // type is dependent? Both gcc and edg can handle that. 7561 if (!ClassType->isDependentType()) { 7562 DeclarationName Name 7563 = Context.DeclarationNames.getCXXDestructorName( 7564 Context.getCanonicalType(ClassType)); 7565 if (NewFD->getDeclName() != Name) { 7566 Diag(NewFD->getLocation(), diag::err_destructor_name); 7567 NewFD->setInvalidDecl(); 7568 return Redeclaration; 7569 } 7570 } 7571 } else if (CXXConversionDecl *Conversion 7572 = dyn_cast<CXXConversionDecl>(NewFD)) { 7573 ActOnConversionDeclarator(Conversion); 7574 } 7575 7576 // Find any virtual functions that this function overrides. 7577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7578 if (!Method->isFunctionTemplateSpecialization() && 7579 !Method->getDescribedFunctionTemplate() && 7580 Method->isCanonicalDecl()) { 7581 if (AddOverriddenMethods(Method->getParent(), Method)) { 7582 // If the function was marked as "static", we have a problem. 7583 if (NewFD->getStorageClass() == SC_Static) { 7584 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7585 } 7586 } 7587 } 7588 7589 if (Method->isStatic()) 7590 checkThisInStaticMemberFunctionType(Method); 7591 } 7592 7593 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7594 if (NewFD->isOverloadedOperator() && 7595 CheckOverloadedOperatorDeclaration(NewFD)) { 7596 NewFD->setInvalidDecl(); 7597 return Redeclaration; 7598 } 7599 7600 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7601 if (NewFD->getLiteralIdentifier() && 7602 CheckLiteralOperatorDeclaration(NewFD)) { 7603 NewFD->setInvalidDecl(); 7604 return Redeclaration; 7605 } 7606 7607 // In C++, check default arguments now that we have merged decls. Unless 7608 // the lexical context is the class, because in this case this is done 7609 // during delayed parsing anyway. 7610 if (!CurContext->isRecord()) 7611 CheckCXXDefaultArguments(NewFD); 7612 7613 // If this function declares a builtin function, check the type of this 7614 // declaration against the expected type for the builtin. 7615 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7616 ASTContext::GetBuiltinTypeError Error; 7617 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7618 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7619 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7620 // The type of this function differs from the type of the builtin, 7621 // so forget about the builtin entirely. 7622 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7623 } 7624 } 7625 7626 // If this function is declared as being extern "C", then check to see if 7627 // the function returns a UDT (class, struct, or union type) that is not C 7628 // compatible, and if it does, warn the user. 7629 // But, issue any diagnostic on the first declaration only. 7630 if (NewFD->isExternC() && Previous.empty()) { 7631 QualType R = NewFD->getReturnType(); 7632 if (R->isIncompleteType() && !R->isVoidType()) 7633 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7634 << NewFD << R; 7635 else if (!R.isPODType(Context) && !R->isVoidType() && 7636 !R->isObjCObjectPointerType()) 7637 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7638 } 7639 } 7640 return Redeclaration; 7641 } 7642 7643 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7644 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7645 if (!TSI) 7646 return SourceRange(); 7647 7648 TypeLoc TL = TSI->getTypeLoc(); 7649 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7650 if (!FunctionTL) 7651 return SourceRange(); 7652 7653 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7654 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7655 return ResultTL.getSourceRange(); 7656 7657 return SourceRange(); 7658 } 7659 7660 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7661 // C++11 [basic.start.main]p3: 7662 // A program that [...] declares main to be inline, static or 7663 // constexpr is ill-formed. 7664 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7665 // appear in a declaration of main. 7666 // static main is not an error under C99, but we should warn about it. 7667 // We accept _Noreturn main as an extension. 7668 if (FD->getStorageClass() == SC_Static) 7669 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7670 ? diag::err_static_main : diag::warn_static_main) 7671 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7672 if (FD->isInlineSpecified()) 7673 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7674 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7675 if (DS.isNoreturnSpecified()) { 7676 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7677 SourceRange NoreturnRange(NoreturnLoc, 7678 PP.getLocForEndOfToken(NoreturnLoc)); 7679 Diag(NoreturnLoc, diag::ext_noreturn_main); 7680 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7681 << FixItHint::CreateRemoval(NoreturnRange); 7682 } 7683 if (FD->isConstexpr()) { 7684 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7685 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7686 FD->setConstexpr(false); 7687 } 7688 7689 if (getLangOpts().OpenCL) { 7690 Diag(FD->getLocation(), diag::err_opencl_no_main) 7691 << FD->hasAttr<OpenCLKernelAttr>(); 7692 FD->setInvalidDecl(); 7693 return; 7694 } 7695 7696 QualType T = FD->getType(); 7697 assert(T->isFunctionType() && "function decl is not of function type"); 7698 const FunctionType* FT = T->castAs<FunctionType>(); 7699 7700 // All the standards say that main() should should return 'int'. 7701 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7702 // In C and C++, main magically returns 0 if you fall off the end; 7703 // set the flag which tells us that. 7704 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7705 FD->setHasImplicitReturnZero(true); 7706 7707 // In C with GNU extensions we allow main() to have non-integer return 7708 // type, but we should warn about the extension, and we disable the 7709 // implicit-return-zero rule. 7710 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7711 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7712 7713 SourceRange ResultRange = getResultSourceRange(FD); 7714 if (ResultRange.isValid()) 7715 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7716 << FixItHint::CreateReplacement(ResultRange, "int"); 7717 7718 // Otherwise, this is just a flat-out error. 7719 } else { 7720 SourceRange ResultRange = getResultSourceRange(FD); 7721 if (ResultRange.isValid()) 7722 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7723 << FixItHint::CreateReplacement(ResultRange, "int"); 7724 else 7725 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7726 7727 FD->setInvalidDecl(true); 7728 } 7729 7730 // Treat protoless main() as nullary. 7731 if (isa<FunctionNoProtoType>(FT)) return; 7732 7733 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7734 unsigned nparams = FTP->getNumParams(); 7735 assert(FD->getNumParams() == nparams); 7736 7737 bool HasExtraParameters = (nparams > 3); 7738 7739 // Darwin passes an undocumented fourth argument of type char**. If 7740 // other platforms start sprouting these, the logic below will start 7741 // getting shifty. 7742 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7743 HasExtraParameters = false; 7744 7745 if (HasExtraParameters) { 7746 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7747 FD->setInvalidDecl(true); 7748 nparams = 3; 7749 } 7750 7751 // FIXME: a lot of the following diagnostics would be improved 7752 // if we had some location information about types. 7753 7754 QualType CharPP = 7755 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7756 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7757 7758 for (unsigned i = 0; i < nparams; ++i) { 7759 QualType AT = FTP->getParamType(i); 7760 7761 bool mismatch = true; 7762 7763 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7764 mismatch = false; 7765 else if (Expected[i] == CharPP) { 7766 // As an extension, the following forms are okay: 7767 // char const ** 7768 // char const * const * 7769 // char * const * 7770 7771 QualifierCollector qs; 7772 const PointerType* PT; 7773 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7774 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7775 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7776 Context.CharTy)) { 7777 qs.removeConst(); 7778 mismatch = !qs.empty(); 7779 } 7780 } 7781 7782 if (mismatch) { 7783 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7784 // TODO: suggest replacing given type with expected type 7785 FD->setInvalidDecl(true); 7786 } 7787 } 7788 7789 if (nparams == 1 && !FD->isInvalidDecl()) { 7790 Diag(FD->getLocation(), diag::warn_main_one_arg); 7791 } 7792 7793 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7794 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7795 FD->setInvalidDecl(); 7796 } 7797 } 7798 7799 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7800 QualType T = FD->getType(); 7801 assert(T->isFunctionType() && "function decl is not of function type"); 7802 const FunctionType *FT = T->castAs<FunctionType>(); 7803 7804 // Set an implicit return of 'zero' if the function can return some integral, 7805 // enumeration, pointer or nullptr type. 7806 if (FT->getReturnType()->isIntegralOrEnumerationType() || 7807 FT->getReturnType()->isAnyPointerType() || 7808 FT->getReturnType()->isNullPtrType()) 7809 // DllMain is exempt because a return value of zero means it failed. 7810 if (FD->getName() != "DllMain") 7811 FD->setHasImplicitReturnZero(true); 7812 7813 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7814 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7815 FD->setInvalidDecl(); 7816 } 7817 } 7818 7819 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7820 // FIXME: Need strict checking. In C89, we need to check for 7821 // any assignment, increment, decrement, function-calls, or 7822 // commas outside of a sizeof. In C99, it's the same list, 7823 // except that the aforementioned are allowed in unevaluated 7824 // expressions. Everything else falls under the 7825 // "may accept other forms of constant expressions" exception. 7826 // (We never end up here for C++, so the constant expression 7827 // rules there don't matter.) 7828 if (Init->isConstantInitializer(Context, false)) 7829 return false; 7830 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7831 << Init->getSourceRange(); 7832 return true; 7833 } 7834 7835 namespace { 7836 // Visits an initialization expression to see if OrigDecl is evaluated in 7837 // its own initialization and throws a warning if it does. 7838 class SelfReferenceChecker 7839 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7840 Sema &S; 7841 Decl *OrigDecl; 7842 bool isRecordType; 7843 bool isPODType; 7844 bool isReferenceType; 7845 7846 public: 7847 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7848 7849 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7850 S(S), OrigDecl(OrigDecl) { 7851 isPODType = false; 7852 isRecordType = false; 7853 isReferenceType = false; 7854 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7855 isPODType = VD->getType().isPODType(S.Context); 7856 isRecordType = VD->getType()->isRecordType(); 7857 isReferenceType = VD->getType()->isReferenceType(); 7858 } 7859 } 7860 7861 // For most expressions, the cast is directly above the DeclRefExpr. 7862 // For conditional operators, the cast can be outside the conditional 7863 // operator if both expressions are DeclRefExpr's. 7864 void HandleValue(Expr *E) { 7865 if (isReferenceType) 7866 return; 7867 E = E->IgnoreParenImpCasts(); 7868 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7869 HandleDeclRefExpr(DRE); 7870 return; 7871 } 7872 7873 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7874 HandleValue(CO->getTrueExpr()); 7875 HandleValue(CO->getFalseExpr()); 7876 return; 7877 } 7878 7879 if (isa<MemberExpr>(E)) { 7880 Expr *Base = E->IgnoreParenImpCasts(); 7881 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7882 // Check for static member variables and don't warn on them. 7883 if (!isa<FieldDecl>(ME->getMemberDecl())) 7884 return; 7885 Base = ME->getBase()->IgnoreParenImpCasts(); 7886 } 7887 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7888 HandleDeclRefExpr(DRE); 7889 return; 7890 } 7891 } 7892 7893 // Reference types are handled here since all uses of references are 7894 // bad, not just r-value uses. 7895 void VisitDeclRefExpr(DeclRefExpr *E) { 7896 if (isReferenceType) 7897 HandleDeclRefExpr(E); 7898 } 7899 7900 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7901 if (E->getCastKind() == CK_LValueToRValue || 7902 (isRecordType && E->getCastKind() == CK_NoOp)) 7903 HandleValue(E->getSubExpr()); 7904 7905 Inherited::VisitImplicitCastExpr(E); 7906 } 7907 7908 void VisitMemberExpr(MemberExpr *E) { 7909 // Don't warn on arrays since they can be treated as pointers. 7910 if (E->getType()->canDecayToPointerType()) return; 7911 7912 // Warn when a non-static method call is followed by non-static member 7913 // field accesses, which is followed by a DeclRefExpr. 7914 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7915 bool Warn = (MD && !MD->isStatic()); 7916 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7917 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7918 if (!isa<FieldDecl>(ME->getMemberDecl())) 7919 Warn = false; 7920 Base = ME->getBase()->IgnoreParenImpCasts(); 7921 } 7922 7923 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7924 if (Warn) 7925 HandleDeclRefExpr(DRE); 7926 return; 7927 } 7928 7929 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7930 // Visit that expression. 7931 Visit(Base); 7932 } 7933 7934 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 7935 if (E->getNumArgs() > 0) 7936 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 7937 HandleDeclRefExpr(DRE); 7938 7939 Inherited::VisitCXXOperatorCallExpr(E); 7940 } 7941 7942 void VisitUnaryOperator(UnaryOperator *E) { 7943 // For POD record types, addresses of its own members are well-defined. 7944 if (E->getOpcode() == UO_AddrOf && isRecordType && 7945 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7946 if (!isPODType) 7947 HandleValue(E->getSubExpr()); 7948 return; 7949 } 7950 Inherited::VisitUnaryOperator(E); 7951 } 7952 7953 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7954 7955 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7956 Decl* ReferenceDecl = DRE->getDecl(); 7957 if (OrigDecl != ReferenceDecl) return; 7958 unsigned diag; 7959 if (isReferenceType) { 7960 diag = diag::warn_uninit_self_reference_in_reference_init; 7961 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7962 diag = diag::warn_static_self_reference_in_init; 7963 } else { 7964 diag = diag::warn_uninit_self_reference_in_init; 7965 } 7966 7967 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7968 S.PDiag(diag) 7969 << DRE->getNameInfo().getName() 7970 << OrigDecl->getLocation() 7971 << DRE->getSourceRange()); 7972 } 7973 }; 7974 7975 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 7976 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 7977 bool DirectInit) { 7978 // Parameters arguments are occassionially constructed with itself, 7979 // for instance, in recursive functions. Skip them. 7980 if (isa<ParmVarDecl>(OrigDecl)) 7981 return; 7982 7983 E = E->IgnoreParens(); 7984 7985 // Skip checking T a = a where T is not a record or reference type. 7986 // Doing so is a way to silence uninitialized warnings. 7987 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 7988 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 7989 if (ICE->getCastKind() == CK_LValueToRValue) 7990 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 7991 if (DRE->getDecl() == OrigDecl) 7992 return; 7993 7994 SelfReferenceChecker(S, OrigDecl).Visit(E); 7995 } 7996 } 7997 7998 /// AddInitializerToDecl - Adds the initializer Init to the 7999 /// declaration dcl. If DirectInit is true, this is C++ direct 8000 /// initialization rather than copy initialization. 8001 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8002 bool DirectInit, bool TypeMayContainAuto) { 8003 // If there is no declaration, there was an error parsing it. Just ignore 8004 // the initializer. 8005 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8006 return; 8007 8008 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8009 // With declarators parsed the way they are, the parser cannot 8010 // distinguish between a normal initializer and a pure-specifier. 8011 // Thus this grotesque test. 8012 IntegerLiteral *IL; 8013 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8014 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8015 CheckPureMethod(Method, Init->getSourceRange()); 8016 else { 8017 Diag(Method->getLocation(), diag::err_member_function_initialization) 8018 << Method->getDeclName() << Init->getSourceRange(); 8019 Method->setInvalidDecl(); 8020 } 8021 return; 8022 } 8023 8024 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8025 if (!VDecl) { 8026 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8027 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8028 RealDecl->setInvalidDecl(); 8029 return; 8030 } 8031 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8032 8033 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8034 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8035 Expr *DeduceInit = Init; 8036 // Initializer could be a C++ direct-initializer. Deduction only works if it 8037 // contains exactly one expression. 8038 if (CXXDirectInit) { 8039 if (CXXDirectInit->getNumExprs() == 0) { 8040 // It isn't possible to write this directly, but it is possible to 8041 // end up in this situation with "auto x(some_pack...);" 8042 Diag(CXXDirectInit->getLocStart(), 8043 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8044 : diag::err_auto_var_init_no_expression) 8045 << VDecl->getDeclName() << VDecl->getType() 8046 << VDecl->getSourceRange(); 8047 RealDecl->setInvalidDecl(); 8048 return; 8049 } else if (CXXDirectInit->getNumExprs() > 1) { 8050 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8051 VDecl->isInitCapture() 8052 ? diag::err_init_capture_multiple_expressions 8053 : diag::err_auto_var_init_multiple_expressions) 8054 << VDecl->getDeclName() << VDecl->getType() 8055 << VDecl->getSourceRange(); 8056 RealDecl->setInvalidDecl(); 8057 return; 8058 } else { 8059 DeduceInit = CXXDirectInit->getExpr(0); 8060 } 8061 } 8062 8063 // Expressions default to 'id' when we're in a debugger. 8064 bool DefaultedToAuto = false; 8065 if (getLangOpts().DebuggerCastResultToId && 8066 Init->getType() == Context.UnknownAnyTy) { 8067 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8068 if (Result.isInvalid()) { 8069 VDecl->setInvalidDecl(); 8070 return; 8071 } 8072 Init = Result.take(); 8073 DefaultedToAuto = true; 8074 } 8075 8076 QualType DeducedType; 8077 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8078 DAR_Failed) 8079 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8080 if (DeducedType.isNull()) { 8081 RealDecl->setInvalidDecl(); 8082 return; 8083 } 8084 VDecl->setType(DeducedType); 8085 assert(VDecl->isLinkageValid()); 8086 8087 // In ARC, infer lifetime. 8088 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8089 VDecl->setInvalidDecl(); 8090 8091 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8092 // 'id' instead of a specific object type prevents most of our usual checks. 8093 // We only want to warn outside of template instantiations, though: 8094 // inside a template, the 'id' could have come from a parameter. 8095 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8096 DeducedType->isObjCIdType()) { 8097 SourceLocation Loc = 8098 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8099 Diag(Loc, diag::warn_auto_var_is_id) 8100 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8101 } 8102 8103 // If this is a redeclaration, check that the type we just deduced matches 8104 // the previously declared type. 8105 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8106 // We never need to merge the type, because we cannot form an incomplete 8107 // array of auto, nor deduce such a type. 8108 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8109 } 8110 8111 // Check the deduced type is valid for a variable declaration. 8112 CheckVariableDeclarationType(VDecl); 8113 if (VDecl->isInvalidDecl()) 8114 return; 8115 } 8116 8117 // dllimport cannot be used on variable definitions. 8118 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8119 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8120 VDecl->setInvalidDecl(); 8121 return; 8122 } 8123 8124 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8125 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8126 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8127 VDecl->setInvalidDecl(); 8128 return; 8129 } 8130 8131 if (!VDecl->getType()->isDependentType()) { 8132 // A definition must end up with a complete type, which means it must be 8133 // complete with the restriction that an array type might be completed by 8134 // the initializer; note that later code assumes this restriction. 8135 QualType BaseDeclType = VDecl->getType(); 8136 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8137 BaseDeclType = Array->getElementType(); 8138 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8139 diag::err_typecheck_decl_incomplete_type)) { 8140 RealDecl->setInvalidDecl(); 8141 return; 8142 } 8143 8144 // The variable can not have an abstract class type. 8145 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8146 diag::err_abstract_type_in_decl, 8147 AbstractVariableType)) 8148 VDecl->setInvalidDecl(); 8149 } 8150 8151 const VarDecl *Def; 8152 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8153 Diag(VDecl->getLocation(), diag::err_redefinition) 8154 << VDecl->getDeclName(); 8155 Diag(Def->getLocation(), diag::note_previous_definition); 8156 VDecl->setInvalidDecl(); 8157 return; 8158 } 8159 8160 const VarDecl* PrevInit = 0; 8161 if (getLangOpts().CPlusPlus) { 8162 // C++ [class.static.data]p4 8163 // If a static data member is of const integral or const 8164 // enumeration type, its declaration in the class definition can 8165 // specify a constant-initializer which shall be an integral 8166 // constant expression (5.19). In that case, the member can appear 8167 // in integral constant expressions. The member shall still be 8168 // defined in a namespace scope if it is used in the program and the 8169 // namespace scope definition shall not contain an initializer. 8170 // 8171 // We already performed a redefinition check above, but for static 8172 // data members we also need to check whether there was an in-class 8173 // declaration with an initializer. 8174 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8175 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8176 << VDecl->getDeclName(); 8177 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8178 return; 8179 } 8180 8181 if (VDecl->hasLocalStorage()) 8182 getCurFunction()->setHasBranchProtectedScope(); 8183 8184 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8185 VDecl->setInvalidDecl(); 8186 return; 8187 } 8188 } 8189 8190 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8191 // a kernel function cannot be initialized." 8192 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8193 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8194 VDecl->setInvalidDecl(); 8195 return; 8196 } 8197 8198 // Get the decls type and save a reference for later, since 8199 // CheckInitializerTypes may change it. 8200 QualType DclT = VDecl->getType(), SavT = DclT; 8201 8202 // Expressions default to 'id' when we're in a debugger 8203 // and we are assigning it to a variable of Objective-C pointer type. 8204 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8205 Init->getType() == Context.UnknownAnyTy) { 8206 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8207 if (Result.isInvalid()) { 8208 VDecl->setInvalidDecl(); 8209 return; 8210 } 8211 Init = Result.take(); 8212 } 8213 8214 // Perform the initialization. 8215 if (!VDecl->isInvalidDecl()) { 8216 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8217 InitializationKind Kind 8218 = DirectInit ? 8219 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8220 Init->getLocStart(), 8221 Init->getLocEnd()) 8222 : InitializationKind::CreateDirectList( 8223 VDecl->getLocation()) 8224 : InitializationKind::CreateCopy(VDecl->getLocation(), 8225 Init->getLocStart()); 8226 8227 MultiExprArg Args = Init; 8228 if (CXXDirectInit) 8229 Args = MultiExprArg(CXXDirectInit->getExprs(), 8230 CXXDirectInit->getNumExprs()); 8231 8232 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8233 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8234 if (Result.isInvalid()) { 8235 VDecl->setInvalidDecl(); 8236 return; 8237 } 8238 8239 Init = Result.takeAs<Expr>(); 8240 } 8241 8242 // Check for self-references within variable initializers. 8243 // Variables declared within a function/method body (except for references) 8244 // are handled by a dataflow analysis. 8245 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8246 VDecl->getType()->isReferenceType()) { 8247 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8248 } 8249 8250 // If the type changed, it means we had an incomplete type that was 8251 // completed by the initializer. For example: 8252 // int ary[] = { 1, 3, 5 }; 8253 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8254 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8255 VDecl->setType(DclT); 8256 8257 if (!VDecl->isInvalidDecl()) { 8258 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8259 8260 if (VDecl->hasAttr<BlocksAttr>()) 8261 checkRetainCycles(VDecl, Init); 8262 8263 // It is safe to assign a weak reference into a strong variable. 8264 // Although this code can still have problems: 8265 // id x = self.weakProp; 8266 // id y = self.weakProp; 8267 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8268 // paths through the function. This should be revisited if 8269 // -Wrepeated-use-of-weak is made flow-sensitive. 8270 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8271 DiagnosticsEngine::Level Level = 8272 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8273 Init->getLocStart()); 8274 if (Level != DiagnosticsEngine::Ignored) 8275 getCurFunction()->markSafeWeakUse(Init); 8276 } 8277 } 8278 8279 // The initialization is usually a full-expression. 8280 // 8281 // FIXME: If this is a braced initialization of an aggregate, it is not 8282 // an expression, and each individual field initializer is a separate 8283 // full-expression. For instance, in: 8284 // 8285 // struct Temp { ~Temp(); }; 8286 // struct S { S(Temp); }; 8287 // struct T { S a, b; } t = { Temp(), Temp() } 8288 // 8289 // we should destroy the first Temp before constructing the second. 8290 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8291 false, 8292 VDecl->isConstexpr()); 8293 if (Result.isInvalid()) { 8294 VDecl->setInvalidDecl(); 8295 return; 8296 } 8297 Init = Result.take(); 8298 8299 // Attach the initializer to the decl. 8300 VDecl->setInit(Init); 8301 8302 if (VDecl->isLocalVarDecl()) { 8303 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8304 // static storage duration shall be constant expressions or string literals. 8305 // C++ does not have this restriction. 8306 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8307 if (VDecl->getStorageClass() == SC_Static) 8308 CheckForConstantInitializer(Init, DclT); 8309 // C89 is stricter than C99 for non-static aggregate types. 8310 // C89 6.5.7p3: All the expressions [...] in an initializer list 8311 // for an object that has aggregate or union type shall be 8312 // constant expressions. 8313 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8314 isa<InitListExpr>(Init) && 8315 !Init->isConstantInitializer(Context, false)) 8316 Diag(Init->getExprLoc(), 8317 diag::ext_aggregate_init_not_constant) 8318 << Init->getSourceRange(); 8319 } 8320 } else if (VDecl->isStaticDataMember() && 8321 VDecl->getLexicalDeclContext()->isRecord()) { 8322 // This is an in-class initialization for a static data member, e.g., 8323 // 8324 // struct S { 8325 // static const int value = 17; 8326 // }; 8327 8328 // C++ [class.mem]p4: 8329 // A member-declarator can contain a constant-initializer only 8330 // if it declares a static member (9.4) of const integral or 8331 // const enumeration type, see 9.4.2. 8332 // 8333 // C++11 [class.static.data]p3: 8334 // If a non-volatile const static data member is of integral or 8335 // enumeration type, its declaration in the class definition can 8336 // specify a brace-or-equal-initializer in which every initalizer-clause 8337 // that is an assignment-expression is a constant expression. A static 8338 // data member of literal type can be declared in the class definition 8339 // with the constexpr specifier; if so, its declaration shall specify a 8340 // brace-or-equal-initializer in which every initializer-clause that is 8341 // an assignment-expression is a constant expression. 8342 8343 // Do nothing on dependent types. 8344 if (DclT->isDependentType()) { 8345 8346 // Allow any 'static constexpr' members, whether or not they are of literal 8347 // type. We separately check that every constexpr variable is of literal 8348 // type. 8349 } else if (VDecl->isConstexpr()) { 8350 8351 // Require constness. 8352 } else if (!DclT.isConstQualified()) { 8353 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8354 << Init->getSourceRange(); 8355 VDecl->setInvalidDecl(); 8356 8357 // We allow integer constant expressions in all cases. 8358 } else if (DclT->isIntegralOrEnumerationType()) { 8359 // Check whether the expression is a constant expression. 8360 SourceLocation Loc; 8361 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8362 // In C++11, a non-constexpr const static data member with an 8363 // in-class initializer cannot be volatile. 8364 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8365 else if (Init->isValueDependent()) 8366 ; // Nothing to check. 8367 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8368 ; // Ok, it's an ICE! 8369 else if (Init->isEvaluatable(Context)) { 8370 // If we can constant fold the initializer through heroics, accept it, 8371 // but report this as a use of an extension for -pedantic. 8372 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8373 << Init->getSourceRange(); 8374 } else { 8375 // Otherwise, this is some crazy unknown case. Report the issue at the 8376 // location provided by the isIntegerConstantExpr failed check. 8377 Diag(Loc, diag::err_in_class_initializer_non_constant) 8378 << Init->getSourceRange(); 8379 VDecl->setInvalidDecl(); 8380 } 8381 8382 // We allow foldable floating-point constants as an extension. 8383 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8384 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8385 // it anyway and provide a fixit to add the 'constexpr'. 8386 if (getLangOpts().CPlusPlus11) { 8387 Diag(VDecl->getLocation(), 8388 diag::ext_in_class_initializer_float_type_cxx11) 8389 << DclT << Init->getSourceRange(); 8390 Diag(VDecl->getLocStart(), 8391 diag::note_in_class_initializer_float_type_cxx11) 8392 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8393 } else { 8394 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8395 << DclT << Init->getSourceRange(); 8396 8397 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8398 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8399 << Init->getSourceRange(); 8400 VDecl->setInvalidDecl(); 8401 } 8402 } 8403 8404 // Suggest adding 'constexpr' in C++11 for literal types. 8405 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8406 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8407 << DclT << Init->getSourceRange() 8408 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8409 VDecl->setConstexpr(true); 8410 8411 } else { 8412 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8413 << DclT << Init->getSourceRange(); 8414 VDecl->setInvalidDecl(); 8415 } 8416 } else if (VDecl->isFileVarDecl()) { 8417 if (VDecl->getStorageClass() == SC_Extern && 8418 (!getLangOpts().CPlusPlus || 8419 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8420 VDecl->isExternC())) && 8421 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8422 Diag(VDecl->getLocation(), diag::warn_extern_init); 8423 8424 // C99 6.7.8p4. All file scoped initializers need to be constant. 8425 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8426 CheckForConstantInitializer(Init, DclT); 8427 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8428 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8429 !Init->isValueDependent() && !VDecl->isConstexpr() && 8430 !Init->isConstantInitializer( 8431 Context, VDecl->getType()->isReferenceType())) { 8432 // GNU C++98 edits for __thread, [basic.start.init]p4: 8433 // An object of thread storage duration shall not require dynamic 8434 // initialization. 8435 // FIXME: Need strict checking here. 8436 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8437 if (getLangOpts().CPlusPlus11) 8438 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8439 } 8440 } 8441 8442 // We will represent direct-initialization similarly to copy-initialization: 8443 // int x(1); -as-> int x = 1; 8444 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8445 // 8446 // Clients that want to distinguish between the two forms, can check for 8447 // direct initializer using VarDecl::getInitStyle(). 8448 // A major benefit is that clients that don't particularly care about which 8449 // exactly form was it (like the CodeGen) can handle both cases without 8450 // special case code. 8451 8452 // C++ 8.5p11: 8453 // The form of initialization (using parentheses or '=') is generally 8454 // insignificant, but does matter when the entity being initialized has a 8455 // class type. 8456 if (CXXDirectInit) { 8457 assert(DirectInit && "Call-style initializer must be direct init."); 8458 VDecl->setInitStyle(VarDecl::CallInit); 8459 } else if (DirectInit) { 8460 // This must be list-initialization. No other way is direct-initialization. 8461 VDecl->setInitStyle(VarDecl::ListInit); 8462 } 8463 8464 CheckCompleteVariableDeclaration(VDecl); 8465 } 8466 8467 /// ActOnInitializerError - Given that there was an error parsing an 8468 /// initializer for the given declaration, try to return to some form 8469 /// of sanity. 8470 void Sema::ActOnInitializerError(Decl *D) { 8471 // Our main concern here is re-establishing invariants like "a 8472 // variable's type is either dependent or complete". 8473 if (!D || D->isInvalidDecl()) return; 8474 8475 VarDecl *VD = dyn_cast<VarDecl>(D); 8476 if (!VD) return; 8477 8478 // Auto types are meaningless if we can't make sense of the initializer. 8479 if (ParsingInitForAutoVars.count(D)) { 8480 D->setInvalidDecl(); 8481 return; 8482 } 8483 8484 QualType Ty = VD->getType(); 8485 if (Ty->isDependentType()) return; 8486 8487 // Require a complete type. 8488 if (RequireCompleteType(VD->getLocation(), 8489 Context.getBaseElementType(Ty), 8490 diag::err_typecheck_decl_incomplete_type)) { 8491 VD->setInvalidDecl(); 8492 return; 8493 } 8494 8495 // Require an abstract type. 8496 if (RequireNonAbstractType(VD->getLocation(), Ty, 8497 diag::err_abstract_type_in_decl, 8498 AbstractVariableType)) { 8499 VD->setInvalidDecl(); 8500 return; 8501 } 8502 8503 // Don't bother complaining about constructors or destructors, 8504 // though. 8505 } 8506 8507 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8508 bool TypeMayContainAuto) { 8509 // If there is no declaration, there was an error parsing it. Just ignore it. 8510 if (RealDecl == 0) 8511 return; 8512 8513 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8514 QualType Type = Var->getType(); 8515 8516 // C++11 [dcl.spec.auto]p3 8517 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8518 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8519 << Var->getDeclName() << Type; 8520 Var->setInvalidDecl(); 8521 return; 8522 } 8523 8524 // C++11 [class.static.data]p3: A static data member can be declared with 8525 // the constexpr specifier; if so, its declaration shall specify 8526 // a brace-or-equal-initializer. 8527 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8528 // the definition of a variable [...] or the declaration of a static data 8529 // member. 8530 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8531 if (Var->isStaticDataMember()) 8532 Diag(Var->getLocation(), 8533 diag::err_constexpr_static_mem_var_requires_init) 8534 << Var->getDeclName(); 8535 else 8536 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8537 Var->setInvalidDecl(); 8538 return; 8539 } 8540 8541 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8542 // be initialized. 8543 if (!Var->isInvalidDecl() && 8544 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8545 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8546 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 8547 Var->setInvalidDecl(); 8548 return; 8549 } 8550 8551 switch (Var->isThisDeclarationADefinition()) { 8552 case VarDecl::Definition: 8553 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8554 break; 8555 8556 // We have an out-of-line definition of a static data member 8557 // that has an in-class initializer, so we type-check this like 8558 // a declaration. 8559 // 8560 // Fall through 8561 8562 case VarDecl::DeclarationOnly: 8563 // It's only a declaration. 8564 8565 // Block scope. C99 6.7p7: If an identifier for an object is 8566 // declared with no linkage (C99 6.2.2p6), the type for the 8567 // object shall be complete. 8568 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8569 !Var->hasLinkage() && !Var->isInvalidDecl() && 8570 RequireCompleteType(Var->getLocation(), Type, 8571 diag::err_typecheck_decl_incomplete_type)) 8572 Var->setInvalidDecl(); 8573 8574 // Make sure that the type is not abstract. 8575 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8576 RequireNonAbstractType(Var->getLocation(), Type, 8577 diag::err_abstract_type_in_decl, 8578 AbstractVariableType)) 8579 Var->setInvalidDecl(); 8580 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8581 Var->getStorageClass() == SC_PrivateExtern) { 8582 Diag(Var->getLocation(), diag::warn_private_extern); 8583 Diag(Var->getLocation(), diag::note_private_extern); 8584 } 8585 8586 return; 8587 8588 case VarDecl::TentativeDefinition: 8589 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8590 // object that has file scope without an initializer, and without a 8591 // storage-class specifier or with the storage-class specifier "static", 8592 // constitutes a tentative definition. Note: A tentative definition with 8593 // external linkage is valid (C99 6.2.2p5). 8594 if (!Var->isInvalidDecl()) { 8595 if (const IncompleteArrayType *ArrayT 8596 = Context.getAsIncompleteArrayType(Type)) { 8597 if (RequireCompleteType(Var->getLocation(), 8598 ArrayT->getElementType(), 8599 diag::err_illegal_decl_array_incomplete_type)) 8600 Var->setInvalidDecl(); 8601 } else if (Var->getStorageClass() == SC_Static) { 8602 // C99 6.9.2p3: If the declaration of an identifier for an object is 8603 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8604 // declared type shall not be an incomplete type. 8605 // NOTE: code such as the following 8606 // static struct s; 8607 // struct s { int a; }; 8608 // is accepted by gcc. Hence here we issue a warning instead of 8609 // an error and we do not invalidate the static declaration. 8610 // NOTE: to avoid multiple warnings, only check the first declaration. 8611 if (Var->isFirstDecl()) 8612 RequireCompleteType(Var->getLocation(), Type, 8613 diag::ext_typecheck_decl_incomplete_type); 8614 } 8615 } 8616 8617 // Record the tentative definition; we're done. 8618 if (!Var->isInvalidDecl()) 8619 TentativeDefinitions.push_back(Var); 8620 return; 8621 } 8622 8623 // Provide a specific diagnostic for uninitialized variable 8624 // definitions with incomplete array type. 8625 if (Type->isIncompleteArrayType()) { 8626 Diag(Var->getLocation(), 8627 diag::err_typecheck_incomplete_array_needs_initializer); 8628 Var->setInvalidDecl(); 8629 return; 8630 } 8631 8632 // Provide a specific diagnostic for uninitialized variable 8633 // definitions with reference type. 8634 if (Type->isReferenceType()) { 8635 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8636 << Var->getDeclName() 8637 << SourceRange(Var->getLocation(), Var->getLocation()); 8638 Var->setInvalidDecl(); 8639 return; 8640 } 8641 8642 // Do not attempt to type-check the default initializer for a 8643 // variable with dependent type. 8644 if (Type->isDependentType()) 8645 return; 8646 8647 if (Var->isInvalidDecl()) 8648 return; 8649 8650 if (RequireCompleteType(Var->getLocation(), 8651 Context.getBaseElementType(Type), 8652 diag::err_typecheck_decl_incomplete_type)) { 8653 Var->setInvalidDecl(); 8654 return; 8655 } 8656 8657 // The variable can not have an abstract class type. 8658 if (RequireNonAbstractType(Var->getLocation(), Type, 8659 diag::err_abstract_type_in_decl, 8660 AbstractVariableType)) { 8661 Var->setInvalidDecl(); 8662 return; 8663 } 8664 8665 // Check for jumps past the implicit initializer. C++0x 8666 // clarifies that this applies to a "variable with automatic 8667 // storage duration", not a "local variable". 8668 // C++11 [stmt.dcl]p3 8669 // A program that jumps from a point where a variable with automatic 8670 // storage duration is not in scope to a point where it is in scope is 8671 // ill-formed unless the variable has scalar type, class type with a 8672 // trivial default constructor and a trivial destructor, a cv-qualified 8673 // version of one of these types, or an array of one of the preceding 8674 // types and is declared without an initializer. 8675 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8676 if (const RecordType *Record 8677 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8678 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8679 // Mark the function for further checking even if the looser rules of 8680 // C++11 do not require such checks, so that we can diagnose 8681 // incompatibilities with C++98. 8682 if (!CXXRecord->isPOD()) 8683 getCurFunction()->setHasBranchProtectedScope(); 8684 } 8685 } 8686 8687 // C++03 [dcl.init]p9: 8688 // If no initializer is specified for an object, and the 8689 // object is of (possibly cv-qualified) non-POD class type (or 8690 // array thereof), the object shall be default-initialized; if 8691 // the object is of const-qualified type, the underlying class 8692 // type shall have a user-declared default 8693 // constructor. Otherwise, if no initializer is specified for 8694 // a non- static object, the object and its subobjects, if 8695 // any, have an indeterminate initial value); if the object 8696 // or any of its subobjects are of const-qualified type, the 8697 // program is ill-formed. 8698 // C++0x [dcl.init]p11: 8699 // If no initializer is specified for an object, the object is 8700 // default-initialized; [...]. 8701 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8702 InitializationKind Kind 8703 = InitializationKind::CreateDefault(Var->getLocation()); 8704 8705 InitializationSequence InitSeq(*this, Entity, Kind, None); 8706 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8707 if (Init.isInvalid()) 8708 Var->setInvalidDecl(); 8709 else if (Init.get()) { 8710 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8711 // This is important for template substitution. 8712 Var->setInitStyle(VarDecl::CallInit); 8713 } 8714 8715 CheckCompleteVariableDeclaration(Var); 8716 } 8717 } 8718 8719 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8720 VarDecl *VD = dyn_cast<VarDecl>(D); 8721 if (!VD) { 8722 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8723 D->setInvalidDecl(); 8724 return; 8725 } 8726 8727 VD->setCXXForRangeDecl(true); 8728 8729 // for-range-declaration cannot be given a storage class specifier. 8730 int Error = -1; 8731 switch (VD->getStorageClass()) { 8732 case SC_None: 8733 break; 8734 case SC_Extern: 8735 Error = 0; 8736 break; 8737 case SC_Static: 8738 Error = 1; 8739 break; 8740 case SC_PrivateExtern: 8741 Error = 2; 8742 break; 8743 case SC_Auto: 8744 Error = 3; 8745 break; 8746 case SC_Register: 8747 Error = 4; 8748 break; 8749 case SC_OpenCLWorkGroupLocal: 8750 llvm_unreachable("Unexpected storage class"); 8751 } 8752 if (VD->isConstexpr()) 8753 Error = 5; 8754 if (Error != -1) { 8755 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8756 << VD->getDeclName() << Error; 8757 D->setInvalidDecl(); 8758 } 8759 } 8760 8761 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8762 if (var->isInvalidDecl()) return; 8763 8764 // In ARC, don't allow jumps past the implicit initialization of a 8765 // local retaining variable. 8766 if (getLangOpts().ObjCAutoRefCount && 8767 var->hasLocalStorage()) { 8768 switch (var->getType().getObjCLifetime()) { 8769 case Qualifiers::OCL_None: 8770 case Qualifiers::OCL_ExplicitNone: 8771 case Qualifiers::OCL_Autoreleasing: 8772 break; 8773 8774 case Qualifiers::OCL_Weak: 8775 case Qualifiers::OCL_Strong: 8776 getCurFunction()->setHasBranchProtectedScope(); 8777 break; 8778 } 8779 } 8780 8781 // Warn about externally-visible variables being defined without a 8782 // prior declaration. We only want to do this for global 8783 // declarations, but we also specifically need to avoid doing it for 8784 // class members because the linkage of an anonymous class can 8785 // change if it's later given a typedef name. 8786 if (var->isThisDeclarationADefinition() && 8787 var->getDeclContext()->getRedeclContext()->isFileContext() && 8788 var->isExternallyVisible() && var->hasLinkage() && 8789 getDiagnostics().getDiagnosticLevel( 8790 diag::warn_missing_variable_declarations, 8791 var->getLocation())) { 8792 // Find a previous declaration that's not a definition. 8793 VarDecl *prev = var->getPreviousDecl(); 8794 while (prev && prev->isThisDeclarationADefinition()) 8795 prev = prev->getPreviousDecl(); 8796 8797 if (!prev) 8798 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8799 } 8800 8801 if (var->getTLSKind() == VarDecl::TLS_Static && 8802 var->getType().isDestructedType()) { 8803 // GNU C++98 edits for __thread, [basic.start.term]p3: 8804 // The type of an object with thread storage duration shall not 8805 // have a non-trivial destructor. 8806 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8807 if (getLangOpts().CPlusPlus11) 8808 Diag(var->getLocation(), diag::note_use_thread_local); 8809 } 8810 8811 // All the following checks are C++ only. 8812 if (!getLangOpts().CPlusPlus) return; 8813 8814 QualType type = var->getType(); 8815 if (type->isDependentType()) return; 8816 8817 // __block variables might require us to capture a copy-initializer. 8818 if (var->hasAttr<BlocksAttr>()) { 8819 // It's currently invalid to ever have a __block variable with an 8820 // array type; should we diagnose that here? 8821 8822 // Regardless, we don't want to ignore array nesting when 8823 // constructing this copy. 8824 if (type->isStructureOrClassType()) { 8825 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8826 SourceLocation poi = var->getLocation(); 8827 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8828 ExprResult result 8829 = PerformMoveOrCopyInitialization( 8830 InitializedEntity::InitializeBlock(poi, type, false), 8831 var, var->getType(), varRef, /*AllowNRVO=*/true); 8832 if (!result.isInvalid()) { 8833 result = MaybeCreateExprWithCleanups(result); 8834 Expr *init = result.takeAs<Expr>(); 8835 Context.setBlockVarCopyInits(var, init); 8836 } 8837 } 8838 } 8839 8840 Expr *Init = var->getInit(); 8841 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8842 QualType baseType = Context.getBaseElementType(type); 8843 8844 if (!var->getDeclContext()->isDependentContext() && 8845 Init && !Init->isValueDependent()) { 8846 if (IsGlobal && !var->isConstexpr() && 8847 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8848 var->getLocation()) 8849 != DiagnosticsEngine::Ignored) { 8850 // Warn about globals which don't have a constant initializer. Don't 8851 // warn about globals with a non-trivial destructor because we already 8852 // warned about them. 8853 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8854 if (!(RD && !RD->hasTrivialDestructor()) && 8855 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8856 Diag(var->getLocation(), diag::warn_global_constructor) 8857 << Init->getSourceRange(); 8858 } 8859 8860 if (var->isConstexpr()) { 8861 SmallVector<PartialDiagnosticAt, 8> Notes; 8862 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8863 SourceLocation DiagLoc = var->getLocation(); 8864 // If the note doesn't add any useful information other than a source 8865 // location, fold it into the primary diagnostic. 8866 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 8867 diag::note_invalid_subexpr_in_const_expr) { 8868 DiagLoc = Notes[0].first; 8869 Notes.clear(); 8870 } 8871 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 8872 << var << Init->getSourceRange(); 8873 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 8874 Diag(Notes[I].first, Notes[I].second); 8875 } 8876 } else if (var->isUsableInConstantExpressions(Context)) { 8877 // Check whether the initializer of a const variable of integral or 8878 // enumeration type is an ICE now, since we can't tell whether it was 8879 // initialized by a constant expression if we check later. 8880 var->checkInitIsICE(); 8881 } 8882 } 8883 8884 // Require the destructor. 8885 if (const RecordType *recordType = baseType->getAs<RecordType>()) 8886 FinalizeVarWithDestructor(var, recordType); 8887 } 8888 8889 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 8890 /// any semantic actions necessary after any initializer has been attached. 8891 void 8892 Sema::FinalizeDeclaration(Decl *ThisDecl) { 8893 // Note that we are no longer parsing the initializer for this declaration. 8894 ParsingInitForAutoVars.erase(ThisDecl); 8895 8896 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 8897 if (!VD) 8898 return; 8899 8900 checkAttributesAfterMerging(*this, *VD); 8901 8902 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 8903 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 8904 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 8905 VD->dropAttr<UsedAttr>(); 8906 } 8907 } 8908 8909 if (!VD->isInvalidDecl() && 8910 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 8911 if (const VarDecl *Def = VD->getDefinition()) { 8912 if (Def->hasAttr<AliasAttr>()) { 8913 Diag(VD->getLocation(), diag::err_tentative_after_alias) 8914 << VD->getDeclName(); 8915 Diag(Def->getLocation(), diag::note_previous_definition); 8916 VD->setInvalidDecl(); 8917 } 8918 } 8919 } 8920 8921 const DeclContext *DC = VD->getDeclContext(); 8922 // If there's a #pragma GCC visibility in scope, and this isn't a class 8923 // member, set the visibility of this variable. 8924 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 8925 AddPushedVisibilityAttribute(VD); 8926 8927 if (VD->isFileVarDecl()) 8928 MarkUnusedFileScopedDecl(VD); 8929 8930 // Now we have parsed the initializer and can update the table of magic 8931 // tag values. 8932 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 8933 !VD->getType()->isIntegralOrEnumerationType()) 8934 return; 8935 8936 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 8937 const Expr *MagicValueExpr = VD->getInit(); 8938 if (!MagicValueExpr) { 8939 continue; 8940 } 8941 llvm::APSInt MagicValueInt; 8942 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 8943 Diag(I->getRange().getBegin(), 8944 diag::err_type_tag_for_datatype_not_ice) 8945 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8946 continue; 8947 } 8948 if (MagicValueInt.getActiveBits() > 64) { 8949 Diag(I->getRange().getBegin(), 8950 diag::err_type_tag_for_datatype_too_large) 8951 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 8952 continue; 8953 } 8954 uint64_t MagicValue = MagicValueInt.getZExtValue(); 8955 RegisterTypeTagForDatatype(I->getArgumentKind(), 8956 MagicValue, 8957 I->getMatchingCType(), 8958 I->getLayoutCompatible(), 8959 I->getMustBeNull()); 8960 } 8961 } 8962 8963 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8964 ArrayRef<Decl *> Group) { 8965 SmallVector<Decl*, 8> Decls; 8966 8967 if (DS.isTypeSpecOwned()) 8968 Decls.push_back(DS.getRepAsDecl()); 8969 8970 DeclaratorDecl *FirstDeclaratorInGroup = 0; 8971 for (unsigned i = 0, e = Group.size(); i != e; ++i) 8972 if (Decl *D = Group[i]) { 8973 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 8974 if (!FirstDeclaratorInGroup) 8975 FirstDeclaratorInGroup = DD; 8976 Decls.push_back(D); 8977 } 8978 8979 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 8980 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 8981 HandleTagNumbering(*this, Tag, S); 8982 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 8983 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 8984 } 8985 } 8986 8987 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 8988 } 8989 8990 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 8991 /// group, performing any necessary semantic checking. 8992 Sema::DeclGroupPtrTy 8993 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 8994 bool TypeMayContainAuto) { 8995 // C++0x [dcl.spec.auto]p7: 8996 // If the type deduced for the template parameter U is not the same in each 8997 // deduction, the program is ill-formed. 8998 // FIXME: When initializer-list support is added, a distinction is needed 8999 // between the deduced type U and the deduced type which 'auto' stands for. 9000 // auto a = 0, b = { 1, 2, 3 }; 9001 // is legal because the deduced type U is 'int' in both cases. 9002 if (TypeMayContainAuto && Group.size() > 1) { 9003 QualType Deduced; 9004 CanQualType DeducedCanon; 9005 VarDecl *DeducedDecl = 0; 9006 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9007 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9008 AutoType *AT = D->getType()->getContainedAutoType(); 9009 // Don't reissue diagnostics when instantiating a template. 9010 if (AT && D->isInvalidDecl()) 9011 break; 9012 QualType U = AT ? AT->getDeducedType() : QualType(); 9013 if (!U.isNull()) { 9014 CanQualType UCanon = Context.getCanonicalType(U); 9015 if (Deduced.isNull()) { 9016 Deduced = U; 9017 DeducedCanon = UCanon; 9018 DeducedDecl = D; 9019 } else if (DeducedCanon != UCanon) { 9020 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9021 diag::err_auto_different_deductions) 9022 << (AT->isDecltypeAuto() ? 1 : 0) 9023 << Deduced << DeducedDecl->getDeclName() 9024 << U << D->getDeclName() 9025 << DeducedDecl->getInit()->getSourceRange() 9026 << D->getInit()->getSourceRange(); 9027 D->setInvalidDecl(); 9028 break; 9029 } 9030 } 9031 } 9032 } 9033 } 9034 9035 ActOnDocumentableDecls(Group); 9036 9037 return DeclGroupPtrTy::make( 9038 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9039 } 9040 9041 void Sema::ActOnDocumentableDecl(Decl *D) { 9042 ActOnDocumentableDecls(D); 9043 } 9044 9045 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9046 // Don't parse the comment if Doxygen diagnostics are ignored. 9047 if (Group.empty() || !Group[0]) 9048 return; 9049 9050 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9051 Group[0]->getLocation()) 9052 == DiagnosticsEngine::Ignored) 9053 return; 9054 9055 if (Group.size() >= 2) { 9056 // This is a decl group. Normally it will contain only declarations 9057 // produced from declarator list. But in case we have any definitions or 9058 // additional declaration references: 9059 // 'typedef struct S {} S;' 9060 // 'typedef struct S *S;' 9061 // 'struct S *pS;' 9062 // FinalizeDeclaratorGroup adds these as separate declarations. 9063 Decl *MaybeTagDecl = Group[0]; 9064 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9065 Group = Group.slice(1); 9066 } 9067 } 9068 9069 // See if there are any new comments that are not attached to a decl. 9070 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9071 if (!Comments.empty() && 9072 !Comments.back()->isAttached()) { 9073 // There is at least one comment that not attached to a decl. 9074 // Maybe it should be attached to one of these decls? 9075 // 9076 // Note that this way we pick up not only comments that precede the 9077 // declaration, but also comments that *follow* the declaration -- thanks to 9078 // the lookahead in the lexer: we've consumed the semicolon and looked 9079 // ahead through comments. 9080 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9081 Context.getCommentForDecl(Group[i], &PP); 9082 } 9083 } 9084 9085 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9086 /// to introduce parameters into function prototype scope. 9087 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9088 const DeclSpec &DS = D.getDeclSpec(); 9089 9090 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9091 9092 // C++03 [dcl.stc]p2 also permits 'auto'. 9093 VarDecl::StorageClass StorageClass = SC_None; 9094 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9095 StorageClass = SC_Register; 9096 } else if (getLangOpts().CPlusPlus && 9097 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9098 StorageClass = SC_Auto; 9099 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9100 Diag(DS.getStorageClassSpecLoc(), 9101 diag::err_invalid_storage_class_in_func_decl); 9102 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9103 } 9104 9105 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9106 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9107 << DeclSpec::getSpecifierName(TSCS); 9108 if (DS.isConstexprSpecified()) 9109 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9110 << 0; 9111 9112 DiagnoseFunctionSpecifiers(DS); 9113 9114 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9115 QualType parmDeclType = TInfo->getType(); 9116 9117 if (getLangOpts().CPlusPlus) { 9118 // Check that there are no default arguments inside the type of this 9119 // parameter. 9120 CheckExtraCXXDefaultArguments(D); 9121 9122 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9123 if (D.getCXXScopeSpec().isSet()) { 9124 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9125 << D.getCXXScopeSpec().getRange(); 9126 D.getCXXScopeSpec().clear(); 9127 } 9128 } 9129 9130 // Ensure we have a valid name 9131 IdentifierInfo *II = 0; 9132 if (D.hasName()) { 9133 II = D.getIdentifier(); 9134 if (!II) { 9135 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9136 << GetNameForDeclarator(D).getName(); 9137 D.setInvalidType(true); 9138 } 9139 } 9140 9141 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9142 if (II) { 9143 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9144 ForRedeclaration); 9145 LookupName(R, S); 9146 if (R.isSingleResult()) { 9147 NamedDecl *PrevDecl = R.getFoundDecl(); 9148 if (PrevDecl->isTemplateParameter()) { 9149 // Maybe we will complain about the shadowed template parameter. 9150 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9151 // Just pretend that we didn't see the previous declaration. 9152 PrevDecl = 0; 9153 } else if (S->isDeclScope(PrevDecl)) { 9154 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9155 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9156 9157 // Recover by removing the name 9158 II = 0; 9159 D.SetIdentifier(0, D.getIdentifierLoc()); 9160 D.setInvalidType(true); 9161 } 9162 } 9163 } 9164 9165 // Temporarily put parameter variables in the translation unit, not 9166 // the enclosing context. This prevents them from accidentally 9167 // looking like class members in C++. 9168 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9169 D.getLocStart(), 9170 D.getIdentifierLoc(), II, 9171 parmDeclType, TInfo, 9172 StorageClass); 9173 9174 if (D.isInvalidType()) 9175 New->setInvalidDecl(); 9176 9177 assert(S->isFunctionPrototypeScope()); 9178 assert(S->getFunctionPrototypeDepth() >= 1); 9179 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9180 S->getNextFunctionPrototypeIndex()); 9181 9182 // Add the parameter declaration into this scope. 9183 S->AddDecl(New); 9184 if (II) 9185 IdResolver.AddDecl(New); 9186 9187 ProcessDeclAttributes(S, New, D); 9188 9189 if (D.getDeclSpec().isModulePrivateSpecified()) 9190 Diag(New->getLocation(), diag::err_module_private_local) 9191 << 1 << New->getDeclName() 9192 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9193 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9194 9195 if (New->hasAttr<BlocksAttr>()) { 9196 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9197 } 9198 return New; 9199 } 9200 9201 /// \brief Synthesizes a variable for a parameter arising from a 9202 /// typedef. 9203 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9204 SourceLocation Loc, 9205 QualType T) { 9206 /* FIXME: setting StartLoc == Loc. 9207 Would it be worth to modify callers so as to provide proper source 9208 location for the unnamed parameters, embedding the parameter's type? */ 9209 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9210 T, Context.getTrivialTypeSourceInfo(T, Loc), 9211 SC_None, 0); 9212 Param->setImplicit(); 9213 return Param; 9214 } 9215 9216 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9217 ParmVarDecl * const *ParamEnd) { 9218 // Don't diagnose unused-parameter errors in template instantiations; we 9219 // will already have done so in the template itself. 9220 if (!ActiveTemplateInstantiations.empty()) 9221 return; 9222 9223 for (; Param != ParamEnd; ++Param) { 9224 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9225 !(*Param)->hasAttr<UnusedAttr>()) { 9226 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9227 << (*Param)->getDeclName(); 9228 } 9229 } 9230 } 9231 9232 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9233 ParmVarDecl * const *ParamEnd, 9234 QualType ReturnTy, 9235 NamedDecl *D) { 9236 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9237 return; 9238 9239 // Warn if the return value is pass-by-value and larger than the specified 9240 // threshold. 9241 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9242 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9243 if (Size > LangOpts.NumLargeByValueCopy) 9244 Diag(D->getLocation(), diag::warn_return_value_size) 9245 << D->getDeclName() << Size; 9246 } 9247 9248 // Warn if any parameter is pass-by-value and larger than the specified 9249 // threshold. 9250 for (; Param != ParamEnd; ++Param) { 9251 QualType T = (*Param)->getType(); 9252 if (T->isDependentType() || !T.isPODType(Context)) 9253 continue; 9254 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9255 if (Size > LangOpts.NumLargeByValueCopy) 9256 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9257 << (*Param)->getDeclName() << Size; 9258 } 9259 } 9260 9261 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9262 SourceLocation NameLoc, IdentifierInfo *Name, 9263 QualType T, TypeSourceInfo *TSInfo, 9264 VarDecl::StorageClass StorageClass) { 9265 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9266 if (getLangOpts().ObjCAutoRefCount && 9267 T.getObjCLifetime() == Qualifiers::OCL_None && 9268 T->isObjCLifetimeType()) { 9269 9270 Qualifiers::ObjCLifetime lifetime; 9271 9272 // Special cases for arrays: 9273 // - if it's const, use __unsafe_unretained 9274 // - otherwise, it's an error 9275 if (T->isArrayType()) { 9276 if (!T.isConstQualified()) { 9277 DelayedDiagnostics.add( 9278 sema::DelayedDiagnostic::makeForbiddenType( 9279 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9280 } 9281 lifetime = Qualifiers::OCL_ExplicitNone; 9282 } else { 9283 lifetime = T->getObjCARCImplicitLifetime(); 9284 } 9285 T = Context.getLifetimeQualifiedType(T, lifetime); 9286 } 9287 9288 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9289 Context.getAdjustedParameterType(T), 9290 TSInfo, 9291 StorageClass, 0); 9292 9293 // Parameters can not be abstract class types. 9294 // For record types, this is done by the AbstractClassUsageDiagnoser once 9295 // the class has been completely parsed. 9296 if (!CurContext->isRecord() && 9297 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9298 AbstractParamType)) 9299 New->setInvalidDecl(); 9300 9301 // Parameter declarators cannot be interface types. All ObjC objects are 9302 // passed by reference. 9303 if (T->isObjCObjectType()) { 9304 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9305 Diag(NameLoc, 9306 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9307 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9308 T = Context.getObjCObjectPointerType(T); 9309 New->setType(T); 9310 } 9311 9312 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9313 // duration shall not be qualified by an address-space qualifier." 9314 // Since all parameters have automatic store duration, they can not have 9315 // an address space. 9316 if (T.getAddressSpace() != 0) { 9317 Diag(NameLoc, diag::err_arg_with_address_space); 9318 New->setInvalidDecl(); 9319 } 9320 9321 return New; 9322 } 9323 9324 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9325 SourceLocation LocAfterDecls) { 9326 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9327 9328 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9329 // for a K&R function. 9330 if (!FTI.hasPrototype) { 9331 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 9332 --i; 9333 if (FTI.Params[i].Param == 0) { 9334 SmallString<256> Code; 9335 llvm::raw_svector_ostream(Code) 9336 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 9337 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 9338 << FTI.Params[i].Ident 9339 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9340 9341 // Implicitly declare the argument as type 'int' for lack of a better 9342 // type. 9343 AttributeFactory attrs; 9344 DeclSpec DS(attrs); 9345 const char* PrevSpec; // unused 9346 unsigned DiagID; // unused 9347 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 9348 DiagID, Context.getPrintingPolicy()); 9349 // Use the identifier location for the type source range. 9350 DS.SetRangeStart(FTI.Params[i].IdentLoc); 9351 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 9352 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9353 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 9354 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 9355 } 9356 } 9357 } 9358 } 9359 9360 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9361 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9362 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9363 Scope *ParentScope = FnBodyScope->getParent(); 9364 9365 D.setFunctionDefinitionKind(FDK_Definition); 9366 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9367 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9368 } 9369 9370 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9371 const FunctionDecl*& PossibleZeroParamPrototype) { 9372 // Don't warn about invalid declarations. 9373 if (FD->isInvalidDecl()) 9374 return false; 9375 9376 // Or declarations that aren't global. 9377 if (!FD->isGlobal()) 9378 return false; 9379 9380 // Don't warn about C++ member functions. 9381 if (isa<CXXMethodDecl>(FD)) 9382 return false; 9383 9384 // Don't warn about 'main'. 9385 if (FD->isMain()) 9386 return false; 9387 9388 // Don't warn about inline functions. 9389 if (FD->isInlined()) 9390 return false; 9391 9392 // Don't warn about function templates. 9393 if (FD->getDescribedFunctionTemplate()) 9394 return false; 9395 9396 // Don't warn about function template specializations. 9397 if (FD->isFunctionTemplateSpecialization()) 9398 return false; 9399 9400 // Don't warn for OpenCL kernels. 9401 if (FD->hasAttr<OpenCLKernelAttr>()) 9402 return false; 9403 9404 bool MissingPrototype = true; 9405 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9406 Prev; Prev = Prev->getPreviousDecl()) { 9407 // Ignore any declarations that occur in function or method 9408 // scope, because they aren't visible from the header. 9409 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9410 continue; 9411 9412 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9413 if (FD->getNumParams() == 0) 9414 PossibleZeroParamPrototype = Prev; 9415 break; 9416 } 9417 9418 return MissingPrototype; 9419 } 9420 9421 void 9422 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9423 const FunctionDecl *EffectiveDefinition) { 9424 // Don't complain if we're in GNU89 mode and the previous definition 9425 // was an extern inline function. 9426 const FunctionDecl *Definition = EffectiveDefinition; 9427 if (!Definition) 9428 if (!FD->isDefined(Definition)) 9429 return; 9430 9431 if (canRedefineFunction(Definition, getLangOpts())) 9432 return; 9433 9434 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9435 Definition->getStorageClass() == SC_Extern) 9436 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9437 << FD->getDeclName() << getLangOpts().CPlusPlus; 9438 else 9439 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9440 9441 Diag(Definition->getLocation(), diag::note_previous_definition); 9442 FD->setInvalidDecl(); 9443 } 9444 9445 9446 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9447 Sema &S) { 9448 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9449 9450 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9451 LSI->CallOperator = CallOperator; 9452 LSI->Lambda = LambdaClass; 9453 LSI->ReturnType = CallOperator->getReturnType(); 9454 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9455 9456 if (LCD == LCD_None) 9457 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9458 else if (LCD == LCD_ByCopy) 9459 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9460 else if (LCD == LCD_ByRef) 9461 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9462 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9463 9464 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9465 LSI->Mutable = !CallOperator->isConst(); 9466 9467 // Add the captures to the LSI so they can be noted as already 9468 // captured within tryCaptureVar. 9469 for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(), 9470 CEnd = LambdaClass->captures_end(); C != CEnd; ++C) { 9471 if (C->capturesVariable()) { 9472 VarDecl *VD = C->getCapturedVar(); 9473 if (VD->isInitCapture()) 9474 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9475 QualType CaptureType = VD->getType(); 9476 const bool ByRef = C->getCaptureKind() == LCK_ByRef; 9477 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9478 /*RefersToEnclosingLocal*/true, C->getLocation(), 9479 /*EllipsisLoc*/C->isPackExpansion() 9480 ? C->getEllipsisLoc() : SourceLocation(), 9481 CaptureType, /*Expr*/ 0); 9482 9483 } else if (C->capturesThis()) { 9484 LSI->addThisCapture(/*Nested*/ false, C->getLocation(), 9485 S.getCurrentThisType(), /*Expr*/ 0); 9486 } 9487 } 9488 } 9489 9490 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9491 // Clear the last template instantiation error context. 9492 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9493 9494 if (!D) 9495 return D; 9496 FunctionDecl *FD = 0; 9497 9498 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9499 FD = FunTmpl->getTemplatedDecl(); 9500 else 9501 FD = cast<FunctionDecl>(D); 9502 // If we are instantiating a generic lambda call operator, push 9503 // a LambdaScopeInfo onto the function stack. But use the information 9504 // that's already been calculated (ActOnLambdaExpr) to prime the current 9505 // LambdaScopeInfo. 9506 // When the template operator is being specialized, the LambdaScopeInfo, 9507 // has to be properly restored so that tryCaptureVariable doesn't try 9508 // and capture any new variables. In addition when calculating potential 9509 // captures during transformation of nested lambdas, it is necessary to 9510 // have the LSI properly restored. 9511 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9512 assert(ActiveTemplateInstantiations.size() && 9513 "There should be an active template instantiation on the stack " 9514 "when instantiating a generic lambda!"); 9515 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9516 } 9517 else 9518 // Enter a new function scope 9519 PushFunctionScope(); 9520 9521 // See if this is a redefinition. 9522 if (!FD->isLateTemplateParsed()) 9523 CheckForFunctionRedefinition(FD); 9524 9525 // Builtin functions cannot be defined. 9526 if (unsigned BuiltinID = FD->getBuiltinID()) { 9527 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9528 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9529 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9530 FD->setInvalidDecl(); 9531 } 9532 } 9533 9534 // The return type of a function definition must be complete 9535 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9536 QualType ResultType = FD->getReturnType(); 9537 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9538 !FD->isInvalidDecl() && 9539 RequireCompleteType(FD->getLocation(), ResultType, 9540 diag::err_func_def_incomplete_result)) 9541 FD->setInvalidDecl(); 9542 9543 // GNU warning -Wmissing-prototypes: 9544 // Warn if a global function is defined without a previous 9545 // prototype declaration. This warning is issued even if the 9546 // definition itself provides a prototype. The aim is to detect 9547 // global functions that fail to be declared in header files. 9548 const FunctionDecl *PossibleZeroParamPrototype = 0; 9549 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9550 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9551 9552 if (PossibleZeroParamPrototype) { 9553 // We found a declaration that is not a prototype, 9554 // but that could be a zero-parameter prototype 9555 if (TypeSourceInfo *TI = 9556 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9557 TypeLoc TL = TI->getTypeLoc(); 9558 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9559 Diag(PossibleZeroParamPrototype->getLocation(), 9560 diag::note_declaration_not_a_prototype) 9561 << PossibleZeroParamPrototype 9562 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9563 } 9564 } 9565 } 9566 9567 if (FnBodyScope) 9568 PushDeclContext(FnBodyScope, FD); 9569 9570 // Check the validity of our function parameters 9571 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9572 /*CheckParameterNames=*/true); 9573 9574 // Introduce our parameters into the function scope 9575 for (auto Param : FD->params()) { 9576 Param->setOwningFunction(FD); 9577 9578 // If this has an identifier, add it to the scope stack. 9579 if (Param->getIdentifier() && FnBodyScope) { 9580 CheckShadow(FnBodyScope, Param); 9581 9582 PushOnScopeChains(Param, FnBodyScope); 9583 } 9584 } 9585 9586 // If we had any tags defined in the function prototype, 9587 // introduce them into the function scope. 9588 if (FnBodyScope) { 9589 for (ArrayRef<NamedDecl *>::iterator 9590 I = FD->getDeclsInPrototypeScope().begin(), 9591 E = FD->getDeclsInPrototypeScope().end(); 9592 I != E; ++I) { 9593 NamedDecl *D = *I; 9594 9595 // Some of these decls (like enums) may have been pinned to the translation unit 9596 // for lack of a real context earlier. If so, remove from the translation unit 9597 // and reattach to the current context. 9598 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9599 // Is the decl actually in the context? 9600 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 9601 if (DI == D) { 9602 Context.getTranslationUnitDecl()->removeDecl(D); 9603 break; 9604 } 9605 } 9606 // Either way, reassign the lexical decl context to our FunctionDecl. 9607 D->setLexicalDeclContext(CurContext); 9608 } 9609 9610 // If the decl has a non-null name, make accessible in the current scope. 9611 if (!D->getName().empty()) 9612 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9613 9614 // Similarly, dive into enums and fish their constants out, making them 9615 // accessible in this scope. 9616 if (auto *ED = dyn_cast<EnumDecl>(D)) { 9617 for (auto *EI : ED->enumerators()) 9618 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 9619 } 9620 } 9621 } 9622 9623 // Ensure that the function's exception specification is instantiated. 9624 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9625 ResolveExceptionSpec(D->getLocation(), FPT); 9626 9627 // Checking attributes of current function definition 9628 // dllimport attribute. 9629 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9630 if (DA && (!FD->hasAttr<DLLExportAttr>())) { 9631 // dllimport attribute cannot be directly applied to definition. 9632 // Microsoft accepts dllimport for functions defined within class scope. 9633 if (!DA->isInherited() && 9634 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9635 Diag(FD->getLocation(), 9636 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9637 << DA; 9638 FD->setInvalidDecl(); 9639 return D; 9640 } 9641 9642 // Visual C++ appears to not think this is an issue, so only issue 9643 // a warning when Microsoft extensions are disabled. 9644 if (!LangOpts.MicrosoftExt) { 9645 // If a symbol previously declared dllimport is later defined, the 9646 // attribute is ignored in subsequent references, and a warning is 9647 // emitted. 9648 Diag(FD->getLocation(), 9649 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 9650 << FD << DA; 9651 } 9652 } 9653 // We want to attach documentation to original Decl (which might be 9654 // a function template). 9655 ActOnDocumentableDecl(D); 9656 return D; 9657 } 9658 9659 /// \brief Given the set of return statements within a function body, 9660 /// compute the variables that are subject to the named return value 9661 /// optimization. 9662 /// 9663 /// Each of the variables that is subject to the named return value 9664 /// optimization will be marked as NRVO variables in the AST, and any 9665 /// return statement that has a marked NRVO variable as its NRVO candidate can 9666 /// use the named return value optimization. 9667 /// 9668 /// This function applies a very simplistic algorithm for NRVO: if every return 9669 /// statement in the function has the same NRVO candidate, that candidate is 9670 /// the NRVO variable. 9671 /// 9672 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9673 /// statements and the lifetimes of the NRVO candidates. We should be able to 9674 /// find a maximal set of NRVO variables. 9675 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9676 ReturnStmt **Returns = Scope->Returns.data(); 9677 9678 const VarDecl *NRVOCandidate = 0; 9679 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9680 if (!Returns[I]->getNRVOCandidate()) 9681 return; 9682 9683 if (!NRVOCandidate) 9684 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9685 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9686 return; 9687 } 9688 9689 if (NRVOCandidate) 9690 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9691 } 9692 9693 bool Sema::canSkipFunctionBody(Decl *D) { 9694 // We cannot skip the body of a function (or function template) which is 9695 // constexpr, since we may need to evaluate its body in order to parse the 9696 // rest of the file. 9697 // We cannot skip the body of a function with an undeduced return type, 9698 // because any callers of that function need to know the type. 9699 if (const FunctionDecl *FD = D->getAsFunction()) 9700 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9701 return false; 9702 return Consumer.shouldSkipFunctionBody(D); 9703 } 9704 9705 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9706 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9707 FD->setHasSkippedBody(); 9708 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9709 MD->setHasSkippedBody(); 9710 return ActOnFinishFunctionBody(Decl, 0); 9711 } 9712 9713 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9714 return ActOnFinishFunctionBody(D, BodyArg, false); 9715 } 9716 9717 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9718 bool IsInstantiation) { 9719 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0; 9720 9721 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9722 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9723 9724 if (FD) { 9725 FD->setBody(Body); 9726 9727 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9728 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 9729 // If the function has a deduced result type but contains no 'return' 9730 // statements, the result type as written must be exactly 'auto', and 9731 // the deduced result type is 'void'. 9732 if (!FD->getReturnType()->getAs<AutoType>()) { 9733 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9734 << FD->getReturnType(); 9735 FD->setInvalidDecl(); 9736 } else { 9737 // Substitute 'void' for the 'auto' in the type. 9738 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9739 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 9740 Context.adjustDeducedFunctionResultType( 9741 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9742 } 9743 } 9744 9745 // The only way to be included in UndefinedButUsed is if there is an 9746 // ODR use before the definition. Avoid the expensive map lookup if this 9747 // is the first declaration. 9748 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9749 if (!FD->isExternallyVisible()) 9750 UndefinedButUsed.erase(FD); 9751 else if (FD->isInlined() && 9752 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9753 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9754 UndefinedButUsed.erase(FD); 9755 } 9756 9757 // If the function implicitly returns zero (like 'main') or is naked, 9758 // don't complain about missing return statements. 9759 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9760 WP.disableCheckFallThrough(); 9761 9762 // MSVC permits the use of pure specifier (=0) on function definition, 9763 // defined at class scope, warn about this non-standard construct. 9764 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9765 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9766 9767 if (!FD->isInvalidDecl()) { 9768 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9769 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9770 FD->getReturnType(), FD); 9771 9772 // If this is a constructor, we need a vtable. 9773 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9774 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9775 9776 // Try to apply the named return value optimization. We have to check 9777 // if we can do this here because lambdas keep return statements around 9778 // to deduce an implicit return type. 9779 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 9780 !FD->isDependentContext()) 9781 computeNRVO(Body, getCurFunction()); 9782 } 9783 9784 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9785 "Function parsing confused"); 9786 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9787 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9788 MD->setBody(Body); 9789 if (!MD->isInvalidDecl()) { 9790 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9791 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9792 MD->getReturnType(), MD); 9793 9794 if (Body) 9795 computeNRVO(Body, getCurFunction()); 9796 } 9797 if (getCurFunction()->ObjCShouldCallSuper) { 9798 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9799 << MD->getSelector().getAsString(); 9800 getCurFunction()->ObjCShouldCallSuper = false; 9801 } 9802 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 9803 const ObjCMethodDecl *InitMethod = 0; 9804 bool isDesignated = 9805 MD->isDesignatedInitializerForTheInterface(&InitMethod); 9806 assert(isDesignated && InitMethod); 9807 (void)isDesignated; 9808 Diag(MD->getLocation(), 9809 diag::warn_objc_designated_init_missing_super_call); 9810 Diag(InitMethod->getLocation(), 9811 diag::note_objc_designated_init_marked_here); 9812 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 9813 } 9814 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 9815 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 9816 getCurFunction()->ObjCWarnForNoInitDelegation = false; 9817 } 9818 } else { 9819 return 0; 9820 } 9821 9822 assert(!getCurFunction()->ObjCShouldCallSuper && 9823 "This should only be set for ObjC methods, which should have been " 9824 "handled in the block above."); 9825 9826 // Verify and clean out per-function state. 9827 if (Body) { 9828 // C++ constructors that have function-try-blocks can't have return 9829 // statements in the handlers of that block. (C++ [except.handle]p14) 9830 // Verify this. 9831 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 9832 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 9833 9834 // Verify that gotos and switch cases don't jump into scopes illegally. 9835 if (getCurFunction()->NeedsScopeChecking() && 9836 !dcl->isInvalidDecl() && 9837 !hasAnyUnrecoverableErrorsInThisFunction() && 9838 !PP.isCodeCompletionEnabled()) 9839 DiagnoseInvalidJumps(Body); 9840 9841 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 9842 if (!Destructor->getParent()->isDependentType()) 9843 CheckDestructor(Destructor); 9844 9845 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9846 Destructor->getParent()); 9847 } 9848 9849 // If any errors have occurred, clear out any temporaries that may have 9850 // been leftover. This ensures that these temporaries won't be picked up for 9851 // deletion in some later function. 9852 if (PP.getDiagnostics().hasErrorOccurred() || 9853 PP.getDiagnostics().getSuppressAllDiagnostics()) { 9854 DiscardCleanupsInEvaluationContext(); 9855 } 9856 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 9857 !isa<FunctionTemplateDecl>(dcl)) { 9858 // Since the body is valid, issue any analysis-based warnings that are 9859 // enabled. 9860 ActivePolicy = &WP; 9861 } 9862 9863 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 9864 (!CheckConstexprFunctionDecl(FD) || 9865 !CheckConstexprFunctionBody(FD, Body))) 9866 FD->setInvalidDecl(); 9867 9868 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 9869 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 9870 assert(MaybeODRUseExprs.empty() && 9871 "Leftover expressions for odr-use checking"); 9872 } 9873 9874 if (!IsInstantiation) 9875 PopDeclContext(); 9876 9877 PopFunctionScopeInfo(ActivePolicy, dcl); 9878 // If any errors have occurred, clear out any temporaries that may have 9879 // been leftover. This ensures that these temporaries won't be picked up for 9880 // deletion in some later function. 9881 if (getDiagnostics().hasErrorOccurred()) { 9882 DiscardCleanupsInEvaluationContext(); 9883 } 9884 9885 return dcl; 9886 } 9887 9888 9889 /// When we finish delayed parsing of an attribute, we must attach it to the 9890 /// relevant Decl. 9891 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 9892 ParsedAttributes &Attrs) { 9893 // Always attach attributes to the underlying decl. 9894 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9895 D = TD->getTemplatedDecl(); 9896 ProcessDeclAttributeList(S, D, Attrs.getList()); 9897 9898 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 9899 if (Method->isStatic()) 9900 checkThisInStaticMemberFunctionAttributes(Method); 9901 } 9902 9903 9904 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 9905 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 9906 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 9907 IdentifierInfo &II, Scope *S) { 9908 // Before we produce a declaration for an implicitly defined 9909 // function, see whether there was a locally-scoped declaration of 9910 // this name as a function or variable. If so, use that 9911 // (non-visible) declaration, and complain about it. 9912 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 9913 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 9914 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 9915 return ExternCPrev; 9916 } 9917 9918 // Extension in C99. Legal in C90, but warn about it. 9919 unsigned diag_id; 9920 if (II.getName().startswith("__builtin_")) 9921 diag_id = diag::warn_builtin_unknown; 9922 else if (getLangOpts().C99) 9923 diag_id = diag::ext_implicit_function_decl; 9924 else 9925 diag_id = diag::warn_implicit_function_decl; 9926 Diag(Loc, diag_id) << &II; 9927 9928 // Because typo correction is expensive, only do it if the implicit 9929 // function declaration is going to be treated as an error. 9930 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 9931 TypoCorrection Corrected; 9932 DeclFilterCCC<FunctionDecl> Validator; 9933 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 9934 LookupOrdinaryName, S, 0, Validator))) 9935 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 9936 /*ErrorRecovery*/false); 9937 } 9938 9939 // Set a Declarator for the implicit definition: int foo(); 9940 const char *Dummy; 9941 AttributeFactory attrFactory; 9942 DeclSpec DS(attrFactory); 9943 unsigned DiagID; 9944 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 9945 Context.getPrintingPolicy()); 9946 (void)Error; // Silence warning. 9947 assert(!Error && "Error setting up implicit decl!"); 9948 SourceLocation NoLoc; 9949 Declarator D(DS, Declarator::BlockContext); 9950 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 9951 /*IsAmbiguous=*/false, 9952 /*RParenLoc=*/NoLoc, 9953 /*ArgInfo=*/0, 9954 /*NumArgs=*/0, 9955 /*EllipsisLoc=*/NoLoc, 9956 /*RParenLoc=*/NoLoc, 9957 /*TypeQuals=*/0, 9958 /*RefQualifierIsLvalueRef=*/true, 9959 /*RefQualifierLoc=*/NoLoc, 9960 /*ConstQualifierLoc=*/NoLoc, 9961 /*VolatileQualifierLoc=*/NoLoc, 9962 /*MutableLoc=*/NoLoc, 9963 EST_None, 9964 /*ESpecLoc=*/NoLoc, 9965 /*Exceptions=*/0, 9966 /*ExceptionRanges=*/0, 9967 /*NumExceptions=*/0, 9968 /*NoexceptExpr=*/0, 9969 Loc, Loc, D), 9970 DS.getAttributes(), 9971 SourceLocation()); 9972 D.SetIdentifier(&II, Loc); 9973 9974 // Insert this function into translation-unit scope. 9975 9976 DeclContext *PrevDC = CurContext; 9977 CurContext = Context.getTranslationUnitDecl(); 9978 9979 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 9980 FD->setImplicit(); 9981 9982 CurContext = PrevDC; 9983 9984 AddKnownFunctionAttributes(FD); 9985 9986 return FD; 9987 } 9988 9989 /// \brief Adds any function attributes that we know a priori based on 9990 /// the declaration of this function. 9991 /// 9992 /// These attributes can apply both to implicitly-declared builtins 9993 /// (like __builtin___printf_chk) or to library-declared functions 9994 /// like NSLog or printf. 9995 /// 9996 /// We need to check for duplicate attributes both here and where user-written 9997 /// attributes are applied to declarations. 9998 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 9999 if (FD->isInvalidDecl()) 10000 return; 10001 10002 // If this is a built-in function, map its builtin attributes to 10003 // actual attributes. 10004 if (unsigned BuiltinID = FD->getBuiltinID()) { 10005 // Handle printf-formatting attributes. 10006 unsigned FormatIdx; 10007 bool HasVAListArg; 10008 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10009 if (!FD->hasAttr<FormatAttr>()) { 10010 const char *fmt = "printf"; 10011 unsigned int NumParams = FD->getNumParams(); 10012 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10013 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10014 fmt = "NSString"; 10015 FD->addAttr(FormatAttr::CreateImplicit(Context, 10016 &Context.Idents.get(fmt), 10017 FormatIdx+1, 10018 HasVAListArg ? 0 : FormatIdx+2, 10019 FD->getLocation())); 10020 } 10021 } 10022 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10023 HasVAListArg)) { 10024 if (!FD->hasAttr<FormatAttr>()) 10025 FD->addAttr(FormatAttr::CreateImplicit(Context, 10026 &Context.Idents.get("scanf"), 10027 FormatIdx+1, 10028 HasVAListArg ? 0 : FormatIdx+2, 10029 FD->getLocation())); 10030 } 10031 10032 // Mark const if we don't care about errno and that is the only 10033 // thing preventing the function from being const. This allows 10034 // IRgen to use LLVM intrinsics for such functions. 10035 if (!getLangOpts().MathErrno && 10036 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10037 if (!FD->hasAttr<ConstAttr>()) 10038 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10039 } 10040 10041 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10042 !FD->hasAttr<ReturnsTwiceAttr>()) 10043 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10044 FD->getLocation())); 10045 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10046 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10047 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10048 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10049 } 10050 10051 IdentifierInfo *Name = FD->getIdentifier(); 10052 if (!Name) 10053 return; 10054 if ((!getLangOpts().CPlusPlus && 10055 FD->getDeclContext()->isTranslationUnit()) || 10056 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10057 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10058 LinkageSpecDecl::lang_c)) { 10059 // Okay: this could be a libc/libm/Objective-C function we know 10060 // about. 10061 } else 10062 return; 10063 10064 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10065 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10066 // target-specific builtins, perhaps? 10067 if (!FD->hasAttr<FormatAttr>()) 10068 FD->addAttr(FormatAttr::CreateImplicit(Context, 10069 &Context.Idents.get("printf"), 2, 10070 Name->isStr("vasprintf") ? 0 : 3, 10071 FD->getLocation())); 10072 } 10073 10074 if (Name->isStr("__CFStringMakeConstantString")) { 10075 // We already have a __builtin___CFStringMakeConstantString, 10076 // but builds that use -fno-constant-cfstrings don't go through that. 10077 if (!FD->hasAttr<FormatArgAttr>()) 10078 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10079 FD->getLocation())); 10080 } 10081 } 10082 10083 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10084 TypeSourceInfo *TInfo) { 10085 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10086 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10087 10088 if (!TInfo) { 10089 assert(D.isInvalidType() && "no declarator info for valid type"); 10090 TInfo = Context.getTrivialTypeSourceInfo(T); 10091 } 10092 10093 // Scope manipulation handled by caller. 10094 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10095 D.getLocStart(), 10096 D.getIdentifierLoc(), 10097 D.getIdentifier(), 10098 TInfo); 10099 10100 // Bail out immediately if we have an invalid declaration. 10101 if (D.isInvalidType()) { 10102 NewTD->setInvalidDecl(); 10103 return NewTD; 10104 } 10105 10106 if (D.getDeclSpec().isModulePrivateSpecified()) { 10107 if (CurContext->isFunctionOrMethod()) 10108 Diag(NewTD->getLocation(), diag::err_module_private_local) 10109 << 2 << NewTD->getDeclName() 10110 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10111 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10112 else 10113 NewTD->setModulePrivate(); 10114 } 10115 10116 // C++ [dcl.typedef]p8: 10117 // If the typedef declaration defines an unnamed class (or 10118 // enum), the first typedef-name declared by the declaration 10119 // to be that class type (or enum type) is used to denote the 10120 // class type (or enum type) for linkage purposes only. 10121 // We need to check whether the type was declared in the declaration. 10122 switch (D.getDeclSpec().getTypeSpecType()) { 10123 case TST_enum: 10124 case TST_struct: 10125 case TST_interface: 10126 case TST_union: 10127 case TST_class: { 10128 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10129 10130 // Do nothing if the tag is not anonymous or already has an 10131 // associated typedef (from an earlier typedef in this decl group). 10132 if (tagFromDeclSpec->getIdentifier()) break; 10133 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10134 10135 // A well-formed anonymous tag must always be a TUK_Definition. 10136 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10137 10138 // The type must match the tag exactly; no qualifiers allowed. 10139 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10140 break; 10141 10142 // If we've already computed linkage for the anonymous tag, then 10143 // adding a typedef name for the anonymous decl can change that 10144 // linkage, which might be a serious problem. Diagnose this as 10145 // unsupported and ignore the typedef name. TODO: we should 10146 // pursue this as a language defect and establish a formal rule 10147 // for how to handle it. 10148 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10149 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10150 10151 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10152 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(), 10153 getLangOpts()); 10154 10155 llvm::SmallString<40> textToInsert; 10156 textToInsert += ' '; 10157 textToInsert += D.getIdentifier()->getName(); 10158 Diag(tagLoc, diag::note_typedef_changes_linkage) 10159 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10160 break; 10161 } 10162 10163 // Otherwise, set this is the anon-decl typedef for the tag. 10164 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10165 break; 10166 } 10167 10168 default: 10169 break; 10170 } 10171 10172 return NewTD; 10173 } 10174 10175 10176 /// \brief Check that this is a valid underlying type for an enum declaration. 10177 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10178 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10179 QualType T = TI->getType(); 10180 10181 if (T->isDependentType()) 10182 return false; 10183 10184 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10185 if (BT->isInteger()) 10186 return false; 10187 10188 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10189 return true; 10190 } 10191 10192 /// Check whether this is a valid redeclaration of a previous enumeration. 10193 /// \return true if the redeclaration was invalid. 10194 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10195 QualType EnumUnderlyingTy, 10196 const EnumDecl *Prev) { 10197 bool IsFixed = !EnumUnderlyingTy.isNull(); 10198 10199 if (IsScoped != Prev->isScoped()) { 10200 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10201 << Prev->isScoped(); 10202 Diag(Prev->getLocation(), diag::note_previous_declaration); 10203 return true; 10204 } 10205 10206 if (IsFixed && Prev->isFixed()) { 10207 if (!EnumUnderlyingTy->isDependentType() && 10208 !Prev->getIntegerType()->isDependentType() && 10209 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10210 Prev->getIntegerType())) { 10211 // TODO: Highlight the underlying type of the redeclaration. 10212 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10213 << EnumUnderlyingTy << Prev->getIntegerType(); 10214 Diag(Prev->getLocation(), diag::note_previous_declaration) 10215 << Prev->getIntegerTypeRange(); 10216 return true; 10217 } 10218 } else if (IsFixed != Prev->isFixed()) { 10219 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10220 << Prev->isFixed(); 10221 Diag(Prev->getLocation(), diag::note_previous_declaration); 10222 return true; 10223 } 10224 10225 return false; 10226 } 10227 10228 /// \brief Get diagnostic %select index for tag kind for 10229 /// redeclaration diagnostic message. 10230 /// WARNING: Indexes apply to particular diagnostics only! 10231 /// 10232 /// \returns diagnostic %select index. 10233 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10234 switch (Tag) { 10235 case TTK_Struct: return 0; 10236 case TTK_Interface: return 1; 10237 case TTK_Class: return 2; 10238 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10239 } 10240 } 10241 10242 /// \brief Determine if tag kind is a class-key compatible with 10243 /// class for redeclaration (class, struct, or __interface). 10244 /// 10245 /// \returns true iff the tag kind is compatible. 10246 static bool isClassCompatTagKind(TagTypeKind Tag) 10247 { 10248 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10249 } 10250 10251 /// \brief Determine whether a tag with a given kind is acceptable 10252 /// as a redeclaration of the given tag declaration. 10253 /// 10254 /// \returns true if the new tag kind is acceptable, false otherwise. 10255 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10256 TagTypeKind NewTag, bool isDefinition, 10257 SourceLocation NewTagLoc, 10258 const IdentifierInfo &Name) { 10259 // C++ [dcl.type.elab]p3: 10260 // The class-key or enum keyword present in the 10261 // elaborated-type-specifier shall agree in kind with the 10262 // declaration to which the name in the elaborated-type-specifier 10263 // refers. This rule also applies to the form of 10264 // elaborated-type-specifier that declares a class-name or 10265 // friend class since it can be construed as referring to the 10266 // definition of the class. Thus, in any 10267 // elaborated-type-specifier, the enum keyword shall be used to 10268 // refer to an enumeration (7.2), the union class-key shall be 10269 // used to refer to a union (clause 9), and either the class or 10270 // struct class-key shall be used to refer to a class (clause 9) 10271 // declared using the class or struct class-key. 10272 TagTypeKind OldTag = Previous->getTagKind(); 10273 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10274 if (OldTag == NewTag) 10275 return true; 10276 10277 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10278 // Warn about the struct/class tag mismatch. 10279 bool isTemplate = false; 10280 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10281 isTemplate = Record->getDescribedClassTemplate(); 10282 10283 if (!ActiveTemplateInstantiations.empty()) { 10284 // In a template instantiation, do not offer fix-its for tag mismatches 10285 // since they usually mess up the template instead of fixing the problem. 10286 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10287 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10288 << getRedeclDiagFromTagKind(OldTag); 10289 return true; 10290 } 10291 10292 if (isDefinition) { 10293 // On definitions, check previous tags and issue a fix-it for each 10294 // one that doesn't match the current tag. 10295 if (Previous->getDefinition()) { 10296 // Don't suggest fix-its for redefinitions. 10297 return true; 10298 } 10299 10300 bool previousMismatch = false; 10301 for (auto I : Previous->redecls()) { 10302 if (I->getTagKind() != NewTag) { 10303 if (!previousMismatch) { 10304 previousMismatch = true; 10305 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10306 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10307 << getRedeclDiagFromTagKind(I->getTagKind()); 10308 } 10309 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10310 << getRedeclDiagFromTagKind(NewTag) 10311 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10312 TypeWithKeyword::getTagTypeKindName(NewTag)); 10313 } 10314 } 10315 return true; 10316 } 10317 10318 // Check for a previous definition. If current tag and definition 10319 // are same type, do nothing. If no definition, but disagree with 10320 // with previous tag type, give a warning, but no fix-it. 10321 const TagDecl *Redecl = Previous->getDefinition() ? 10322 Previous->getDefinition() : Previous; 10323 if (Redecl->getTagKind() == NewTag) { 10324 return true; 10325 } 10326 10327 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10328 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10329 << getRedeclDiagFromTagKind(OldTag); 10330 Diag(Redecl->getLocation(), diag::note_previous_use); 10331 10332 // If there is a previous definition, suggest a fix-it. 10333 if (Previous->getDefinition()) { 10334 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10335 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10336 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10337 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10338 } 10339 10340 return true; 10341 } 10342 return false; 10343 } 10344 10345 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10346 /// former case, Name will be non-null. In the later case, Name will be null. 10347 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10348 /// reference/declaration/definition of a tag. 10349 /// 10350 /// IsTypeSpecifier is true if this is a type-specifier (or 10351 /// trailing-type-specifier) other than one in an alias-declaration. 10352 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10353 SourceLocation KWLoc, CXXScopeSpec &SS, 10354 IdentifierInfo *Name, SourceLocation NameLoc, 10355 AttributeList *Attr, AccessSpecifier AS, 10356 SourceLocation ModulePrivateLoc, 10357 MultiTemplateParamsArg TemplateParameterLists, 10358 bool &OwnedDecl, bool &IsDependent, 10359 SourceLocation ScopedEnumKWLoc, 10360 bool ScopedEnumUsesClassTag, 10361 TypeResult UnderlyingType, 10362 bool IsTypeSpecifier) { 10363 // If this is not a definition, it must have a name. 10364 IdentifierInfo *OrigName = Name; 10365 assert((Name != 0 || TUK == TUK_Definition) && 10366 "Nameless record must be a definition!"); 10367 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10368 10369 OwnedDecl = false; 10370 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10371 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10372 10373 // FIXME: Check explicit specializations more carefully. 10374 bool isExplicitSpecialization = false; 10375 bool Invalid = false; 10376 10377 // We only need to do this matching if we have template parameters 10378 // or a scope specifier, which also conveniently avoids this work 10379 // for non-C++ cases. 10380 if (TemplateParameterLists.size() > 0 || 10381 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10382 if (TemplateParameterList *TemplateParams = 10383 MatchTemplateParametersToScopeSpecifier( 10384 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10385 isExplicitSpecialization, Invalid)) { 10386 if (Kind == TTK_Enum) { 10387 Diag(KWLoc, diag::err_enum_template); 10388 return 0; 10389 } 10390 10391 if (TemplateParams->size() > 0) { 10392 // This is a declaration or definition of a class template (which may 10393 // be a member of another template). 10394 10395 if (Invalid) 10396 return 0; 10397 10398 OwnedDecl = false; 10399 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10400 SS, Name, NameLoc, Attr, 10401 TemplateParams, AS, 10402 ModulePrivateLoc, 10403 TemplateParameterLists.size()-1, 10404 TemplateParameterLists.data()); 10405 return Result.get(); 10406 } else { 10407 // The "template<>" header is extraneous. 10408 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10409 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10410 isExplicitSpecialization = true; 10411 } 10412 } 10413 } 10414 10415 // Figure out the underlying type if this a enum declaration. We need to do 10416 // this early, because it's needed to detect if this is an incompatible 10417 // redeclaration. 10418 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10419 10420 if (Kind == TTK_Enum) { 10421 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10422 // No underlying type explicitly specified, or we failed to parse the 10423 // type, default to int. 10424 EnumUnderlying = Context.IntTy.getTypePtr(); 10425 else if (UnderlyingType.get()) { 10426 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10427 // integral type; any cv-qualification is ignored. 10428 TypeSourceInfo *TI = 0; 10429 GetTypeFromParser(UnderlyingType.get(), &TI); 10430 EnumUnderlying = TI; 10431 10432 if (CheckEnumUnderlyingType(TI)) 10433 // Recover by falling back to int. 10434 EnumUnderlying = Context.IntTy.getTypePtr(); 10435 10436 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10437 UPPC_FixedUnderlyingType)) 10438 EnumUnderlying = Context.IntTy.getTypePtr(); 10439 10440 } else if (getLangOpts().MSVCCompat) 10441 // Microsoft enums are always of int type. 10442 EnumUnderlying = Context.IntTy.getTypePtr(); 10443 } 10444 10445 DeclContext *SearchDC = CurContext; 10446 DeclContext *DC = CurContext; 10447 bool isStdBadAlloc = false; 10448 10449 RedeclarationKind Redecl = ForRedeclaration; 10450 if (TUK == TUK_Friend || TUK == TUK_Reference) 10451 Redecl = NotForRedeclaration; 10452 10453 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10454 bool FriendSawTagOutsideEnclosingNamespace = false; 10455 if (Name && SS.isNotEmpty()) { 10456 // We have a nested-name tag ('struct foo::bar'). 10457 10458 // Check for invalid 'foo::'. 10459 if (SS.isInvalid()) { 10460 Name = 0; 10461 goto CreateNewDecl; 10462 } 10463 10464 // If this is a friend or a reference to a class in a dependent 10465 // context, don't try to make a decl for it. 10466 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10467 DC = computeDeclContext(SS, false); 10468 if (!DC) { 10469 IsDependent = true; 10470 return 0; 10471 } 10472 } else { 10473 DC = computeDeclContext(SS, true); 10474 if (!DC) { 10475 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10476 << SS.getRange(); 10477 return 0; 10478 } 10479 } 10480 10481 if (RequireCompleteDeclContext(SS, DC)) 10482 return 0; 10483 10484 SearchDC = DC; 10485 // Look-up name inside 'foo::'. 10486 LookupQualifiedName(Previous, DC); 10487 10488 if (Previous.isAmbiguous()) 10489 return 0; 10490 10491 if (Previous.empty()) { 10492 // Name lookup did not find anything. However, if the 10493 // nested-name-specifier refers to the current instantiation, 10494 // and that current instantiation has any dependent base 10495 // classes, we might find something at instantiation time: treat 10496 // this as a dependent elaborated-type-specifier. 10497 // But this only makes any sense for reference-like lookups. 10498 if (Previous.wasNotFoundInCurrentInstantiation() && 10499 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10500 IsDependent = true; 10501 return 0; 10502 } 10503 10504 // A tag 'foo::bar' must already exist. 10505 Diag(NameLoc, diag::err_not_tag_in_scope) 10506 << Kind << Name << DC << SS.getRange(); 10507 Name = 0; 10508 Invalid = true; 10509 goto CreateNewDecl; 10510 } 10511 } else if (Name) { 10512 // If this is a named struct, check to see if there was a previous forward 10513 // declaration or definition. 10514 // FIXME: We're looking into outer scopes here, even when we 10515 // shouldn't be. Doing so can result in ambiguities that we 10516 // shouldn't be diagnosing. 10517 LookupName(Previous, S); 10518 10519 // When declaring or defining a tag, ignore ambiguities introduced 10520 // by types using'ed into this scope. 10521 if (Previous.isAmbiguous() && 10522 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10523 LookupResult::Filter F = Previous.makeFilter(); 10524 while (F.hasNext()) { 10525 NamedDecl *ND = F.next(); 10526 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10527 F.erase(); 10528 } 10529 F.done(); 10530 } 10531 10532 // C++11 [namespace.memdef]p3: 10533 // If the name in a friend declaration is neither qualified nor 10534 // a template-id and the declaration is a function or an 10535 // elaborated-type-specifier, the lookup to determine whether 10536 // the entity has been previously declared shall not consider 10537 // any scopes outside the innermost enclosing namespace. 10538 // 10539 // Does it matter that this should be by scope instead of by 10540 // semantic context? 10541 if (!Previous.empty() && TUK == TUK_Friend) { 10542 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10543 LookupResult::Filter F = Previous.makeFilter(); 10544 while (F.hasNext()) { 10545 NamedDecl *ND = F.next(); 10546 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10547 if (DC->isFileContext() && 10548 !EnclosingNS->Encloses(ND->getDeclContext())) { 10549 F.erase(); 10550 FriendSawTagOutsideEnclosingNamespace = true; 10551 } 10552 } 10553 F.done(); 10554 } 10555 10556 // Note: there used to be some attempt at recovery here. 10557 if (Previous.isAmbiguous()) 10558 return 0; 10559 10560 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10561 // FIXME: This makes sure that we ignore the contexts associated 10562 // with C structs, unions, and enums when looking for a matching 10563 // tag declaration or definition. See the similar lookup tweak 10564 // in Sema::LookupName; is there a better way to deal with this? 10565 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10566 SearchDC = SearchDC->getParent(); 10567 } 10568 } else if (S->isFunctionPrototypeScope()) { 10569 // If this is an enum declaration in function prototype scope, set its 10570 // initial context to the translation unit. 10571 // FIXME: [citation needed] 10572 SearchDC = Context.getTranslationUnitDecl(); 10573 } 10574 10575 if (Previous.isSingleResult() && 10576 Previous.getFoundDecl()->isTemplateParameter()) { 10577 // Maybe we will complain about the shadowed template parameter. 10578 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10579 // Just pretend that we didn't see the previous declaration. 10580 Previous.clear(); 10581 } 10582 10583 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10584 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10585 // This is a declaration of or a reference to "std::bad_alloc". 10586 isStdBadAlloc = true; 10587 10588 if (Previous.empty() && StdBadAlloc) { 10589 // std::bad_alloc has been implicitly declared (but made invisible to 10590 // name lookup). Fill in this implicit declaration as the previous 10591 // declaration, so that the declarations get chained appropriately. 10592 Previous.addDecl(getStdBadAlloc()); 10593 } 10594 } 10595 10596 // If we didn't find a previous declaration, and this is a reference 10597 // (or friend reference), move to the correct scope. In C++, we 10598 // also need to do a redeclaration lookup there, just in case 10599 // there's a shadow friend decl. 10600 if (Name && Previous.empty() && 10601 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10602 if (Invalid) goto CreateNewDecl; 10603 assert(SS.isEmpty()); 10604 10605 if (TUK == TUK_Reference) { 10606 // C++ [basic.scope.pdecl]p5: 10607 // -- for an elaborated-type-specifier of the form 10608 // 10609 // class-key identifier 10610 // 10611 // if the elaborated-type-specifier is used in the 10612 // decl-specifier-seq or parameter-declaration-clause of a 10613 // function defined in namespace scope, the identifier is 10614 // declared as a class-name in the namespace that contains 10615 // the declaration; otherwise, except as a friend 10616 // declaration, the identifier is declared in the smallest 10617 // non-class, non-function-prototype scope that contains the 10618 // declaration. 10619 // 10620 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10621 // C structs and unions. 10622 // 10623 // It is an error in C++ to declare (rather than define) an enum 10624 // type, including via an elaborated type specifier. We'll 10625 // diagnose that later; for now, declare the enum in the same 10626 // scope as we would have picked for any other tag type. 10627 // 10628 // GNU C also supports this behavior as part of its incomplete 10629 // enum types extension, while GNU C++ does not. 10630 // 10631 // Find the context where we'll be declaring the tag. 10632 // FIXME: We would like to maintain the current DeclContext as the 10633 // lexical context, 10634 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10635 SearchDC = SearchDC->getParent(); 10636 10637 // Find the scope where we'll be declaring the tag. 10638 while (S->isClassScope() || 10639 (getLangOpts().CPlusPlus && 10640 S->isFunctionPrototypeScope()) || 10641 ((S->getFlags() & Scope::DeclScope) == 0) || 10642 (S->getEntity() && S->getEntity()->isTransparentContext())) 10643 S = S->getParent(); 10644 } else { 10645 assert(TUK == TUK_Friend); 10646 // C++ [namespace.memdef]p3: 10647 // If a friend declaration in a non-local class first declares a 10648 // class or function, the friend class or function is a member of 10649 // the innermost enclosing namespace. 10650 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10651 } 10652 10653 // In C++, we need to do a redeclaration lookup to properly 10654 // diagnose some problems. 10655 if (getLangOpts().CPlusPlus) { 10656 Previous.setRedeclarationKind(ForRedeclaration); 10657 LookupQualifiedName(Previous, SearchDC); 10658 } 10659 } 10660 10661 if (!Previous.empty()) { 10662 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10663 NamedDecl *DirectPrevDecl = 10664 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10665 10666 // It's okay to have a tag decl in the same scope as a typedef 10667 // which hides a tag decl in the same scope. Finding this 10668 // insanity with a redeclaration lookup can only actually happen 10669 // in C++. 10670 // 10671 // This is also okay for elaborated-type-specifiers, which is 10672 // technically forbidden by the current standard but which is 10673 // okay according to the likely resolution of an open issue; 10674 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10675 if (getLangOpts().CPlusPlus) { 10676 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10677 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10678 TagDecl *Tag = TT->getDecl(); 10679 if (Tag->getDeclName() == Name && 10680 Tag->getDeclContext()->getRedeclContext() 10681 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10682 PrevDecl = Tag; 10683 Previous.clear(); 10684 Previous.addDecl(Tag); 10685 Previous.resolveKind(); 10686 } 10687 } 10688 } 10689 } 10690 10691 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10692 // If this is a use of a previous tag, or if the tag is already declared 10693 // in the same scope (so that the definition/declaration completes or 10694 // rementions the tag), reuse the decl. 10695 if (TUK == TUK_Reference || TUK == TUK_Friend || 10696 isDeclInScope(DirectPrevDecl, SearchDC, S, 10697 SS.isNotEmpty() || isExplicitSpecialization)) { 10698 // Make sure that this wasn't declared as an enum and now used as a 10699 // struct or something similar. 10700 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10701 TUK == TUK_Definition, KWLoc, 10702 *Name)) { 10703 bool SafeToContinue 10704 = (PrevTagDecl->getTagKind() != TTK_Enum && 10705 Kind != TTK_Enum); 10706 if (SafeToContinue) 10707 Diag(KWLoc, diag::err_use_with_wrong_tag) 10708 << Name 10709 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10710 PrevTagDecl->getKindName()); 10711 else 10712 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10713 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10714 10715 if (SafeToContinue) 10716 Kind = PrevTagDecl->getTagKind(); 10717 else { 10718 // Recover by making this an anonymous redefinition. 10719 Name = 0; 10720 Previous.clear(); 10721 Invalid = true; 10722 } 10723 } 10724 10725 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10726 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10727 10728 // If this is an elaborated-type-specifier for a scoped enumeration, 10729 // the 'class' keyword is not necessary and not permitted. 10730 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10731 if (ScopedEnum) 10732 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10733 << PrevEnum->isScoped() 10734 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10735 return PrevTagDecl; 10736 } 10737 10738 QualType EnumUnderlyingTy; 10739 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10740 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 10741 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10742 EnumUnderlyingTy = QualType(T, 0); 10743 10744 // All conflicts with previous declarations are recovered by 10745 // returning the previous declaration, unless this is a definition, 10746 // in which case we want the caller to bail out. 10747 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10748 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10749 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10750 } 10751 10752 // C++11 [class.mem]p1: 10753 // A member shall not be declared twice in the member-specification, 10754 // except that a nested class or member class template can be declared 10755 // and then later defined. 10756 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10757 S->isDeclScope(PrevDecl)) { 10758 Diag(NameLoc, diag::ext_member_redeclared); 10759 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10760 } 10761 10762 if (!Invalid) { 10763 // If this is a use, just return the declaration we found. 10764 10765 // FIXME: In the future, return a variant or some other clue 10766 // for the consumer of this Decl to know it doesn't own it. 10767 // For our current ASTs this shouldn't be a problem, but will 10768 // need to be changed with DeclGroups. 10769 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10770 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10771 return PrevTagDecl; 10772 10773 // Diagnose attempts to redefine a tag. 10774 if (TUK == TUK_Definition) { 10775 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10776 // If we're defining a specialization and the previous definition 10777 // is from an implicit instantiation, don't emit an error 10778 // here; we'll catch this in the general case below. 10779 bool IsExplicitSpecializationAfterInstantiation = false; 10780 if (isExplicitSpecialization) { 10781 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10782 IsExplicitSpecializationAfterInstantiation = 10783 RD->getTemplateSpecializationKind() != 10784 TSK_ExplicitSpecialization; 10785 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10786 IsExplicitSpecializationAfterInstantiation = 10787 ED->getTemplateSpecializationKind() != 10788 TSK_ExplicitSpecialization; 10789 } 10790 10791 if (!IsExplicitSpecializationAfterInstantiation) { 10792 // A redeclaration in function prototype scope in C isn't 10793 // visible elsewhere, so merely issue a warning. 10794 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10795 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10796 else 10797 Diag(NameLoc, diag::err_redefinition) << Name; 10798 Diag(Def->getLocation(), diag::note_previous_definition); 10799 // If this is a redefinition, recover by making this 10800 // struct be anonymous, which will make any later 10801 // references get the previous definition. 10802 Name = 0; 10803 Previous.clear(); 10804 Invalid = true; 10805 } 10806 } else { 10807 // If the type is currently being defined, complain 10808 // about a nested redefinition. 10809 const TagType *Tag 10810 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10811 if (Tag->isBeingDefined()) { 10812 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10813 Diag(PrevTagDecl->getLocation(), 10814 diag::note_previous_definition); 10815 Name = 0; 10816 Previous.clear(); 10817 Invalid = true; 10818 } 10819 } 10820 10821 // Okay, this is definition of a previously declared or referenced 10822 // tag PrevDecl. We're going to create a new Decl for it. 10823 } 10824 } 10825 // If we get here we have (another) forward declaration or we 10826 // have a definition. Just create a new decl. 10827 10828 } else { 10829 // If we get here, this is a definition of a new tag type in a nested 10830 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 10831 // new decl/type. We set PrevDecl to NULL so that the entities 10832 // have distinct types. 10833 Previous.clear(); 10834 } 10835 // If we get here, we're going to create a new Decl. If PrevDecl 10836 // is non-NULL, it's a definition of the tag declared by 10837 // PrevDecl. If it's NULL, we have a new definition. 10838 10839 10840 // Otherwise, PrevDecl is not a tag, but was found with tag 10841 // lookup. This is only actually possible in C++, where a few 10842 // things like templates still live in the tag namespace. 10843 } else { 10844 // Use a better diagnostic if an elaborated-type-specifier 10845 // found the wrong kind of type on the first 10846 // (non-redeclaration) lookup. 10847 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 10848 !Previous.isForRedeclaration()) { 10849 unsigned Kind = 0; 10850 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10851 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10852 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10853 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 10854 Diag(PrevDecl->getLocation(), diag::note_declared_at); 10855 Invalid = true; 10856 10857 // Otherwise, only diagnose if the declaration is in scope. 10858 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 10859 SS.isNotEmpty() || isExplicitSpecialization)) { 10860 // do nothing 10861 10862 // Diagnose implicit declarations introduced by elaborated types. 10863 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 10864 unsigned Kind = 0; 10865 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 10866 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 10867 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 10868 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 10869 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10870 Invalid = true; 10871 10872 // Otherwise it's a declaration. Call out a particularly common 10873 // case here. 10874 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10875 unsigned Kind = 0; 10876 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 10877 Diag(NameLoc, diag::err_tag_definition_of_typedef) 10878 << Name << Kind << TND->getUnderlyingType(); 10879 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 10880 Invalid = true; 10881 10882 // Otherwise, diagnose. 10883 } else { 10884 // The tag name clashes with something else in the target scope, 10885 // issue an error and recover by making this tag be anonymous. 10886 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 10887 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10888 Name = 0; 10889 Invalid = true; 10890 } 10891 10892 // The existing declaration isn't relevant to us; we're in a 10893 // new scope, so clear out the previous declaration. 10894 Previous.clear(); 10895 } 10896 } 10897 10898 CreateNewDecl: 10899 10900 TagDecl *PrevDecl = 0; 10901 if (Previous.isSingleResult()) 10902 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 10903 10904 // If there is an identifier, use the location of the identifier as the 10905 // location of the decl, otherwise use the location of the struct/union 10906 // keyword. 10907 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 10908 10909 // Otherwise, create a new declaration. If there is a previous 10910 // declaration of the same entity, the two will be linked via 10911 // PrevDecl. 10912 TagDecl *New; 10913 10914 bool IsForwardReference = false; 10915 if (Kind == TTK_Enum) { 10916 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10917 // enum X { A, B, C } D; D should chain to X. 10918 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 10919 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 10920 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 10921 // If this is an undefined enum, warn. 10922 if (TUK != TUK_Definition && !Invalid) { 10923 TagDecl *Def; 10924 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 10925 cast<EnumDecl>(New)->isFixed()) { 10926 // C++0x: 7.2p2: opaque-enum-declaration. 10927 // Conflicts are diagnosed above. Do nothing. 10928 } 10929 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 10930 Diag(Loc, diag::ext_forward_ref_enum_def) 10931 << New; 10932 Diag(Def->getLocation(), diag::note_previous_definition); 10933 } else { 10934 unsigned DiagID = diag::ext_forward_ref_enum; 10935 if (getLangOpts().MSVCCompat) 10936 DiagID = diag::ext_ms_forward_ref_enum; 10937 else if (getLangOpts().CPlusPlus) 10938 DiagID = diag::err_forward_ref_enum; 10939 Diag(Loc, DiagID); 10940 10941 // If this is a forward-declared reference to an enumeration, make a 10942 // note of it; we won't actually be introducing the declaration into 10943 // the declaration context. 10944 if (TUK == TUK_Reference) 10945 IsForwardReference = true; 10946 } 10947 } 10948 10949 if (EnumUnderlying) { 10950 EnumDecl *ED = cast<EnumDecl>(New); 10951 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10952 ED->setIntegerTypeSourceInfo(TI); 10953 else 10954 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 10955 ED->setPromotionType(ED->getIntegerType()); 10956 } 10957 10958 } else { 10959 // struct/union/class 10960 10961 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 10962 // struct X { int A; } D; D should chain to X. 10963 if (getLangOpts().CPlusPlus) { 10964 // FIXME: Look for a way to use RecordDecl for simple structs. 10965 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10966 cast_or_null<CXXRecordDecl>(PrevDecl)); 10967 10968 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 10969 StdBadAlloc = cast<CXXRecordDecl>(New); 10970 } else 10971 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 10972 cast_or_null<RecordDecl>(PrevDecl)); 10973 } 10974 10975 // C++11 [dcl.type]p3: 10976 // A type-specifier-seq shall not define a class or enumeration [...]. 10977 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 10978 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 10979 << Context.getTagDeclType(New); 10980 Invalid = true; 10981 } 10982 10983 // Maybe add qualifier info. 10984 if (SS.isNotEmpty()) { 10985 if (SS.isSet()) { 10986 // If this is either a declaration or a definition, check the 10987 // nested-name-specifier against the current context. We don't do this 10988 // for explicit specializations, because they have similar checking 10989 // (with more specific diagnostics) in the call to 10990 // CheckMemberSpecialization, below. 10991 if (!isExplicitSpecialization && 10992 (TUK == TUK_Definition || TUK == TUK_Declaration) && 10993 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 10994 Invalid = true; 10995 10996 New->setQualifierInfo(SS.getWithLocInContext(Context)); 10997 if (TemplateParameterLists.size() > 0) { 10998 New->setTemplateParameterListsInfo(Context, 10999 TemplateParameterLists.size(), 11000 TemplateParameterLists.data()); 11001 } 11002 } 11003 else 11004 Invalid = true; 11005 } 11006 11007 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11008 // Add alignment attributes if necessary; these attributes are checked when 11009 // the ASTContext lays out the structure. 11010 // 11011 // It is important for implementing the correct semantics that this 11012 // happen here (in act on tag decl). The #pragma pack stack is 11013 // maintained as a result of parser callbacks which can occur at 11014 // many points during the parsing of a struct declaration (because 11015 // the #pragma tokens are effectively skipped over during the 11016 // parsing of the struct). 11017 if (TUK == TUK_Definition) { 11018 AddAlignmentAttributesForRecord(RD); 11019 AddMsStructLayoutForRecord(RD); 11020 } 11021 } 11022 11023 if (ModulePrivateLoc.isValid()) { 11024 if (isExplicitSpecialization) 11025 Diag(New->getLocation(), diag::err_module_private_specialization) 11026 << 2 11027 << FixItHint::CreateRemoval(ModulePrivateLoc); 11028 // __module_private__ does not apply to local classes. However, we only 11029 // diagnose this as an error when the declaration specifiers are 11030 // freestanding. Here, we just ignore the __module_private__. 11031 else if (!SearchDC->isFunctionOrMethod()) 11032 New->setModulePrivate(); 11033 } 11034 11035 // If this is a specialization of a member class (of a class template), 11036 // check the specialization. 11037 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11038 Invalid = true; 11039 11040 if (Invalid) 11041 New->setInvalidDecl(); 11042 11043 if (Attr) 11044 ProcessDeclAttributeList(S, New, Attr); 11045 11046 // If we're declaring or defining a tag in function prototype scope in C, 11047 // note that this type can only be used within the function and add it to 11048 // the list of decls to inject into the function definition scope. 11049 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) && 11050 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11051 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11052 DeclsInPrototypeScope.push_back(New); 11053 } 11054 11055 // Set the lexical context. If the tag has a C++ scope specifier, the 11056 // lexical context will be different from the semantic context. 11057 New->setLexicalDeclContext(CurContext); 11058 11059 // Mark this as a friend decl if applicable. 11060 // In Microsoft mode, a friend declaration also acts as a forward 11061 // declaration so we always pass true to setObjectOfFriendDecl to make 11062 // the tag name visible. 11063 if (TUK == TUK_Friend) 11064 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11065 getLangOpts().MicrosoftExt); 11066 11067 // Set the access specifier. 11068 if (!Invalid && SearchDC->isRecord()) 11069 SetMemberAccessSpecifier(New, PrevDecl, AS); 11070 11071 if (TUK == TUK_Definition) 11072 New->startDefinition(); 11073 11074 // If this has an identifier, add it to the scope stack. 11075 if (TUK == TUK_Friend) { 11076 // We might be replacing an existing declaration in the lookup tables; 11077 // if so, borrow its access specifier. 11078 if (PrevDecl) 11079 New->setAccess(PrevDecl->getAccess()); 11080 11081 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11082 DC->makeDeclVisibleInContext(New); 11083 if (Name) // can be null along some error paths 11084 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11085 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11086 } else if (Name) { 11087 S = getNonFieldDeclScope(S); 11088 PushOnScopeChains(New, S, !IsForwardReference); 11089 if (IsForwardReference) 11090 SearchDC->makeDeclVisibleInContext(New); 11091 11092 } else { 11093 CurContext->addDecl(New); 11094 } 11095 11096 // If this is the C FILE type, notify the AST context. 11097 if (IdentifierInfo *II = New->getIdentifier()) 11098 if (!New->isInvalidDecl() && 11099 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11100 II->isStr("FILE")) 11101 Context.setFILEDecl(New); 11102 11103 if (PrevDecl) 11104 mergeDeclAttributes(New, PrevDecl); 11105 11106 // If there's a #pragma GCC visibility in scope, set the visibility of this 11107 // record. 11108 AddPushedVisibilityAttribute(New); 11109 11110 OwnedDecl = true; 11111 // In C++, don't return an invalid declaration. We can't recover well from 11112 // the cases where we make the type anonymous. 11113 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11114 } 11115 11116 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11117 AdjustDeclIfTemplate(TagD); 11118 TagDecl *Tag = cast<TagDecl>(TagD); 11119 11120 // Enter the tag context. 11121 PushDeclContext(S, Tag); 11122 11123 ActOnDocumentableDecl(TagD); 11124 11125 // If there's a #pragma GCC visibility in scope, set the visibility of this 11126 // record. 11127 AddPushedVisibilityAttribute(Tag); 11128 } 11129 11130 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11131 assert(isa<ObjCContainerDecl>(IDecl) && 11132 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11133 DeclContext *OCD = cast<DeclContext>(IDecl); 11134 assert(getContainingDC(OCD) == CurContext && 11135 "The next DeclContext should be lexically contained in the current one."); 11136 CurContext = OCD; 11137 return IDecl; 11138 } 11139 11140 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11141 SourceLocation FinalLoc, 11142 bool IsFinalSpelledSealed, 11143 SourceLocation LBraceLoc) { 11144 AdjustDeclIfTemplate(TagD); 11145 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11146 11147 FieldCollector->StartClass(); 11148 11149 if (!Record->getIdentifier()) 11150 return; 11151 11152 if (FinalLoc.isValid()) 11153 Record->addAttr(new (Context) 11154 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11155 11156 // C++ [class]p2: 11157 // [...] The class-name is also inserted into the scope of the 11158 // class itself; this is known as the injected-class-name. For 11159 // purposes of access checking, the injected-class-name is treated 11160 // as if it were a public member name. 11161 CXXRecordDecl *InjectedClassName 11162 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11163 Record->getLocStart(), Record->getLocation(), 11164 Record->getIdentifier(), 11165 /*PrevDecl=*/0, 11166 /*DelayTypeCreation=*/true); 11167 Context.getTypeDeclType(InjectedClassName, Record); 11168 InjectedClassName->setImplicit(); 11169 InjectedClassName->setAccess(AS_public); 11170 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11171 InjectedClassName->setDescribedClassTemplate(Template); 11172 PushOnScopeChains(InjectedClassName, S); 11173 assert(InjectedClassName->isInjectedClassName() && 11174 "Broken injected-class-name"); 11175 } 11176 11177 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11178 SourceLocation RBraceLoc) { 11179 AdjustDeclIfTemplate(TagD); 11180 TagDecl *Tag = cast<TagDecl>(TagD); 11181 Tag->setRBraceLoc(RBraceLoc); 11182 11183 // Make sure we "complete" the definition even it is invalid. 11184 if (Tag->isBeingDefined()) { 11185 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11186 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11187 RD->completeDefinition(); 11188 } 11189 11190 if (isa<CXXRecordDecl>(Tag)) 11191 FieldCollector->FinishClass(); 11192 11193 // Exit this scope of this tag's definition. 11194 PopDeclContext(); 11195 11196 if (getCurLexicalContext()->isObjCContainer() && 11197 Tag->getDeclContext()->isFileContext()) 11198 Tag->setTopLevelDeclInObjCContainer(); 11199 11200 // Notify the consumer that we've defined a tag. 11201 if (!Tag->isInvalidDecl()) 11202 Consumer.HandleTagDeclDefinition(Tag); 11203 } 11204 11205 void Sema::ActOnObjCContainerFinishDefinition() { 11206 // Exit this scope of this interface definition. 11207 PopDeclContext(); 11208 } 11209 11210 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11211 assert(DC == CurContext && "Mismatch of container contexts"); 11212 OriginalLexicalContext = DC; 11213 ActOnObjCContainerFinishDefinition(); 11214 } 11215 11216 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11217 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11218 OriginalLexicalContext = 0; 11219 } 11220 11221 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11222 AdjustDeclIfTemplate(TagD); 11223 TagDecl *Tag = cast<TagDecl>(TagD); 11224 Tag->setInvalidDecl(); 11225 11226 // Make sure we "complete" the definition even it is invalid. 11227 if (Tag->isBeingDefined()) { 11228 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11229 RD->completeDefinition(); 11230 } 11231 11232 // We're undoing ActOnTagStartDefinition here, not 11233 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11234 // the FieldCollector. 11235 11236 PopDeclContext(); 11237 } 11238 11239 // Note that FieldName may be null for anonymous bitfields. 11240 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11241 IdentifierInfo *FieldName, 11242 QualType FieldTy, bool IsMsStruct, 11243 Expr *BitWidth, bool *ZeroWidth) { 11244 // Default to true; that shouldn't confuse checks for emptiness 11245 if (ZeroWidth) 11246 *ZeroWidth = true; 11247 11248 // C99 6.7.2.1p4 - verify the field type. 11249 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11250 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11251 // Handle incomplete types with specific error. 11252 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11253 return ExprError(); 11254 if (FieldName) 11255 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11256 << FieldName << FieldTy << BitWidth->getSourceRange(); 11257 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11258 << FieldTy << BitWidth->getSourceRange(); 11259 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11260 UPPC_BitFieldWidth)) 11261 return ExprError(); 11262 11263 // If the bit-width is type- or value-dependent, don't try to check 11264 // it now. 11265 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11266 return Owned(BitWidth); 11267 11268 llvm::APSInt Value; 11269 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11270 if (ICE.isInvalid()) 11271 return ICE; 11272 BitWidth = ICE.take(); 11273 11274 if (Value != 0 && ZeroWidth) 11275 *ZeroWidth = false; 11276 11277 // Zero-width bitfield is ok for anonymous field. 11278 if (Value == 0 && FieldName) 11279 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11280 11281 if (Value.isSigned() && Value.isNegative()) { 11282 if (FieldName) 11283 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11284 << FieldName << Value.toString(10); 11285 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11286 << Value.toString(10); 11287 } 11288 11289 if (!FieldTy->isDependentType()) { 11290 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11291 if (Value.getZExtValue() > TypeSize) { 11292 if (!getLangOpts().CPlusPlus || IsMsStruct || 11293 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11294 if (FieldName) 11295 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11296 << FieldName << (unsigned)Value.getZExtValue() 11297 << (unsigned)TypeSize; 11298 11299 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11300 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11301 } 11302 11303 if (FieldName) 11304 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11305 << FieldName << (unsigned)Value.getZExtValue() 11306 << (unsigned)TypeSize; 11307 else 11308 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11309 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11310 } 11311 } 11312 11313 return Owned(BitWidth); 11314 } 11315 11316 /// ActOnField - Each field of a C struct/union is passed into this in order 11317 /// to create a FieldDecl object for it. 11318 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11319 Declarator &D, Expr *BitfieldWidth) { 11320 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11321 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11322 /*InitStyle=*/ICIS_NoInit, AS_public); 11323 return Res; 11324 } 11325 11326 /// HandleField - Analyze a field of a C struct or a C++ data member. 11327 /// 11328 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11329 SourceLocation DeclStart, 11330 Declarator &D, Expr *BitWidth, 11331 InClassInitStyle InitStyle, 11332 AccessSpecifier AS) { 11333 IdentifierInfo *II = D.getIdentifier(); 11334 SourceLocation Loc = DeclStart; 11335 if (II) Loc = D.getIdentifierLoc(); 11336 11337 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11338 QualType T = TInfo->getType(); 11339 if (getLangOpts().CPlusPlus) { 11340 CheckExtraCXXDefaultArguments(D); 11341 11342 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11343 UPPC_DataMemberType)) { 11344 D.setInvalidType(); 11345 T = Context.IntTy; 11346 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11347 } 11348 } 11349 11350 // TR 18037 does not allow fields to be declared with address spaces. 11351 if (T.getQualifiers().hasAddressSpace()) { 11352 Diag(Loc, diag::err_field_with_address_space); 11353 D.setInvalidType(); 11354 } 11355 11356 // OpenCL 1.2 spec, s6.9 r: 11357 // The event type cannot be used to declare a structure or union field. 11358 if (LangOpts.OpenCL && T->isEventT()) { 11359 Diag(Loc, diag::err_event_t_struct_field); 11360 D.setInvalidType(); 11361 } 11362 11363 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11364 11365 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11366 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11367 diag::err_invalid_thread) 11368 << DeclSpec::getSpecifierName(TSCS); 11369 11370 // Check to see if this name was declared as a member previously 11371 NamedDecl *PrevDecl = 0; 11372 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11373 LookupName(Previous, S); 11374 switch (Previous.getResultKind()) { 11375 case LookupResult::Found: 11376 case LookupResult::FoundUnresolvedValue: 11377 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11378 break; 11379 11380 case LookupResult::FoundOverloaded: 11381 PrevDecl = Previous.getRepresentativeDecl(); 11382 break; 11383 11384 case LookupResult::NotFound: 11385 case LookupResult::NotFoundInCurrentInstantiation: 11386 case LookupResult::Ambiguous: 11387 break; 11388 } 11389 Previous.suppressDiagnostics(); 11390 11391 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11392 // Maybe we will complain about the shadowed template parameter. 11393 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11394 // Just pretend that we didn't see the previous declaration. 11395 PrevDecl = 0; 11396 } 11397 11398 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11399 PrevDecl = 0; 11400 11401 bool Mutable 11402 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11403 SourceLocation TSSL = D.getLocStart(); 11404 FieldDecl *NewFD 11405 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11406 TSSL, AS, PrevDecl, &D); 11407 11408 if (NewFD->isInvalidDecl()) 11409 Record->setInvalidDecl(); 11410 11411 if (D.getDeclSpec().isModulePrivateSpecified()) 11412 NewFD->setModulePrivate(); 11413 11414 if (NewFD->isInvalidDecl() && PrevDecl) { 11415 // Don't introduce NewFD into scope; there's already something 11416 // with the same name in the same scope. 11417 } else if (II) { 11418 PushOnScopeChains(NewFD, S); 11419 } else 11420 Record->addDecl(NewFD); 11421 11422 return NewFD; 11423 } 11424 11425 /// \brief Build a new FieldDecl and check its well-formedness. 11426 /// 11427 /// This routine builds a new FieldDecl given the fields name, type, 11428 /// record, etc. \p PrevDecl should refer to any previous declaration 11429 /// with the same name and in the same scope as the field to be 11430 /// created. 11431 /// 11432 /// \returns a new FieldDecl. 11433 /// 11434 /// \todo The Declarator argument is a hack. It will be removed once 11435 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11436 TypeSourceInfo *TInfo, 11437 RecordDecl *Record, SourceLocation Loc, 11438 bool Mutable, Expr *BitWidth, 11439 InClassInitStyle InitStyle, 11440 SourceLocation TSSL, 11441 AccessSpecifier AS, NamedDecl *PrevDecl, 11442 Declarator *D) { 11443 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11444 bool InvalidDecl = false; 11445 if (D) InvalidDecl = D->isInvalidType(); 11446 11447 // If we receive a broken type, recover by assuming 'int' and 11448 // marking this declaration as invalid. 11449 if (T.isNull()) { 11450 InvalidDecl = true; 11451 T = Context.IntTy; 11452 } 11453 11454 QualType EltTy = Context.getBaseElementType(T); 11455 if (!EltTy->isDependentType()) { 11456 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11457 // Fields of incomplete type force their record to be invalid. 11458 Record->setInvalidDecl(); 11459 InvalidDecl = true; 11460 } else { 11461 NamedDecl *Def; 11462 EltTy->isIncompleteType(&Def); 11463 if (Def && Def->isInvalidDecl()) { 11464 Record->setInvalidDecl(); 11465 InvalidDecl = true; 11466 } 11467 } 11468 } 11469 11470 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11471 if (BitWidth && getLangOpts().OpenCL) { 11472 Diag(Loc, diag::err_opencl_bitfields); 11473 InvalidDecl = true; 11474 } 11475 11476 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11477 // than a variably modified type. 11478 if (!InvalidDecl && T->isVariablyModifiedType()) { 11479 bool SizeIsNegative; 11480 llvm::APSInt Oversized; 11481 11482 TypeSourceInfo *FixedTInfo = 11483 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11484 SizeIsNegative, 11485 Oversized); 11486 if (FixedTInfo) { 11487 Diag(Loc, diag::warn_illegal_constant_array_size); 11488 TInfo = FixedTInfo; 11489 T = FixedTInfo->getType(); 11490 } else { 11491 if (SizeIsNegative) 11492 Diag(Loc, diag::err_typecheck_negative_array_size); 11493 else if (Oversized.getBoolValue()) 11494 Diag(Loc, diag::err_array_too_large) 11495 << Oversized.toString(10); 11496 else 11497 Diag(Loc, diag::err_typecheck_field_variable_size); 11498 InvalidDecl = true; 11499 } 11500 } 11501 11502 // Fields can not have abstract class types 11503 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11504 diag::err_abstract_type_in_decl, 11505 AbstractFieldType)) 11506 InvalidDecl = true; 11507 11508 bool ZeroWidth = false; 11509 // If this is declared as a bit-field, check the bit-field. 11510 if (!InvalidDecl && BitWidth) { 11511 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11512 &ZeroWidth).take(); 11513 if (!BitWidth) { 11514 InvalidDecl = true; 11515 BitWidth = 0; 11516 ZeroWidth = false; 11517 } 11518 } 11519 11520 // Check that 'mutable' is consistent with the type of the declaration. 11521 if (!InvalidDecl && Mutable) { 11522 unsigned DiagID = 0; 11523 if (T->isReferenceType()) 11524 DiagID = diag::err_mutable_reference; 11525 else if (T.isConstQualified()) 11526 DiagID = diag::err_mutable_const; 11527 11528 if (DiagID) { 11529 SourceLocation ErrLoc = Loc; 11530 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11531 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11532 Diag(ErrLoc, DiagID); 11533 Mutable = false; 11534 InvalidDecl = true; 11535 } 11536 } 11537 11538 // C++11 [class.union]p8 (DR1460): 11539 // At most one variant member of a union may have a 11540 // brace-or-equal-initializer. 11541 if (InitStyle != ICIS_NoInit) 11542 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11543 11544 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11545 BitWidth, Mutable, InitStyle); 11546 if (InvalidDecl) 11547 NewFD->setInvalidDecl(); 11548 11549 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11550 Diag(Loc, diag::err_duplicate_member) << II; 11551 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11552 NewFD->setInvalidDecl(); 11553 } 11554 11555 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11556 if (Record->isUnion()) { 11557 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11558 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11559 if (RDecl->getDefinition()) { 11560 // C++ [class.union]p1: An object of a class with a non-trivial 11561 // constructor, a non-trivial copy constructor, a non-trivial 11562 // destructor, or a non-trivial copy assignment operator 11563 // cannot be a member of a union, nor can an array of such 11564 // objects. 11565 if (CheckNontrivialField(NewFD)) 11566 NewFD->setInvalidDecl(); 11567 } 11568 } 11569 11570 // C++ [class.union]p1: If a union contains a member of reference type, 11571 // the program is ill-formed, except when compiling with MSVC extensions 11572 // enabled. 11573 if (EltTy->isReferenceType()) { 11574 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11575 diag::ext_union_member_of_reference_type : 11576 diag::err_union_member_of_reference_type) 11577 << NewFD->getDeclName() << EltTy; 11578 if (!getLangOpts().MicrosoftExt) 11579 NewFD->setInvalidDecl(); 11580 } 11581 } 11582 } 11583 11584 // FIXME: We need to pass in the attributes given an AST 11585 // representation, not a parser representation. 11586 if (D) { 11587 // FIXME: The current scope is almost... but not entirely... correct here. 11588 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11589 11590 if (NewFD->hasAttrs()) 11591 CheckAlignasUnderalignment(NewFD); 11592 } 11593 11594 // In auto-retain/release, infer strong retension for fields of 11595 // retainable type. 11596 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11597 NewFD->setInvalidDecl(); 11598 11599 if (T.isObjCGCWeak()) 11600 Diag(Loc, diag::warn_attribute_weak_on_field); 11601 11602 NewFD->setAccess(AS); 11603 return NewFD; 11604 } 11605 11606 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11607 assert(FD); 11608 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11609 11610 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11611 return false; 11612 11613 QualType EltTy = Context.getBaseElementType(FD->getType()); 11614 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11615 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11616 if (RDecl->getDefinition()) { 11617 // We check for copy constructors before constructors 11618 // because otherwise we'll never get complaints about 11619 // copy constructors. 11620 11621 CXXSpecialMember member = CXXInvalid; 11622 // We're required to check for any non-trivial constructors. Since the 11623 // implicit default constructor is suppressed if there are any 11624 // user-declared constructors, we just need to check that there is a 11625 // trivial default constructor and a trivial copy constructor. (We don't 11626 // worry about move constructors here, since this is a C++98 check.) 11627 if (RDecl->hasNonTrivialCopyConstructor()) 11628 member = CXXCopyConstructor; 11629 else if (!RDecl->hasTrivialDefaultConstructor()) 11630 member = CXXDefaultConstructor; 11631 else if (RDecl->hasNonTrivialCopyAssignment()) 11632 member = CXXCopyAssignment; 11633 else if (RDecl->hasNonTrivialDestructor()) 11634 member = CXXDestructor; 11635 11636 if (member != CXXInvalid) { 11637 if (!getLangOpts().CPlusPlus11 && 11638 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11639 // Objective-C++ ARC: it is an error to have a non-trivial field of 11640 // a union. However, system headers in Objective-C programs 11641 // occasionally have Objective-C lifetime objects within unions, 11642 // and rather than cause the program to fail, we make those 11643 // members unavailable. 11644 SourceLocation Loc = FD->getLocation(); 11645 if (getSourceManager().isInSystemHeader(Loc)) { 11646 if (!FD->hasAttr<UnavailableAttr>()) 11647 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11648 "this system field has retaining ownership", 11649 Loc)); 11650 return false; 11651 } 11652 } 11653 11654 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11655 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11656 diag::err_illegal_union_or_anon_struct_member) 11657 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11658 DiagnoseNontrivial(RDecl, member); 11659 return !getLangOpts().CPlusPlus11; 11660 } 11661 } 11662 } 11663 11664 return false; 11665 } 11666 11667 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11668 /// AST enum value. 11669 static ObjCIvarDecl::AccessControl 11670 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11671 switch (ivarVisibility) { 11672 default: llvm_unreachable("Unknown visitibility kind"); 11673 case tok::objc_private: return ObjCIvarDecl::Private; 11674 case tok::objc_public: return ObjCIvarDecl::Public; 11675 case tok::objc_protected: return ObjCIvarDecl::Protected; 11676 case tok::objc_package: return ObjCIvarDecl::Package; 11677 } 11678 } 11679 11680 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11681 /// in order to create an IvarDecl object for it. 11682 Decl *Sema::ActOnIvar(Scope *S, 11683 SourceLocation DeclStart, 11684 Declarator &D, Expr *BitfieldWidth, 11685 tok::ObjCKeywordKind Visibility) { 11686 11687 IdentifierInfo *II = D.getIdentifier(); 11688 Expr *BitWidth = (Expr*)BitfieldWidth; 11689 SourceLocation Loc = DeclStart; 11690 if (II) Loc = D.getIdentifierLoc(); 11691 11692 // FIXME: Unnamed fields can be handled in various different ways, for 11693 // example, unnamed unions inject all members into the struct namespace! 11694 11695 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11696 QualType T = TInfo->getType(); 11697 11698 if (BitWidth) { 11699 // 6.7.2.1p3, 6.7.2.1p4 11700 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11701 if (!BitWidth) 11702 D.setInvalidType(); 11703 } else { 11704 // Not a bitfield. 11705 11706 // validate II. 11707 11708 } 11709 if (T->isReferenceType()) { 11710 Diag(Loc, diag::err_ivar_reference_type); 11711 D.setInvalidType(); 11712 } 11713 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11714 // than a variably modified type. 11715 else if (T->isVariablyModifiedType()) { 11716 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11717 D.setInvalidType(); 11718 } 11719 11720 // Get the visibility (access control) for this ivar. 11721 ObjCIvarDecl::AccessControl ac = 11722 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11723 : ObjCIvarDecl::None; 11724 // Must set ivar's DeclContext to its enclosing interface. 11725 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11726 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11727 return 0; 11728 ObjCContainerDecl *EnclosingContext; 11729 if (ObjCImplementationDecl *IMPDecl = 11730 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11731 if (LangOpts.ObjCRuntime.isFragile()) { 11732 // Case of ivar declared in an implementation. Context is that of its class. 11733 EnclosingContext = IMPDecl->getClassInterface(); 11734 assert(EnclosingContext && "Implementation has no class interface!"); 11735 } 11736 else 11737 EnclosingContext = EnclosingDecl; 11738 } else { 11739 if (ObjCCategoryDecl *CDecl = 11740 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11741 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11742 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11743 return 0; 11744 } 11745 } 11746 EnclosingContext = EnclosingDecl; 11747 } 11748 11749 // Construct the decl. 11750 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11751 DeclStart, Loc, II, T, 11752 TInfo, ac, (Expr *)BitfieldWidth); 11753 11754 if (II) { 11755 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11756 ForRedeclaration); 11757 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11758 && !isa<TagDecl>(PrevDecl)) { 11759 Diag(Loc, diag::err_duplicate_member) << II; 11760 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11761 NewID->setInvalidDecl(); 11762 } 11763 } 11764 11765 // Process attributes attached to the ivar. 11766 ProcessDeclAttributes(S, NewID, D); 11767 11768 if (D.isInvalidType()) 11769 NewID->setInvalidDecl(); 11770 11771 // In ARC, infer 'retaining' for ivars of retainable type. 11772 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11773 NewID->setInvalidDecl(); 11774 11775 if (D.getDeclSpec().isModulePrivateSpecified()) 11776 NewID->setModulePrivate(); 11777 11778 if (II) { 11779 // FIXME: When interfaces are DeclContexts, we'll need to add 11780 // these to the interface. 11781 S->AddDecl(NewID); 11782 IdResolver.AddDecl(NewID); 11783 } 11784 11785 if (LangOpts.ObjCRuntime.isNonFragile() && 11786 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11787 Diag(Loc, diag::warn_ivars_in_interface); 11788 11789 return NewID; 11790 } 11791 11792 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11793 /// class and class extensions. For every class \@interface and class 11794 /// extension \@interface, if the last ivar is a bitfield of any type, 11795 /// then add an implicit `char :0` ivar to the end of that interface. 11796 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11797 SmallVectorImpl<Decl *> &AllIvarDecls) { 11798 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11799 return; 11800 11801 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11802 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11803 11804 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11805 return; 11806 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11807 if (!ID) { 11808 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11809 if (!CD->IsClassExtension()) 11810 return; 11811 } 11812 // No need to add this to end of @implementation. 11813 else 11814 return; 11815 } 11816 // All conditions are met. Add a new bitfield to the tail end of ivars. 11817 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11818 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11819 11820 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11821 DeclLoc, DeclLoc, 0, 11822 Context.CharTy, 11823 Context.getTrivialTypeSourceInfo(Context.CharTy, 11824 DeclLoc), 11825 ObjCIvarDecl::Private, BW, 11826 true); 11827 AllIvarDecls.push_back(Ivar); 11828 } 11829 11830 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 11831 ArrayRef<Decl *> Fields, SourceLocation LBrac, 11832 SourceLocation RBrac, AttributeList *Attr) { 11833 assert(EnclosingDecl && "missing record or interface decl"); 11834 11835 // If this is an Objective-C @implementation or category and we have 11836 // new fields here we should reset the layout of the interface since 11837 // it will now change. 11838 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 11839 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 11840 switch (DC->getKind()) { 11841 default: break; 11842 case Decl::ObjCCategory: 11843 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 11844 break; 11845 case Decl::ObjCImplementation: 11846 Context. 11847 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 11848 break; 11849 } 11850 } 11851 11852 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 11853 11854 // Start counting up the number of named members; make sure to include 11855 // members of anonymous structs and unions in the total. 11856 unsigned NumNamedMembers = 0; 11857 if (Record) { 11858 for (const auto *I : Record->decls()) { 11859 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 11860 if (IFD->getDeclName()) 11861 ++NumNamedMembers; 11862 } 11863 } 11864 11865 // Verify that all the fields are okay. 11866 SmallVector<FieldDecl*, 32> RecFields; 11867 11868 bool ARCErrReported = false; 11869 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 11870 i != end; ++i) { 11871 FieldDecl *FD = cast<FieldDecl>(*i); 11872 11873 // Get the type for the field. 11874 const Type *FDTy = FD->getType().getTypePtr(); 11875 11876 if (!FD->isAnonymousStructOrUnion()) { 11877 // Remember all fields written by the user. 11878 RecFields.push_back(FD); 11879 } 11880 11881 // If the field is already invalid for some reason, don't emit more 11882 // diagnostics about it. 11883 if (FD->isInvalidDecl()) { 11884 EnclosingDecl->setInvalidDecl(); 11885 continue; 11886 } 11887 11888 // C99 6.7.2.1p2: 11889 // A structure or union shall not contain a member with 11890 // incomplete or function type (hence, a structure shall not 11891 // contain an instance of itself, but may contain a pointer to 11892 // an instance of itself), except that the last member of a 11893 // structure with more than one named member may have incomplete 11894 // array type; such a structure (and any union containing, 11895 // possibly recursively, a member that is such a structure) 11896 // shall not be a member of a structure or an element of an 11897 // array. 11898 if (FDTy->isFunctionType()) { 11899 // Field declared as a function. 11900 Diag(FD->getLocation(), diag::err_field_declared_as_function) 11901 << FD->getDeclName(); 11902 FD->setInvalidDecl(); 11903 EnclosingDecl->setInvalidDecl(); 11904 continue; 11905 } else if (FDTy->isIncompleteArrayType() && Record && 11906 ((i + 1 == Fields.end() && !Record->isUnion()) || 11907 ((getLangOpts().MicrosoftExt || 11908 getLangOpts().CPlusPlus) && 11909 (i + 1 == Fields.end() || Record->isUnion())))) { 11910 // Flexible array member. 11911 // Microsoft and g++ is more permissive regarding flexible array. 11912 // It will accept flexible array in union and also 11913 // as the sole element of a struct/class. 11914 unsigned DiagID = 0; 11915 if (Record->isUnion()) 11916 DiagID = getLangOpts().MicrosoftExt 11917 ? diag::ext_flexible_array_union_ms 11918 : getLangOpts().CPlusPlus 11919 ? diag::ext_flexible_array_union_gnu 11920 : diag::err_flexible_array_union; 11921 else if (Fields.size() == 1) 11922 DiagID = getLangOpts().MicrosoftExt 11923 ? diag::ext_flexible_array_empty_aggregate_ms 11924 : getLangOpts().CPlusPlus 11925 ? diag::ext_flexible_array_empty_aggregate_gnu 11926 : NumNamedMembers < 1 11927 ? diag::err_flexible_array_empty_aggregate 11928 : 0; 11929 11930 if (DiagID) 11931 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 11932 << Record->getTagKind(); 11933 // While the layout of types that contain virtual bases is not specified 11934 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 11935 // virtual bases after the derived members. This would make a flexible 11936 // array member declared at the end of an object not adjacent to the end 11937 // of the type. 11938 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 11939 if (RD->getNumVBases() != 0) 11940 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 11941 << FD->getDeclName() << Record->getTagKind(); 11942 if (!getLangOpts().C99) 11943 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 11944 << FD->getDeclName() << Record->getTagKind(); 11945 11946 // If the element type has a non-trivial destructor, we would not 11947 // implicitly destroy the elements, so disallow it for now. 11948 // 11949 // FIXME: GCC allows this. We should probably either implicitly delete 11950 // the destructor of the containing class, or just allow this. 11951 QualType BaseElem = Context.getBaseElementType(FD->getType()); 11952 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 11953 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 11954 << FD->getDeclName() << FD->getType(); 11955 FD->setInvalidDecl(); 11956 EnclosingDecl->setInvalidDecl(); 11957 continue; 11958 } 11959 // Okay, we have a legal flexible array member at the end of the struct. 11960 if (Record) 11961 Record->setHasFlexibleArrayMember(true); 11962 } else if (!FDTy->isDependentType() && 11963 RequireCompleteType(FD->getLocation(), FD->getType(), 11964 diag::err_field_incomplete)) { 11965 // Incomplete type 11966 FD->setInvalidDecl(); 11967 EnclosingDecl->setInvalidDecl(); 11968 continue; 11969 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 11970 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 11971 // If this is a member of a union, then entire union becomes "flexible". 11972 if (Record && Record->isUnion()) { 11973 Record->setHasFlexibleArrayMember(true); 11974 } else { 11975 // If this is a struct/class and this is not the last element, reject 11976 // it. Note that GCC supports variable sized arrays in the middle of 11977 // structures. 11978 if (i + 1 != Fields.end()) 11979 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 11980 << FD->getDeclName() << FD->getType(); 11981 else { 11982 // We support flexible arrays at the end of structs in 11983 // other structs as an extension. 11984 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 11985 << FD->getDeclName(); 11986 if (Record) 11987 Record->setHasFlexibleArrayMember(true); 11988 } 11989 } 11990 } 11991 if (isa<ObjCContainerDecl>(EnclosingDecl) && 11992 RequireNonAbstractType(FD->getLocation(), FD->getType(), 11993 diag::err_abstract_type_in_decl, 11994 AbstractIvarType)) { 11995 // Ivars can not have abstract class types 11996 FD->setInvalidDecl(); 11997 } 11998 if (Record && FDTTy->getDecl()->hasObjectMember()) 11999 Record->setHasObjectMember(true); 12000 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12001 Record->setHasVolatileMember(true); 12002 } else if (FDTy->isObjCObjectType()) { 12003 /// A field cannot be an Objective-c object 12004 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12005 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12006 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12007 FD->setType(T); 12008 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12009 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12010 // It's an error in ARC if a field has lifetime. 12011 // We don't want to report this in a system header, though, 12012 // so we just make the field unavailable. 12013 // FIXME: that's really not sufficient; we need to make the type 12014 // itself invalid to, say, initialize or copy. 12015 QualType T = FD->getType(); 12016 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12017 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12018 SourceLocation loc = FD->getLocation(); 12019 if (getSourceManager().isInSystemHeader(loc)) { 12020 if (!FD->hasAttr<UnavailableAttr>()) { 12021 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12022 "this system field has retaining ownership", 12023 loc)); 12024 } 12025 } else { 12026 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12027 << T->isBlockPointerType() << Record->getTagKind(); 12028 } 12029 ARCErrReported = true; 12030 } 12031 } else if (getLangOpts().ObjC1 && 12032 getLangOpts().getGC() != LangOptions::NonGC && 12033 Record && !Record->hasObjectMember()) { 12034 if (FD->getType()->isObjCObjectPointerType() || 12035 FD->getType().isObjCGCStrong()) 12036 Record->setHasObjectMember(true); 12037 else if (Context.getAsArrayType(FD->getType())) { 12038 QualType BaseType = Context.getBaseElementType(FD->getType()); 12039 if (BaseType->isRecordType() && 12040 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12041 Record->setHasObjectMember(true); 12042 else if (BaseType->isObjCObjectPointerType() || 12043 BaseType.isObjCGCStrong()) 12044 Record->setHasObjectMember(true); 12045 } 12046 } 12047 if (Record && FD->getType().isVolatileQualified()) 12048 Record->setHasVolatileMember(true); 12049 // Keep track of the number of named members. 12050 if (FD->getIdentifier()) 12051 ++NumNamedMembers; 12052 } 12053 12054 // Okay, we successfully defined 'Record'. 12055 if (Record) { 12056 bool Completed = false; 12057 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12058 if (!CXXRecord->isInvalidDecl()) { 12059 // Set access bits correctly on the directly-declared conversions. 12060 for (CXXRecordDecl::conversion_iterator 12061 I = CXXRecord->conversion_begin(), 12062 E = CXXRecord->conversion_end(); I != E; ++I) 12063 I.setAccess((*I)->getAccess()); 12064 12065 if (!CXXRecord->isDependentType()) { 12066 if (CXXRecord->hasUserDeclaredDestructor()) { 12067 // Adjust user-defined destructor exception spec. 12068 if (getLangOpts().CPlusPlus11) 12069 AdjustDestructorExceptionSpec(CXXRecord, 12070 CXXRecord->getDestructor()); 12071 } 12072 12073 // Add any implicitly-declared members to this class. 12074 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12075 12076 // If we have virtual base classes, we may end up finding multiple 12077 // final overriders for a given virtual function. Check for this 12078 // problem now. 12079 if (CXXRecord->getNumVBases()) { 12080 CXXFinalOverriderMap FinalOverriders; 12081 CXXRecord->getFinalOverriders(FinalOverriders); 12082 12083 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12084 MEnd = FinalOverriders.end(); 12085 M != MEnd; ++M) { 12086 for (OverridingMethods::iterator SO = M->second.begin(), 12087 SOEnd = M->second.end(); 12088 SO != SOEnd; ++SO) { 12089 assert(SO->second.size() > 0 && 12090 "Virtual function without overridding functions?"); 12091 if (SO->second.size() == 1) 12092 continue; 12093 12094 // C++ [class.virtual]p2: 12095 // In a derived class, if a virtual member function of a base 12096 // class subobject has more than one final overrider the 12097 // program is ill-formed. 12098 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12099 << (const NamedDecl *)M->first << Record; 12100 Diag(M->first->getLocation(), 12101 diag::note_overridden_virtual_function); 12102 for (OverridingMethods::overriding_iterator 12103 OM = SO->second.begin(), 12104 OMEnd = SO->second.end(); 12105 OM != OMEnd; ++OM) 12106 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12107 << (const NamedDecl *)M->first << OM->Method->getParent(); 12108 12109 Record->setInvalidDecl(); 12110 } 12111 } 12112 CXXRecord->completeDefinition(&FinalOverriders); 12113 Completed = true; 12114 } 12115 } 12116 } 12117 } 12118 12119 if (!Completed) 12120 Record->completeDefinition(); 12121 12122 if (Record->hasAttrs()) { 12123 CheckAlignasUnderalignment(Record); 12124 12125 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12126 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12127 IA->getRange(), IA->getBestCase(), 12128 IA->getSemanticSpelling()); 12129 } 12130 12131 // Check if the structure/union declaration is a type that can have zero 12132 // size in C. For C this is a language extension, for C++ it may cause 12133 // compatibility problems. 12134 bool CheckForZeroSize; 12135 if (!getLangOpts().CPlusPlus) { 12136 CheckForZeroSize = true; 12137 } else { 12138 // For C++ filter out types that cannot be referenced in C code. 12139 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12140 CheckForZeroSize = 12141 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12142 !CXXRecord->isDependentType() && 12143 CXXRecord->isCLike(); 12144 } 12145 if (CheckForZeroSize) { 12146 bool ZeroSize = true; 12147 bool IsEmpty = true; 12148 unsigned NonBitFields = 0; 12149 for (RecordDecl::field_iterator I = Record->field_begin(), 12150 E = Record->field_end(); 12151 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12152 IsEmpty = false; 12153 if (I->isUnnamedBitfield()) { 12154 if (I->getBitWidthValue(Context) > 0) 12155 ZeroSize = false; 12156 } else { 12157 ++NonBitFields; 12158 QualType FieldType = I->getType(); 12159 if (FieldType->isIncompleteType() || 12160 !Context.getTypeSizeInChars(FieldType).isZero()) 12161 ZeroSize = false; 12162 } 12163 } 12164 12165 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12166 // allowed in C++, but warn if its declaration is inside 12167 // extern "C" block. 12168 if (ZeroSize) { 12169 Diag(RecLoc, getLangOpts().CPlusPlus ? 12170 diag::warn_zero_size_struct_union_in_extern_c : 12171 diag::warn_zero_size_struct_union_compat) 12172 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12173 } 12174 12175 // Structs without named members are extension in C (C99 6.7.2.1p7), 12176 // but are accepted by GCC. 12177 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12178 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12179 diag::ext_no_named_members_in_struct_union) 12180 << Record->isUnion(); 12181 } 12182 } 12183 } else { 12184 ObjCIvarDecl **ClsFields = 12185 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12186 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12187 ID->setEndOfDefinitionLoc(RBrac); 12188 // Add ivar's to class's DeclContext. 12189 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12190 ClsFields[i]->setLexicalDeclContext(ID); 12191 ID->addDecl(ClsFields[i]); 12192 } 12193 // Must enforce the rule that ivars in the base classes may not be 12194 // duplicates. 12195 if (ID->getSuperClass()) 12196 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12197 } else if (ObjCImplementationDecl *IMPDecl = 12198 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12199 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12200 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12201 // Ivar declared in @implementation never belongs to the implementation. 12202 // Only it is in implementation's lexical context. 12203 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12204 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12205 IMPDecl->setIvarLBraceLoc(LBrac); 12206 IMPDecl->setIvarRBraceLoc(RBrac); 12207 } else if (ObjCCategoryDecl *CDecl = 12208 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12209 // case of ivars in class extension; all other cases have been 12210 // reported as errors elsewhere. 12211 // FIXME. Class extension does not have a LocEnd field. 12212 // CDecl->setLocEnd(RBrac); 12213 // Add ivar's to class extension's DeclContext. 12214 // Diagnose redeclaration of private ivars. 12215 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12216 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12217 if (IDecl) { 12218 if (const ObjCIvarDecl *ClsIvar = 12219 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12220 Diag(ClsFields[i]->getLocation(), 12221 diag::err_duplicate_ivar_declaration); 12222 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12223 continue; 12224 } 12225 for (ObjCInterfaceDecl::known_extensions_iterator 12226 Ext = IDecl->known_extensions_begin(), 12227 ExtEnd = IDecl->known_extensions_end(); 12228 Ext != ExtEnd; ++Ext) { 12229 if (const ObjCIvarDecl *ClsExtIvar 12230 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12231 Diag(ClsFields[i]->getLocation(), 12232 diag::err_duplicate_ivar_declaration); 12233 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12234 continue; 12235 } 12236 } 12237 } 12238 ClsFields[i]->setLexicalDeclContext(CDecl); 12239 CDecl->addDecl(ClsFields[i]); 12240 } 12241 CDecl->setIvarLBraceLoc(LBrac); 12242 CDecl->setIvarRBraceLoc(RBrac); 12243 } 12244 } 12245 12246 if (Attr) 12247 ProcessDeclAttributeList(S, Record, Attr); 12248 } 12249 12250 /// \brief Determine whether the given integral value is representable within 12251 /// the given type T. 12252 static bool isRepresentableIntegerValue(ASTContext &Context, 12253 llvm::APSInt &Value, 12254 QualType T) { 12255 assert(T->isIntegralType(Context) && "Integral type required!"); 12256 unsigned BitWidth = Context.getIntWidth(T); 12257 12258 if (Value.isUnsigned() || Value.isNonNegative()) { 12259 if (T->isSignedIntegerOrEnumerationType()) 12260 --BitWidth; 12261 return Value.getActiveBits() <= BitWidth; 12262 } 12263 return Value.getMinSignedBits() <= BitWidth; 12264 } 12265 12266 // \brief Given an integral type, return the next larger integral type 12267 // (or a NULL type of no such type exists). 12268 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12269 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12270 // enum checking below. 12271 assert(T->isIntegralType(Context) && "Integral type required!"); 12272 const unsigned NumTypes = 4; 12273 QualType SignedIntegralTypes[NumTypes] = { 12274 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12275 }; 12276 QualType UnsignedIntegralTypes[NumTypes] = { 12277 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12278 Context.UnsignedLongLongTy 12279 }; 12280 12281 unsigned BitWidth = Context.getTypeSize(T); 12282 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12283 : UnsignedIntegralTypes; 12284 for (unsigned I = 0; I != NumTypes; ++I) 12285 if (Context.getTypeSize(Types[I]) > BitWidth) 12286 return Types[I]; 12287 12288 return QualType(); 12289 } 12290 12291 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12292 EnumConstantDecl *LastEnumConst, 12293 SourceLocation IdLoc, 12294 IdentifierInfo *Id, 12295 Expr *Val) { 12296 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12297 llvm::APSInt EnumVal(IntWidth); 12298 QualType EltTy; 12299 12300 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12301 Val = 0; 12302 12303 if (Val) 12304 Val = DefaultLvalueConversion(Val).take(); 12305 12306 if (Val) { 12307 if (Enum->isDependentType() || Val->isTypeDependent()) 12308 EltTy = Context.DependentTy; 12309 else { 12310 SourceLocation ExpLoc; 12311 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12312 !getLangOpts().MSVCCompat) { 12313 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12314 // constant-expression in the enumerator-definition shall be a converted 12315 // constant expression of the underlying type. 12316 EltTy = Enum->getIntegerType(); 12317 ExprResult Converted = 12318 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12319 CCEK_Enumerator); 12320 if (Converted.isInvalid()) 12321 Val = 0; 12322 else 12323 Val = Converted.take(); 12324 } else if (!Val->isValueDependent() && 12325 !(Val = VerifyIntegerConstantExpression(Val, 12326 &EnumVal).take())) { 12327 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12328 } else { 12329 if (Enum->isFixed()) { 12330 EltTy = Enum->getIntegerType(); 12331 12332 // In Obj-C and Microsoft mode, require the enumeration value to be 12333 // representable in the underlying type of the enumeration. In C++11, 12334 // we perform a non-narrowing conversion as part of converted constant 12335 // expression checking. 12336 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12337 if (getLangOpts().MSVCCompat) { 12338 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12339 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12340 } else 12341 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12342 } else 12343 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12344 } else if (getLangOpts().CPlusPlus) { 12345 // C++11 [dcl.enum]p5: 12346 // If the underlying type is not fixed, the type of each enumerator 12347 // is the type of its initializing value: 12348 // - If an initializer is specified for an enumerator, the 12349 // initializing value has the same type as the expression. 12350 EltTy = Val->getType(); 12351 } else { 12352 // C99 6.7.2.2p2: 12353 // The expression that defines the value of an enumeration constant 12354 // shall be an integer constant expression that has a value 12355 // representable as an int. 12356 12357 // Complain if the value is not representable in an int. 12358 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12359 Diag(IdLoc, diag::ext_enum_value_not_int) 12360 << EnumVal.toString(10) << Val->getSourceRange() 12361 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12362 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12363 // Force the type of the expression to 'int'. 12364 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12365 } 12366 EltTy = Val->getType(); 12367 } 12368 } 12369 } 12370 } 12371 12372 if (!Val) { 12373 if (Enum->isDependentType()) 12374 EltTy = Context.DependentTy; 12375 else if (!LastEnumConst) { 12376 // C++0x [dcl.enum]p5: 12377 // If the underlying type is not fixed, the type of each enumerator 12378 // is the type of its initializing value: 12379 // - If no initializer is specified for the first enumerator, the 12380 // initializing value has an unspecified integral type. 12381 // 12382 // GCC uses 'int' for its unspecified integral type, as does 12383 // C99 6.7.2.2p3. 12384 if (Enum->isFixed()) { 12385 EltTy = Enum->getIntegerType(); 12386 } 12387 else { 12388 EltTy = Context.IntTy; 12389 } 12390 } else { 12391 // Assign the last value + 1. 12392 EnumVal = LastEnumConst->getInitVal(); 12393 ++EnumVal; 12394 EltTy = LastEnumConst->getType(); 12395 12396 // Check for overflow on increment. 12397 if (EnumVal < LastEnumConst->getInitVal()) { 12398 // C++0x [dcl.enum]p5: 12399 // If the underlying type is not fixed, the type of each enumerator 12400 // is the type of its initializing value: 12401 // 12402 // - Otherwise the type of the initializing value is the same as 12403 // the type of the initializing value of the preceding enumerator 12404 // unless the incremented value is not representable in that type, 12405 // in which case the type is an unspecified integral type 12406 // sufficient to contain the incremented value. If no such type 12407 // exists, the program is ill-formed. 12408 QualType T = getNextLargerIntegralType(Context, EltTy); 12409 if (T.isNull() || Enum->isFixed()) { 12410 // There is no integral type larger enough to represent this 12411 // value. Complain, then allow the value to wrap around. 12412 EnumVal = LastEnumConst->getInitVal(); 12413 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12414 ++EnumVal; 12415 if (Enum->isFixed()) 12416 // When the underlying type is fixed, this is ill-formed. 12417 Diag(IdLoc, diag::err_enumerator_wrapped) 12418 << EnumVal.toString(10) 12419 << EltTy; 12420 else 12421 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 12422 << EnumVal.toString(10); 12423 } else { 12424 EltTy = T; 12425 } 12426 12427 // Retrieve the last enumerator's value, extent that type to the 12428 // type that is supposed to be large enough to represent the incremented 12429 // value, then increment. 12430 EnumVal = LastEnumConst->getInitVal(); 12431 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12432 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12433 ++EnumVal; 12434 12435 // If we're not in C++, diagnose the overflow of enumerator values, 12436 // which in C99 means that the enumerator value is not representable in 12437 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12438 // permits enumerator values that are representable in some larger 12439 // integral type. 12440 if (!getLangOpts().CPlusPlus && !T.isNull()) 12441 Diag(IdLoc, diag::warn_enum_value_overflow); 12442 } else if (!getLangOpts().CPlusPlus && 12443 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12444 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12445 Diag(IdLoc, diag::ext_enum_value_not_int) 12446 << EnumVal.toString(10) << 1; 12447 } 12448 } 12449 } 12450 12451 if (!EltTy->isDependentType()) { 12452 // Make the enumerator value match the signedness and size of the 12453 // enumerator's type. 12454 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12455 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12456 } 12457 12458 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12459 Val, EnumVal); 12460 } 12461 12462 12463 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12464 SourceLocation IdLoc, IdentifierInfo *Id, 12465 AttributeList *Attr, 12466 SourceLocation EqualLoc, Expr *Val) { 12467 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12468 EnumConstantDecl *LastEnumConst = 12469 cast_or_null<EnumConstantDecl>(lastEnumConst); 12470 12471 // The scope passed in may not be a decl scope. Zip up the scope tree until 12472 // we find one that is. 12473 S = getNonFieldDeclScope(S); 12474 12475 // Verify that there isn't already something declared with this name in this 12476 // scope. 12477 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12478 ForRedeclaration); 12479 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12480 // Maybe we will complain about the shadowed template parameter. 12481 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12482 // Just pretend that we didn't see the previous declaration. 12483 PrevDecl = 0; 12484 } 12485 12486 if (PrevDecl) { 12487 // When in C++, we may get a TagDecl with the same name; in this case the 12488 // enum constant will 'hide' the tag. 12489 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12490 "Received TagDecl when not in C++!"); 12491 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12492 if (isa<EnumConstantDecl>(PrevDecl)) 12493 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12494 else 12495 Diag(IdLoc, diag::err_redefinition) << Id; 12496 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12497 return 0; 12498 } 12499 } 12500 12501 // C++ [class.mem]p15: 12502 // If T is the name of a class, then each of the following shall have a name 12503 // different from T: 12504 // - every enumerator of every member of class T that is an unscoped 12505 // enumerated type 12506 if (CXXRecordDecl *Record 12507 = dyn_cast<CXXRecordDecl>( 12508 TheEnumDecl->getDeclContext()->getRedeclContext())) 12509 if (!TheEnumDecl->isScoped() && 12510 Record->getIdentifier() && Record->getIdentifier() == Id) 12511 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12512 12513 EnumConstantDecl *New = 12514 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12515 12516 if (New) { 12517 // Process attributes. 12518 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12519 12520 // Register this decl in the current scope stack. 12521 New->setAccess(TheEnumDecl->getAccess()); 12522 PushOnScopeChains(New, S); 12523 } 12524 12525 ActOnDocumentableDecl(New); 12526 12527 return New; 12528 } 12529 12530 // Returns true when the enum initial expression does not trigger the 12531 // duplicate enum warning. A few common cases are exempted as follows: 12532 // Element2 = Element1 12533 // Element2 = Element1 + 1 12534 // Element2 = Element1 - 1 12535 // Where Element2 and Element1 are from the same enum. 12536 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12537 Expr *InitExpr = ECD->getInitExpr(); 12538 if (!InitExpr) 12539 return true; 12540 InitExpr = InitExpr->IgnoreImpCasts(); 12541 12542 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12543 if (!BO->isAdditiveOp()) 12544 return true; 12545 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12546 if (!IL) 12547 return true; 12548 if (IL->getValue() != 1) 12549 return true; 12550 12551 InitExpr = BO->getLHS(); 12552 } 12553 12554 // This checks if the elements are from the same enum. 12555 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12556 if (!DRE) 12557 return true; 12558 12559 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12560 if (!EnumConstant) 12561 return true; 12562 12563 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12564 Enum) 12565 return true; 12566 12567 return false; 12568 } 12569 12570 struct DupKey { 12571 int64_t val; 12572 bool isTombstoneOrEmptyKey; 12573 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12574 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12575 }; 12576 12577 static DupKey GetDupKey(const llvm::APSInt& Val) { 12578 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12579 false); 12580 } 12581 12582 struct DenseMapInfoDupKey { 12583 static DupKey getEmptyKey() { return DupKey(0, true); } 12584 static DupKey getTombstoneKey() { return DupKey(1, true); } 12585 static unsigned getHashValue(const DupKey Key) { 12586 return (unsigned)(Key.val * 37); 12587 } 12588 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12589 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12590 LHS.val == RHS.val; 12591 } 12592 }; 12593 12594 // Emits a warning when an element is implicitly set a value that 12595 // a previous element has already been set to. 12596 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12597 EnumDecl *Enum, 12598 QualType EnumType) { 12599 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12600 Enum->getLocation()) == 12601 DiagnosticsEngine::Ignored) 12602 return; 12603 // Avoid anonymous enums 12604 if (!Enum->getIdentifier()) 12605 return; 12606 12607 // Only check for small enums. 12608 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12609 return; 12610 12611 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12612 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12613 12614 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12615 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12616 ValueToVectorMap; 12617 12618 DuplicatesVector DupVector; 12619 ValueToVectorMap EnumMap; 12620 12621 // Populate the EnumMap with all values represented by enum constants without 12622 // an initialier. 12623 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12624 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12625 12626 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12627 // this constant. Skip this enum since it may be ill-formed. 12628 if (!ECD) { 12629 return; 12630 } 12631 12632 if (ECD->getInitExpr()) 12633 continue; 12634 12635 DupKey Key = GetDupKey(ECD->getInitVal()); 12636 DeclOrVector &Entry = EnumMap[Key]; 12637 12638 // First time encountering this value. 12639 if (Entry.isNull()) 12640 Entry = ECD; 12641 } 12642 12643 // Create vectors for any values that has duplicates. 12644 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12645 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12646 if (!ValidDuplicateEnum(ECD, Enum)) 12647 continue; 12648 12649 DupKey Key = GetDupKey(ECD->getInitVal()); 12650 12651 DeclOrVector& Entry = EnumMap[Key]; 12652 if (Entry.isNull()) 12653 continue; 12654 12655 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12656 // Ensure constants are different. 12657 if (D == ECD) 12658 continue; 12659 12660 // Create new vector and push values onto it. 12661 ECDVector *Vec = new ECDVector(); 12662 Vec->push_back(D); 12663 Vec->push_back(ECD); 12664 12665 // Update entry to point to the duplicates vector. 12666 Entry = Vec; 12667 12668 // Store the vector somewhere we can consult later for quick emission of 12669 // diagnostics. 12670 DupVector.push_back(Vec); 12671 continue; 12672 } 12673 12674 ECDVector *Vec = Entry.get<ECDVector*>(); 12675 // Make sure constants are not added more than once. 12676 if (*Vec->begin() == ECD) 12677 continue; 12678 12679 Vec->push_back(ECD); 12680 } 12681 12682 // Emit diagnostics. 12683 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12684 DupVectorEnd = DupVector.end(); 12685 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12686 ECDVector *Vec = *DupVectorIter; 12687 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12688 12689 // Emit warning for one enum constant. 12690 ECDVector::iterator I = Vec->begin(); 12691 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12692 << (*I)->getName() << (*I)->getInitVal().toString(10) 12693 << (*I)->getSourceRange(); 12694 ++I; 12695 12696 // Emit one note for each of the remaining enum constants with 12697 // the same value. 12698 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12699 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12700 << (*I)->getName() << (*I)->getInitVal().toString(10) 12701 << (*I)->getSourceRange(); 12702 delete Vec; 12703 } 12704 } 12705 12706 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12707 SourceLocation RBraceLoc, Decl *EnumDeclX, 12708 ArrayRef<Decl *> Elements, 12709 Scope *S, AttributeList *Attr) { 12710 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12711 QualType EnumType = Context.getTypeDeclType(Enum); 12712 12713 if (Attr) 12714 ProcessDeclAttributeList(S, Enum, Attr); 12715 12716 if (Enum->isDependentType()) { 12717 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12718 EnumConstantDecl *ECD = 12719 cast_or_null<EnumConstantDecl>(Elements[i]); 12720 if (!ECD) continue; 12721 12722 ECD->setType(EnumType); 12723 } 12724 12725 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12726 return; 12727 } 12728 12729 // TODO: If the result value doesn't fit in an int, it must be a long or long 12730 // long value. ISO C does not support this, but GCC does as an extension, 12731 // emit a warning. 12732 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12733 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12734 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12735 12736 // Verify that all the values are okay, compute the size of the values, and 12737 // reverse the list. 12738 unsigned NumNegativeBits = 0; 12739 unsigned NumPositiveBits = 0; 12740 12741 // Keep track of whether all elements have type int. 12742 bool AllElementsInt = true; 12743 12744 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12745 EnumConstantDecl *ECD = 12746 cast_or_null<EnumConstantDecl>(Elements[i]); 12747 if (!ECD) continue; // Already issued a diagnostic. 12748 12749 const llvm::APSInt &InitVal = ECD->getInitVal(); 12750 12751 // Keep track of the size of positive and negative values. 12752 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12753 NumPositiveBits = std::max(NumPositiveBits, 12754 (unsigned)InitVal.getActiveBits()); 12755 else 12756 NumNegativeBits = std::max(NumNegativeBits, 12757 (unsigned)InitVal.getMinSignedBits()); 12758 12759 // Keep track of whether every enum element has type int (very commmon). 12760 if (AllElementsInt) 12761 AllElementsInt = ECD->getType() == Context.IntTy; 12762 } 12763 12764 // Figure out the type that should be used for this enum. 12765 QualType BestType; 12766 unsigned BestWidth; 12767 12768 // C++0x N3000 [conv.prom]p3: 12769 // An rvalue of an unscoped enumeration type whose underlying 12770 // type is not fixed can be converted to an rvalue of the first 12771 // of the following types that can represent all the values of 12772 // the enumeration: int, unsigned int, long int, unsigned long 12773 // int, long long int, or unsigned long long int. 12774 // C99 6.4.4.3p2: 12775 // An identifier declared as an enumeration constant has type int. 12776 // The C99 rule is modified by a gcc extension 12777 QualType BestPromotionType; 12778 12779 bool Packed = Enum->hasAttr<PackedAttr>(); 12780 // -fshort-enums is the equivalent to specifying the packed attribute on all 12781 // enum definitions. 12782 if (LangOpts.ShortEnums) 12783 Packed = true; 12784 12785 if (Enum->isFixed()) { 12786 BestType = Enum->getIntegerType(); 12787 if (BestType->isPromotableIntegerType()) 12788 BestPromotionType = Context.getPromotedIntegerType(BestType); 12789 else 12790 BestPromotionType = BestType; 12791 // We don't need to set BestWidth, because BestType is going to be the type 12792 // of the enumerators, but we do anyway because otherwise some compilers 12793 // warn that it might be used uninitialized. 12794 BestWidth = CharWidth; 12795 } 12796 else if (NumNegativeBits) { 12797 // If there is a negative value, figure out the smallest integer type (of 12798 // int/long/longlong) that fits. 12799 // If it's packed, check also if it fits a char or a short. 12800 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12801 BestType = Context.SignedCharTy; 12802 BestWidth = CharWidth; 12803 } else if (Packed && NumNegativeBits <= ShortWidth && 12804 NumPositiveBits < ShortWidth) { 12805 BestType = Context.ShortTy; 12806 BestWidth = ShortWidth; 12807 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12808 BestType = Context.IntTy; 12809 BestWidth = IntWidth; 12810 } else { 12811 BestWidth = Context.getTargetInfo().getLongWidth(); 12812 12813 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12814 BestType = Context.LongTy; 12815 } else { 12816 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12817 12818 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12819 Diag(Enum->getLocation(), diag::ext_enum_too_large); 12820 BestType = Context.LongLongTy; 12821 } 12822 } 12823 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12824 } else { 12825 // If there is no negative value, figure out the smallest type that fits 12826 // all of the enumerator values. 12827 // If it's packed, check also if it fits a char or a short. 12828 if (Packed && NumPositiveBits <= CharWidth) { 12829 BestType = Context.UnsignedCharTy; 12830 BestPromotionType = Context.IntTy; 12831 BestWidth = CharWidth; 12832 } else if (Packed && NumPositiveBits <= ShortWidth) { 12833 BestType = Context.UnsignedShortTy; 12834 BestPromotionType = Context.IntTy; 12835 BestWidth = ShortWidth; 12836 } else if (NumPositiveBits <= IntWidth) { 12837 BestType = Context.UnsignedIntTy; 12838 BestWidth = IntWidth; 12839 BestPromotionType 12840 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12841 ? Context.UnsignedIntTy : Context.IntTy; 12842 } else if (NumPositiveBits <= 12843 (BestWidth = Context.getTargetInfo().getLongWidth())) { 12844 BestType = Context.UnsignedLongTy; 12845 BestPromotionType 12846 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12847 ? Context.UnsignedLongTy : Context.LongTy; 12848 } else { 12849 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12850 assert(NumPositiveBits <= BestWidth && 12851 "How could an initializer get larger than ULL?"); 12852 BestType = Context.UnsignedLongLongTy; 12853 BestPromotionType 12854 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 12855 ? Context.UnsignedLongLongTy : Context.LongLongTy; 12856 } 12857 } 12858 12859 // Loop over all of the enumerator constants, changing their types to match 12860 // the type of the enum if needed. 12861 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12862 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12863 if (!ECD) continue; // Already issued a diagnostic. 12864 12865 // Standard C says the enumerators have int type, but we allow, as an 12866 // extension, the enumerators to be larger than int size. If each 12867 // enumerator value fits in an int, type it as an int, otherwise type it the 12868 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 12869 // that X has type 'int', not 'unsigned'. 12870 12871 // Determine whether the value fits into an int. 12872 llvm::APSInt InitVal = ECD->getInitVal(); 12873 12874 // If it fits into an integer type, force it. Otherwise force it to match 12875 // the enum decl type. 12876 QualType NewTy; 12877 unsigned NewWidth; 12878 bool NewSign; 12879 if (!getLangOpts().CPlusPlus && 12880 !Enum->isFixed() && 12881 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 12882 NewTy = Context.IntTy; 12883 NewWidth = IntWidth; 12884 NewSign = true; 12885 } else if (ECD->getType() == BestType) { 12886 // Already the right type! 12887 if (getLangOpts().CPlusPlus) 12888 // C++ [dcl.enum]p4: Following the closing brace of an 12889 // enum-specifier, each enumerator has the type of its 12890 // enumeration. 12891 ECD->setType(EnumType); 12892 continue; 12893 } else { 12894 NewTy = BestType; 12895 NewWidth = BestWidth; 12896 NewSign = BestType->isSignedIntegerOrEnumerationType(); 12897 } 12898 12899 // Adjust the APSInt value. 12900 InitVal = InitVal.extOrTrunc(NewWidth); 12901 InitVal.setIsSigned(NewSign); 12902 ECD->setInitVal(InitVal); 12903 12904 // Adjust the Expr initializer and type. 12905 if (ECD->getInitExpr() && 12906 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 12907 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 12908 CK_IntegralCast, 12909 ECD->getInitExpr(), 12910 /*base paths*/ 0, 12911 VK_RValue)); 12912 if (getLangOpts().CPlusPlus) 12913 // C++ [dcl.enum]p4: Following the closing brace of an 12914 // enum-specifier, each enumerator has the type of its 12915 // enumeration. 12916 ECD->setType(EnumType); 12917 else 12918 ECD->setType(NewTy); 12919 } 12920 12921 Enum->completeDefinition(BestType, BestPromotionType, 12922 NumPositiveBits, NumNegativeBits); 12923 12924 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 12925 12926 // Now that the enum type is defined, ensure it's not been underaligned. 12927 if (Enum->hasAttrs()) 12928 CheckAlignasUnderalignment(Enum); 12929 } 12930 12931 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 12932 SourceLocation StartLoc, 12933 SourceLocation EndLoc) { 12934 StringLiteral *AsmString = cast<StringLiteral>(expr); 12935 12936 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 12937 AsmString, StartLoc, 12938 EndLoc); 12939 CurContext->addDecl(New); 12940 return New; 12941 } 12942 12943 static void checkModuleImportContext(Sema &S, Module *M, 12944 SourceLocation ImportLoc, 12945 DeclContext *DC) { 12946 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 12947 switch (LSD->getLanguage()) { 12948 case LinkageSpecDecl::lang_c: 12949 if (!M->IsExternC) { 12950 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 12951 << M->getFullModuleName(); 12952 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 12953 return; 12954 } 12955 break; 12956 case LinkageSpecDecl::lang_cxx: 12957 break; 12958 } 12959 DC = LSD->getParent(); 12960 } 12961 12962 while (isa<LinkageSpecDecl>(DC)) 12963 DC = DC->getParent(); 12964 if (!isa<TranslationUnitDecl>(DC)) { 12965 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 12966 << M->getFullModuleName() << DC; 12967 S.Diag(cast<Decl>(DC)->getLocStart(), 12968 diag::note_module_import_not_at_top_level) 12969 << DC; 12970 } 12971 } 12972 12973 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 12974 SourceLocation ImportLoc, 12975 ModuleIdPath Path) { 12976 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 12977 Module::AllVisible, 12978 /*IsIncludeDirective=*/false); 12979 if (!Mod) 12980 return true; 12981 12982 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 12983 12984 SmallVector<SourceLocation, 2> IdentifierLocs; 12985 Module *ModCheck = Mod; 12986 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 12987 // If we've run out of module parents, just drop the remaining identifiers. 12988 // We need the length to be consistent. 12989 if (!ModCheck) 12990 break; 12991 ModCheck = ModCheck->Parent; 12992 12993 IdentifierLocs.push_back(Path[I].second); 12994 } 12995 12996 ImportDecl *Import = ImportDecl::Create(Context, 12997 Context.getTranslationUnitDecl(), 12998 AtLoc.isValid()? AtLoc : ImportLoc, 12999 Mod, IdentifierLocs); 13000 Context.getTranslationUnitDecl()->addDecl(Import); 13001 return Import; 13002 } 13003 13004 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13005 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13006 13007 // FIXME: Should we synthesize an ImportDecl here? 13008 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13009 /*Complain=*/true); 13010 } 13011 13012 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 13013 // Create the implicit import declaration. 13014 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13015 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13016 Loc, Mod, Loc); 13017 TU->addDecl(ImportD); 13018 Consumer.HandleImplicitImportDecl(ImportD); 13019 13020 // Make the module visible. 13021 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13022 /*Complain=*/false); 13023 } 13024 13025 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13026 IdentifierInfo* AliasName, 13027 SourceLocation PragmaLoc, 13028 SourceLocation NameLoc, 13029 SourceLocation AliasNameLoc) { 13030 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13031 LookupOrdinaryName); 13032 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13033 AliasName->getName(), 0); 13034 13035 if (PrevDecl) 13036 PrevDecl->addAttr(Attr); 13037 else 13038 (void)ExtnameUndeclaredIdentifiers.insert( 13039 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13040 } 13041 13042 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13043 SourceLocation PragmaLoc, 13044 SourceLocation NameLoc) { 13045 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13046 13047 if (PrevDecl) { 13048 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13049 } else { 13050 (void)WeakUndeclaredIdentifiers.insert( 13051 std::pair<IdentifierInfo*,WeakInfo> 13052 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 13053 } 13054 } 13055 13056 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13057 IdentifierInfo* AliasName, 13058 SourceLocation PragmaLoc, 13059 SourceLocation NameLoc, 13060 SourceLocation AliasNameLoc) { 13061 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13062 LookupOrdinaryName); 13063 WeakInfo W = WeakInfo(Name, NameLoc); 13064 13065 if (PrevDecl) { 13066 if (!PrevDecl->hasAttr<AliasAttr>()) 13067 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13068 DeclApplyPragmaWeak(TUScope, ND, W); 13069 } else { 13070 (void)WeakUndeclaredIdentifiers.insert( 13071 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13072 } 13073 } 13074 13075 Decl *Sema::getObjCDeclContext() const { 13076 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13077 } 13078 13079 AvailabilityResult Sema::getCurContextAvailability() const { 13080 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13081 // If we are within an Objective-C method, we should consult 13082 // both the availability of the method as well as the 13083 // enclosing class. If the class is (say) deprecated, 13084 // the entire method is considered deprecated from the 13085 // purpose of checking if the current context is deprecated. 13086 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13087 AvailabilityResult R = MD->getAvailability(); 13088 if (R != AR_Available) 13089 return R; 13090 D = MD->getClassInterface(); 13091 } 13092 // If we are within an Objective-c @implementation, it 13093 // gets the same availability context as the @interface. 13094 else if (const ObjCImplementationDecl *ID = 13095 dyn_cast<ObjCImplementationDecl>(D)) { 13096 D = ID->getClassInterface(); 13097 } 13098 return D->getAvailability(); 13099 } 13100