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 bool ValidateCandidate(const TypoCorrection &candidate) override { 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 (const auto &Base : RD->bases()) 390 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 391 return true; 392 return S->isFunctionPrototypeScope(); 393 } 394 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 395 } 396 397 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 398 SourceLocation IILoc, 399 Scope *S, 400 CXXScopeSpec *SS, 401 ParsedType &SuggestedType, 402 bool AllowClassTemplates) { 403 // We don't have anything to suggest (yet). 404 SuggestedType = ParsedType(); 405 406 // There may have been a typo in the name of the type. Look up typo 407 // results, in case we have something that we can suggest. 408 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 409 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 410 LookupOrdinaryName, S, SS, 411 Validator)) { 412 if (Corrected.isKeyword()) { 413 // We corrected to a keyword. 414 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 415 II = Corrected.getCorrectionAsIdentifierInfo(); 416 } else { 417 // We found a similarly-named type or interface; suggest that. 418 if (!SS || !SS->isSet()) { 419 diagnoseTypo(Corrected, 420 PDiag(diag::err_unknown_typename_suggest) << II); 421 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 422 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 423 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 424 II->getName().equals(CorrectedStr); 425 diagnoseTypo(Corrected, 426 PDiag(diag::err_unknown_nested_typename_suggest) 427 << II << DC << DroppedSpecifier << SS->getRange()); 428 } else { 429 llvm_unreachable("could not have corrected a typo here"); 430 } 431 432 CXXScopeSpec tmpSS; 433 if (Corrected.getCorrectionSpecifier()) 434 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 435 SourceRange(IILoc)); 436 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 437 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 438 false, ParsedType(), 439 /*IsCtorOrDtorName=*/false, 440 /*NonTrivialTypeSourceInfo=*/true); 441 } 442 return true; 443 } 444 445 if (getLangOpts().CPlusPlus) { 446 // See if II is a class template that the user forgot to pass arguments to. 447 UnqualifiedId Name; 448 Name.setIdentifier(II, IILoc); 449 CXXScopeSpec EmptySS; 450 TemplateTy TemplateResult; 451 bool MemberOfUnknownSpecialization; 452 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 453 Name, ParsedType(), true, TemplateResult, 454 MemberOfUnknownSpecialization) == TNK_Type_template) { 455 TemplateName TplName = TemplateResult.get(); 456 Diag(IILoc, diag::err_template_missing_args) << TplName; 457 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 458 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 459 << TplDecl->getTemplateParameters()->getSourceRange(); 460 } 461 return true; 462 } 463 } 464 465 // FIXME: Should we move the logic that tries to recover from a missing tag 466 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 467 468 if (!SS || (!SS->isSet() && !SS->isInvalid())) 469 Diag(IILoc, diag::err_unknown_typename) << II; 470 else if (DeclContext *DC = computeDeclContext(*SS, false)) 471 Diag(IILoc, diag::err_typename_nested_not_found) 472 << II << DC << SS->getRange(); 473 else if (isDependentScopeSpecifier(*SS)) { 474 unsigned DiagID = diag::err_typename_missing; 475 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 476 DiagID = diag::warn_typename_missing; 477 478 Diag(SS->getRange().getBegin(), DiagID) 479 << SS->getScopeRep() << II->getName() 480 << SourceRange(SS->getRange().getBegin(), IILoc) 481 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 482 SuggestedType = ActOnTypenameType(S, SourceLocation(), 483 *SS, *II, IILoc).get(); 484 } else { 485 assert(SS && SS->isInvalid() && 486 "Invalid scope specifier has already been diagnosed"); 487 } 488 489 return true; 490 } 491 492 /// \brief Determine whether the given result set contains either a type name 493 /// or 494 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 495 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 496 NextToken.is(tok::less); 497 498 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 499 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 500 return true; 501 502 if (CheckTemplate && isa<TemplateDecl>(*I)) 503 return true; 504 } 505 506 return false; 507 } 508 509 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 510 Scope *S, CXXScopeSpec &SS, 511 IdentifierInfo *&Name, 512 SourceLocation NameLoc) { 513 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 514 SemaRef.LookupParsedName(R, S, &SS); 515 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 516 const char *TagName = 0; 517 const char *FixItTagName = 0; 518 switch (Tag->getTagKind()) { 519 case TTK_Class: 520 TagName = "class"; 521 FixItTagName = "class "; 522 break; 523 524 case TTK_Enum: 525 TagName = "enum"; 526 FixItTagName = "enum "; 527 break; 528 529 case TTK_Struct: 530 TagName = "struct"; 531 FixItTagName = "struct "; 532 break; 533 534 case TTK_Interface: 535 TagName = "__interface"; 536 FixItTagName = "__interface "; 537 break; 538 539 case TTK_Union: 540 TagName = "union"; 541 FixItTagName = "union "; 542 break; 543 } 544 545 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 546 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 547 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 548 549 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 550 I != IEnd; ++I) 551 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 552 << Name << TagName; 553 554 // Replace lookup results with just the tag decl. 555 Result.clear(Sema::LookupTagName); 556 SemaRef.LookupParsedName(Result, S, &SS); 557 return true; 558 } 559 560 return false; 561 } 562 563 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 564 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 565 QualType T, SourceLocation NameLoc) { 566 ASTContext &Context = S.Context; 567 568 TypeLocBuilder Builder; 569 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 570 571 T = S.getElaboratedType(ETK_None, SS, T); 572 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 573 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 574 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 575 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 576 } 577 578 Sema::NameClassification Sema::ClassifyName(Scope *S, 579 CXXScopeSpec &SS, 580 IdentifierInfo *&Name, 581 SourceLocation NameLoc, 582 const Token &NextToken, 583 bool IsAddressOfOperand, 584 CorrectionCandidateCallback *CCC) { 585 DeclarationNameInfo NameInfo(Name, NameLoc); 586 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 587 588 if (NextToken.is(tok::coloncolon)) { 589 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 590 QualType(), false, SS, 0, false); 591 592 } 593 594 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 595 LookupParsedName(Result, S, &SS, !CurMethod); 596 597 // Perform lookup for Objective-C instance variables (including automatically 598 // synthesized instance variables), if we're in an Objective-C method. 599 // FIXME: This lookup really, really needs to be folded in to the normal 600 // unqualified lookup mechanism. 601 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 602 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 603 if (E.get() || E.isInvalid()) 604 return E; 605 } 606 607 bool SecondTry = false; 608 bool IsFilteredTemplateName = false; 609 610 Corrected: 611 switch (Result.getResultKind()) { 612 case LookupResult::NotFound: 613 // If an unqualified-id is followed by a '(', then we have a function 614 // call. 615 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 616 // In C++, this is an ADL-only call. 617 // FIXME: Reference? 618 if (getLangOpts().CPlusPlus) 619 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 620 621 // C90 6.3.2.2: 622 // If the expression that precedes the parenthesized argument list in a 623 // function call consists solely of an identifier, and if no 624 // declaration is visible for this identifier, the identifier is 625 // implicitly declared exactly as if, in the innermost block containing 626 // the function call, the declaration 627 // 628 // extern int identifier (); 629 // 630 // appeared. 631 // 632 // We also allow this in C99 as an extension. 633 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 634 Result.addDecl(D); 635 Result.resolveKind(); 636 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 637 } 638 } 639 640 // In C, we first see whether there is a tag type by the same name, in 641 // which case it's likely that the user just forget to write "enum", 642 // "struct", or "union". 643 if (!getLangOpts().CPlusPlus && !SecondTry && 644 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 645 break; 646 } 647 648 // Perform typo correction to determine if there is another name that is 649 // close to this name. 650 if (!SecondTry && CCC) { 651 SecondTry = true; 652 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 653 Result.getLookupKind(), S, 654 &SS, *CCC)) { 655 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 656 unsigned QualifiedDiag = diag::err_no_member_suggest; 657 658 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 659 NamedDecl *UnderlyingFirstDecl 660 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 661 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 662 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 663 UnqualifiedDiag = diag::err_no_template_suggest; 664 QualifiedDiag = diag::err_no_member_template_suggest; 665 } else if (UnderlyingFirstDecl && 666 (isa<TypeDecl>(UnderlyingFirstDecl) || 667 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 668 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 669 UnqualifiedDiag = diag::err_unknown_typename_suggest; 670 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 671 } 672 673 if (SS.isEmpty()) { 674 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 675 } else {// FIXME: is this even reachable? Test it. 676 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 677 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 678 Name->getName().equals(CorrectedStr); 679 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 680 << Name << computeDeclContext(SS, false) 681 << DroppedSpecifier << SS.getRange()); 682 } 683 684 // Update the name, so that the caller has the new name. 685 Name = Corrected.getCorrectionAsIdentifierInfo(); 686 687 // Typo correction corrected to a keyword. 688 if (Corrected.isKeyword()) 689 return Name; 690 691 // Also update the LookupResult... 692 // FIXME: This should probably go away at some point 693 Result.clear(); 694 Result.setLookupName(Corrected.getCorrection()); 695 if (FirstDecl) 696 Result.addDecl(FirstDecl); 697 698 // If we found an Objective-C instance variable, let 699 // LookupInObjCMethod build the appropriate expression to 700 // reference the ivar. 701 // FIXME: This is a gross hack. 702 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 703 Result.clear(); 704 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 705 return E; 706 } 707 708 goto Corrected; 709 } 710 } 711 712 // We failed to correct; just fall through and let the parser deal with it. 713 Result.suppressDiagnostics(); 714 return NameClassification::Unknown(); 715 716 case LookupResult::NotFoundInCurrentInstantiation: { 717 // We performed name lookup into the current instantiation, and there were 718 // dependent bases, so we treat this result the same way as any other 719 // dependent nested-name-specifier. 720 721 // C++ [temp.res]p2: 722 // A name used in a template declaration or definition and that is 723 // dependent on a template-parameter is assumed not to name a type 724 // unless the applicable name lookup finds a type name or the name is 725 // qualified by the keyword typename. 726 // 727 // FIXME: If the next token is '<', we might want to ask the parser to 728 // perform some heroics to see if we actually have a 729 // template-argument-list, which would indicate a missing 'template' 730 // keyword here. 731 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 732 NameInfo, IsAddressOfOperand, 733 /*TemplateArgs=*/0); 734 } 735 736 case LookupResult::Found: 737 case LookupResult::FoundOverloaded: 738 case LookupResult::FoundUnresolvedValue: 739 break; 740 741 case LookupResult::Ambiguous: 742 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 743 hasAnyAcceptableTemplateNames(Result)) { 744 // C++ [temp.local]p3: 745 // A lookup that finds an injected-class-name (10.2) can result in an 746 // ambiguity in certain cases (for example, if it is found in more than 747 // one base class). If all of the injected-class-names that are found 748 // refer to specializations of the same class template, and if the name 749 // is followed by a template-argument-list, the reference refers to the 750 // class template itself and not a specialization thereof, and is not 751 // ambiguous. 752 // 753 // This filtering can make an ambiguous result into an unambiguous one, 754 // so try again after filtering out template names. 755 FilterAcceptableTemplateNames(Result); 756 if (!Result.isAmbiguous()) { 757 IsFilteredTemplateName = true; 758 break; 759 } 760 } 761 762 // Diagnose the ambiguity and return an error. 763 return NameClassification::Error(); 764 } 765 766 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 767 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 768 // C++ [temp.names]p3: 769 // After name lookup (3.4) finds that a name is a template-name or that 770 // an operator-function-id or a literal- operator-id refers to a set of 771 // overloaded functions any member of which is a function template if 772 // this is followed by a <, the < is always taken as the delimiter of a 773 // template-argument-list and never as the less-than operator. 774 if (!IsFilteredTemplateName) 775 FilterAcceptableTemplateNames(Result); 776 777 if (!Result.empty()) { 778 bool IsFunctionTemplate; 779 bool IsVarTemplate; 780 TemplateName Template; 781 if (Result.end() - Result.begin() > 1) { 782 IsFunctionTemplate = true; 783 Template = Context.getOverloadedTemplateName(Result.begin(), 784 Result.end()); 785 } else { 786 TemplateDecl *TD 787 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 788 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 789 IsVarTemplate = isa<VarTemplateDecl>(TD); 790 791 if (SS.isSet() && !SS.isInvalid()) 792 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 793 /*TemplateKeyword=*/false, 794 TD); 795 else 796 Template = TemplateName(TD); 797 } 798 799 if (IsFunctionTemplate) { 800 // Function templates always go through overload resolution, at which 801 // point we'll perform the various checks (e.g., accessibility) we need 802 // to based on which function we selected. 803 Result.suppressDiagnostics(); 804 805 return NameClassification::FunctionTemplate(Template); 806 } 807 808 return IsVarTemplate ? NameClassification::VarTemplate(Template) 809 : NameClassification::TypeTemplate(Template); 810 } 811 } 812 813 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 814 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 815 DiagnoseUseOfDecl(Type, NameLoc); 816 QualType T = Context.getTypeDeclType(Type); 817 if (SS.isNotEmpty()) 818 return buildNestedType(*this, SS, T, NameLoc); 819 return ParsedType::make(T); 820 } 821 822 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 823 if (!Class) { 824 // FIXME: It's unfortunate that we don't have a Type node for handling this. 825 if (ObjCCompatibleAliasDecl *Alias 826 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 827 Class = Alias->getClassInterface(); 828 } 829 830 if (Class) { 831 DiagnoseUseOfDecl(Class, NameLoc); 832 833 if (NextToken.is(tok::period)) { 834 // Interface. <something> is parsed as a property reference expression. 835 // Just return "unknown" as a fall-through for now. 836 Result.suppressDiagnostics(); 837 return NameClassification::Unknown(); 838 } 839 840 QualType T = Context.getObjCInterfaceType(Class); 841 return ParsedType::make(T); 842 } 843 844 // We can have a type template here if we're classifying a template argument. 845 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 846 return NameClassification::TypeTemplate( 847 TemplateName(cast<TemplateDecl>(FirstDecl))); 848 849 // Check for a tag type hidden by a non-type decl in a few cases where it 850 // seems likely a type is wanted instead of the non-type that was found. 851 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 852 if ((NextToken.is(tok::identifier) || 853 (NextIsOp && 854 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 855 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 856 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 857 DiagnoseUseOfDecl(Type, NameLoc); 858 QualType T = Context.getTypeDeclType(Type); 859 if (SS.isNotEmpty()) 860 return buildNestedType(*this, SS, T, NameLoc); 861 return ParsedType::make(T); 862 } 863 864 if (FirstDecl->isCXXClassMember()) 865 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 866 867 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 868 return BuildDeclarationNameExpr(SS, Result, ADL); 869 } 870 871 // Determines the context to return to after temporarily entering a 872 // context. This depends in an unnecessarily complicated way on the 873 // exact ordering of callbacks from the parser. 874 DeclContext *Sema::getContainingDC(DeclContext *DC) { 875 876 // Functions defined inline within classes aren't parsed until we've 877 // finished parsing the top-level class, so the top-level class is 878 // the context we'll need to return to. 879 // A Lambda call operator whose parent is a class must not be treated 880 // as an inline member function. A Lambda can be used legally 881 // either as an in-class member initializer or a default argument. These 882 // are parsed once the class has been marked complete and so the containing 883 // context would be the nested class (when the lambda is defined in one); 884 // If the class is not complete, then the lambda is being used in an 885 // ill-formed fashion (such as to specify the width of a bit-field, or 886 // in an array-bound) - in which case we still want to return the 887 // lexically containing DC (which could be a nested class). 888 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 889 DC = DC->getLexicalParent(); 890 891 // A function not defined within a class will always return to its 892 // lexical context. 893 if (!isa<CXXRecordDecl>(DC)) 894 return DC; 895 896 // A C++ inline method/friend is parsed *after* the topmost class 897 // it was declared in is fully parsed ("complete"); the topmost 898 // class is the context we need to return to. 899 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 900 DC = RD; 901 902 // Return the declaration context of the topmost class the inline method is 903 // declared in. 904 return DC; 905 } 906 907 return DC->getLexicalParent(); 908 } 909 910 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 911 assert(getContainingDC(DC) == CurContext && 912 "The next DeclContext should be lexically contained in the current one."); 913 CurContext = DC; 914 S->setEntity(DC); 915 } 916 917 void Sema::PopDeclContext() { 918 assert(CurContext && "DeclContext imbalance!"); 919 920 CurContext = getContainingDC(CurContext); 921 assert(CurContext && "Popped translation unit!"); 922 } 923 924 /// EnterDeclaratorContext - Used when we must lookup names in the context 925 /// of a declarator's nested name specifier. 926 /// 927 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 928 // C++0x [basic.lookup.unqual]p13: 929 // A name used in the definition of a static data member of class 930 // X (after the qualified-id of the static member) is looked up as 931 // if the name was used in a member function of X. 932 // C++0x [basic.lookup.unqual]p14: 933 // If a variable member of a namespace is defined outside of the 934 // scope of its namespace then any name used in the definition of 935 // the variable member (after the declarator-id) is looked up as 936 // if the definition of the variable member occurred in its 937 // namespace. 938 // Both of these imply that we should push a scope whose context 939 // is the semantic context of the declaration. We can't use 940 // PushDeclContext here because that context is not necessarily 941 // lexically contained in the current context. Fortunately, 942 // the containing scope should have the appropriate information. 943 944 assert(!S->getEntity() && "scope already has entity"); 945 946 #ifndef NDEBUG 947 Scope *Ancestor = S->getParent(); 948 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 949 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 950 #endif 951 952 CurContext = DC; 953 S->setEntity(DC); 954 } 955 956 void Sema::ExitDeclaratorContext(Scope *S) { 957 assert(S->getEntity() == CurContext && "Context imbalance!"); 958 959 // Switch back to the lexical context. The safety of this is 960 // enforced by an assert in EnterDeclaratorContext. 961 Scope *Ancestor = S->getParent(); 962 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 963 CurContext = Ancestor->getEntity(); 964 965 // We don't need to do anything with the scope, which is going to 966 // disappear. 967 } 968 969 970 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 971 // We assume that the caller has already called 972 // ActOnReenterTemplateScope so getTemplatedDecl() works. 973 FunctionDecl *FD = D->getAsFunction(); 974 if (!FD) 975 return; 976 977 // Same implementation as PushDeclContext, but enters the context 978 // from the lexical parent, rather than the top-level class. 979 assert(CurContext == FD->getLexicalParent() && 980 "The next DeclContext should be lexically contained in the current one."); 981 CurContext = FD; 982 S->setEntity(CurContext); 983 984 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 985 ParmVarDecl *Param = FD->getParamDecl(P); 986 // If the parameter has an identifier, then add it to the scope 987 if (Param->getIdentifier()) { 988 S->AddDecl(Param); 989 IdResolver.AddDecl(Param); 990 } 991 } 992 } 993 994 995 void Sema::ActOnExitFunctionContext() { 996 // Same implementation as PopDeclContext, but returns to the lexical parent, 997 // rather than the top-level class. 998 assert(CurContext && "DeclContext imbalance!"); 999 CurContext = CurContext->getLexicalParent(); 1000 assert(CurContext && "Popped translation unit!"); 1001 } 1002 1003 1004 /// \brief Determine whether we allow overloading of the function 1005 /// PrevDecl with another declaration. 1006 /// 1007 /// This routine determines whether overloading is possible, not 1008 /// whether some new function is actually an overload. It will return 1009 /// true in C++ (where we can always provide overloads) or, as an 1010 /// extension, in C when the previous function is already an 1011 /// overloaded function declaration or has the "overloadable" 1012 /// attribute. 1013 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1014 ASTContext &Context) { 1015 if (Context.getLangOpts().CPlusPlus) 1016 return true; 1017 1018 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1019 return true; 1020 1021 return (Previous.getResultKind() == LookupResult::Found 1022 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1023 } 1024 1025 /// Add this decl to the scope shadowed decl chains. 1026 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1027 // Move up the scope chain until we find the nearest enclosing 1028 // non-transparent context. The declaration will be introduced into this 1029 // scope. 1030 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1031 S = S->getParent(); 1032 1033 // Add scoped declarations into their context, so that they can be 1034 // found later. Declarations without a context won't be inserted 1035 // into any context. 1036 if (AddToContext) 1037 CurContext->addDecl(D); 1038 1039 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1040 // are function-local declarations. 1041 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1042 !D->getDeclContext()->getRedeclContext()->Equals( 1043 D->getLexicalDeclContext()->getRedeclContext()) && 1044 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1045 return; 1046 1047 // Template instantiations should also not be pushed into scope. 1048 if (isa<FunctionDecl>(D) && 1049 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1050 return; 1051 1052 // If this replaces anything in the current scope, 1053 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1054 IEnd = IdResolver.end(); 1055 for (; I != IEnd; ++I) { 1056 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1057 S->RemoveDecl(*I); 1058 IdResolver.RemoveDecl(*I); 1059 1060 // Should only need to replace one decl. 1061 break; 1062 } 1063 } 1064 1065 S->AddDecl(D); 1066 1067 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1068 // Implicitly-generated labels may end up getting generated in an order that 1069 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1070 // the label at the appropriate place in the identifier chain. 1071 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1072 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1073 if (IDC == CurContext) { 1074 if (!S->isDeclScope(*I)) 1075 continue; 1076 } else if (IDC->Encloses(CurContext)) 1077 break; 1078 } 1079 1080 IdResolver.InsertDeclAfter(I, D); 1081 } else { 1082 IdResolver.AddDecl(D); 1083 } 1084 } 1085 1086 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1087 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1088 TUScope->AddDecl(D); 1089 } 1090 1091 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1092 bool AllowInlineNamespace) { 1093 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1094 } 1095 1096 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1097 DeclContext *TargetDC = DC->getPrimaryContext(); 1098 do { 1099 if (DeclContext *ScopeDC = S->getEntity()) 1100 if (ScopeDC->getPrimaryContext() == TargetDC) 1101 return S; 1102 } while ((S = S->getParent())); 1103 1104 return 0; 1105 } 1106 1107 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1108 DeclContext*, 1109 ASTContext&); 1110 1111 /// Filters out lookup results that don't fall within the given scope 1112 /// as determined by isDeclInScope. 1113 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1114 bool ConsiderLinkage, 1115 bool AllowInlineNamespace) { 1116 LookupResult::Filter F = R.makeFilter(); 1117 while (F.hasNext()) { 1118 NamedDecl *D = F.next(); 1119 1120 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1121 continue; 1122 1123 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1124 continue; 1125 1126 F.erase(); 1127 } 1128 1129 F.done(); 1130 } 1131 1132 static bool isUsingDecl(NamedDecl *D) { 1133 return isa<UsingShadowDecl>(D) || 1134 isa<UnresolvedUsingTypenameDecl>(D) || 1135 isa<UnresolvedUsingValueDecl>(D); 1136 } 1137 1138 /// Removes using shadow declarations from the lookup results. 1139 static void RemoveUsingDecls(LookupResult &R) { 1140 LookupResult::Filter F = R.makeFilter(); 1141 while (F.hasNext()) 1142 if (isUsingDecl(F.next())) 1143 F.erase(); 1144 1145 F.done(); 1146 } 1147 1148 /// \brief Check for this common pattern: 1149 /// @code 1150 /// class S { 1151 /// S(const S&); // DO NOT IMPLEMENT 1152 /// void operator=(const S&); // DO NOT IMPLEMENT 1153 /// }; 1154 /// @endcode 1155 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1156 // FIXME: Should check for private access too but access is set after we get 1157 // the decl here. 1158 if (D->doesThisDeclarationHaveABody()) 1159 return false; 1160 1161 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1162 return CD->isCopyConstructor(); 1163 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1164 return Method->isCopyAssignmentOperator(); 1165 return false; 1166 } 1167 1168 // We need this to handle 1169 // 1170 // typedef struct { 1171 // void *foo() { return 0; } 1172 // } A; 1173 // 1174 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1175 // for example. If 'A', foo will have external linkage. If we have '*A', 1176 // foo will have no linkage. Since we can't know until we get to the end 1177 // of the typedef, this function finds out if D might have non-external linkage. 1178 // Callers should verify at the end of the TU if it D has external linkage or 1179 // not. 1180 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1181 const DeclContext *DC = D->getDeclContext(); 1182 while (!DC->isTranslationUnit()) { 1183 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1184 if (!RD->hasNameForLinkage()) 1185 return true; 1186 } 1187 DC = DC->getParent(); 1188 } 1189 1190 return !D->isExternallyVisible(); 1191 } 1192 1193 // FIXME: This needs to be refactored; some other isInMainFile users want 1194 // these semantics. 1195 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1196 if (S.TUKind != TU_Complete) 1197 return false; 1198 return S.SourceMgr.isInMainFile(Loc); 1199 } 1200 1201 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1202 assert(D); 1203 1204 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1205 return false; 1206 1207 // Ignore all entities declared within templates, and out-of-line definitions 1208 // of members of 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 (auto *TmpD : S->decls()) { 1380 assert(TmpD && "This decl didn't get pushed??"); 1381 1382 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1383 NamedDecl *D = cast<NamedDecl>(TmpD); 1384 1385 if (!D->getDeclName()) continue; 1386 1387 // Diagnose unused variables in this scope. 1388 if (!S->hasUnrecoverableErrorOccurred()) 1389 DiagnoseUnusedDecl(D); 1390 1391 // If this was a forward reference to a label, verify it was defined. 1392 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1393 CheckPoppedLabel(LD, *this); 1394 1395 // Remove this name from our lexical scope. 1396 IdResolver.RemoveDecl(D); 1397 } 1398 } 1399 1400 /// \brief Look for an Objective-C class in the translation unit. 1401 /// 1402 /// \param Id The name of the Objective-C class we're looking for. If 1403 /// typo-correction fixes this name, the Id will be updated 1404 /// to the fixed name. 1405 /// 1406 /// \param IdLoc The location of the name in the translation unit. 1407 /// 1408 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1409 /// if there is no class with the given name. 1410 /// 1411 /// \returns The declaration of the named Objective-C class, or NULL if the 1412 /// class could not be found. 1413 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1414 SourceLocation IdLoc, 1415 bool DoTypoCorrection) { 1416 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1417 // creation from this context. 1418 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1419 1420 if (!IDecl && DoTypoCorrection) { 1421 // Perform typo correction at the given location, but only if we 1422 // find an Objective-C class name. 1423 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1424 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1425 LookupOrdinaryName, TUScope, NULL, 1426 Validator)) { 1427 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1428 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1429 Id = IDecl->getIdentifier(); 1430 } 1431 } 1432 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1433 // This routine must always return a class definition, if any. 1434 if (Def && Def->getDefinition()) 1435 Def = Def->getDefinition(); 1436 return Def; 1437 } 1438 1439 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1440 /// from S, where a non-field would be declared. This routine copes 1441 /// with the difference between C and C++ scoping rules in structs and 1442 /// unions. For example, the following code is well-formed in C but 1443 /// ill-formed in C++: 1444 /// @code 1445 /// struct S6 { 1446 /// enum { BAR } e; 1447 /// }; 1448 /// 1449 /// void test_S6() { 1450 /// struct S6 a; 1451 /// a.e = BAR; 1452 /// } 1453 /// @endcode 1454 /// For the declaration of BAR, this routine will return a different 1455 /// scope. The scope S will be the scope of the unnamed enumeration 1456 /// within S6. In C++, this routine will return the scope associated 1457 /// with S6, because the enumeration's scope is a transparent 1458 /// context but structures can contain non-field names. In C, this 1459 /// routine will return the translation unit scope, since the 1460 /// enumeration's scope is a transparent context and structures cannot 1461 /// contain non-field names. 1462 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1463 while (((S->getFlags() & Scope::DeclScope) == 0) || 1464 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1465 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1466 S = S->getParent(); 1467 return S; 1468 } 1469 1470 /// \brief Looks up the declaration of "struct objc_super" and 1471 /// saves it for later use in building builtin declaration of 1472 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1473 /// pre-existing declaration exists no action takes place. 1474 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1475 IdentifierInfo *II) { 1476 if (!II->isStr("objc_msgSendSuper")) 1477 return; 1478 ASTContext &Context = ThisSema.Context; 1479 1480 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1481 SourceLocation(), Sema::LookupTagName); 1482 ThisSema.LookupName(Result, S); 1483 if (Result.getResultKind() == LookupResult::Found) 1484 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1485 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1486 } 1487 1488 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1489 /// file scope. lazily create a decl for it. ForRedeclaration is true 1490 /// if we're creating this built-in in anticipation of redeclaring the 1491 /// built-in. 1492 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1493 Scope *S, bool ForRedeclaration, 1494 SourceLocation Loc) { 1495 LookupPredefedObjCSuperType(*this, S, II); 1496 1497 Builtin::ID BID = (Builtin::ID)bid; 1498 1499 ASTContext::GetBuiltinTypeError Error; 1500 QualType R = Context.GetBuiltinType(BID, Error); 1501 switch (Error) { 1502 case ASTContext::GE_None: 1503 // Okay 1504 break; 1505 1506 case ASTContext::GE_Missing_stdio: 1507 if (ForRedeclaration) 1508 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1509 << Context.BuiltinInfo.GetName(BID); 1510 return 0; 1511 1512 case ASTContext::GE_Missing_setjmp: 1513 if (ForRedeclaration) 1514 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1515 << Context.BuiltinInfo.GetName(BID); 1516 return 0; 1517 1518 case ASTContext::GE_Missing_ucontext: 1519 if (ForRedeclaration) 1520 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1521 << Context.BuiltinInfo.GetName(BID); 1522 return 0; 1523 } 1524 1525 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1526 Diag(Loc, diag::ext_implicit_lib_function_decl) 1527 << Context.BuiltinInfo.GetName(BID) 1528 << R; 1529 if (Context.BuiltinInfo.getHeaderName(BID) && 1530 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1531 != DiagnosticsEngine::Ignored) 1532 Diag(Loc, diag::note_please_include_header) 1533 << Context.BuiltinInfo.getHeaderName(BID) 1534 << Context.BuiltinInfo.GetName(BID); 1535 } 1536 1537 DeclContext *Parent = Context.getTranslationUnitDecl(); 1538 if (getLangOpts().CPlusPlus) { 1539 LinkageSpecDecl *CLinkageDecl = 1540 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1541 LinkageSpecDecl::lang_c, false); 1542 CLinkageDecl->setImplicit(); 1543 Parent->addDecl(CLinkageDecl); 1544 Parent = CLinkageDecl; 1545 } 1546 1547 FunctionDecl *New = FunctionDecl::Create(Context, 1548 Parent, 1549 Loc, Loc, II, R, /*TInfo=*/0, 1550 SC_Extern, 1551 false, 1552 /*hasPrototype=*/true); 1553 New->setImplicit(); 1554 1555 // Create Decl objects for each parameter, adding them to the 1556 // FunctionDecl. 1557 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1558 SmallVector<ParmVarDecl*, 16> Params; 1559 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1560 ParmVarDecl *parm = 1561 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1562 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0); 1563 parm->setScopeInfo(0, i); 1564 Params.push_back(parm); 1565 } 1566 New->setParams(Params); 1567 } 1568 1569 AddKnownFunctionAttributes(New); 1570 RegisterLocallyScopedExternCDecl(New, S); 1571 1572 // TUScope is the translation-unit scope to insert this function into. 1573 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1574 // relate Scopes to DeclContexts, and probably eliminate CurContext 1575 // entirely, but we're not there yet. 1576 DeclContext *SavedContext = CurContext; 1577 CurContext = Parent; 1578 PushOnScopeChains(New, TUScope); 1579 CurContext = SavedContext; 1580 return New; 1581 } 1582 1583 /// \brief Filter out any previous declarations that the given declaration 1584 /// should not consider because they are not permitted to conflict, e.g., 1585 /// because they come from hidden sub-modules and do not refer to the same 1586 /// entity. 1587 static void filterNonConflictingPreviousDecls(ASTContext &context, 1588 NamedDecl *decl, 1589 LookupResult &previous){ 1590 // This is only interesting when modules are enabled. 1591 if (!context.getLangOpts().Modules) 1592 return; 1593 1594 // Empty sets are uninteresting. 1595 if (previous.empty()) 1596 return; 1597 1598 LookupResult::Filter filter = previous.makeFilter(); 1599 while (filter.hasNext()) { 1600 NamedDecl *old = filter.next(); 1601 1602 // Non-hidden declarations are never ignored. 1603 if (!old->isHidden()) 1604 continue; 1605 1606 if (!old->isExternallyVisible()) 1607 filter.erase(); 1608 } 1609 1610 filter.done(); 1611 } 1612 1613 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1614 QualType OldType; 1615 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1616 OldType = OldTypedef->getUnderlyingType(); 1617 else 1618 OldType = Context.getTypeDeclType(Old); 1619 QualType NewType = New->getUnderlyingType(); 1620 1621 if (NewType->isVariablyModifiedType()) { 1622 // Must not redefine a typedef with a variably-modified type. 1623 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1624 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1625 << Kind << NewType; 1626 if (Old->getLocation().isValid()) 1627 Diag(Old->getLocation(), diag::note_previous_definition); 1628 New->setInvalidDecl(); 1629 return true; 1630 } 1631 1632 if (OldType != NewType && 1633 !OldType->isDependentType() && 1634 !NewType->isDependentType() && 1635 !Context.hasSameType(OldType, NewType)) { 1636 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1637 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1638 << Kind << NewType << OldType; 1639 if (Old->getLocation().isValid()) 1640 Diag(Old->getLocation(), diag::note_previous_definition); 1641 New->setInvalidDecl(); 1642 return true; 1643 } 1644 return false; 1645 } 1646 1647 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1648 /// same name and scope as a previous declaration 'Old'. Figure out 1649 /// how to resolve this situation, merging decls or emitting 1650 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1651 /// 1652 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1653 // If the new decl is known invalid already, don't bother doing any 1654 // merging checks. 1655 if (New->isInvalidDecl()) return; 1656 1657 // Allow multiple definitions for ObjC built-in typedefs. 1658 // FIXME: Verify the underlying types are equivalent! 1659 if (getLangOpts().ObjC1) { 1660 const IdentifierInfo *TypeID = New->getIdentifier(); 1661 switch (TypeID->getLength()) { 1662 default: break; 1663 case 2: 1664 { 1665 if (!TypeID->isStr("id")) 1666 break; 1667 QualType T = New->getUnderlyingType(); 1668 if (!T->isPointerType()) 1669 break; 1670 if (!T->isVoidPointerType()) { 1671 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1672 if (!PT->isStructureType()) 1673 break; 1674 } 1675 Context.setObjCIdRedefinitionType(T); 1676 // Install the built-in type for 'id', ignoring the current definition. 1677 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1678 return; 1679 } 1680 case 5: 1681 if (!TypeID->isStr("Class")) 1682 break; 1683 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1684 // Install the built-in type for 'Class', ignoring the current definition. 1685 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1686 return; 1687 case 3: 1688 if (!TypeID->isStr("SEL")) 1689 break; 1690 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1691 // Install the built-in type for 'SEL', ignoring the current definition. 1692 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1693 return; 1694 } 1695 // Fall through - the typedef name was not a builtin type. 1696 } 1697 1698 // Verify the old decl was also a type. 1699 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1700 if (!Old) { 1701 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1702 << New->getDeclName(); 1703 1704 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1705 if (OldD->getLocation().isValid()) 1706 Diag(OldD->getLocation(), diag::note_previous_definition); 1707 1708 return New->setInvalidDecl(); 1709 } 1710 1711 // If the old declaration is invalid, just give up here. 1712 if (Old->isInvalidDecl()) 1713 return New->setInvalidDecl(); 1714 1715 // If the typedef types are not identical, reject them in all languages and 1716 // with any extensions enabled. 1717 if (isIncompatibleTypedef(Old, New)) 1718 return; 1719 1720 // The types match. Link up the redeclaration chain and merge attributes if 1721 // the old declaration was a typedef. 1722 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1723 New->setPreviousDecl(Typedef); 1724 mergeDeclAttributes(New, Old); 1725 } 1726 1727 if (getLangOpts().MicrosoftExt) 1728 return; 1729 1730 if (getLangOpts().CPlusPlus) { 1731 // C++ [dcl.typedef]p2: 1732 // In a given non-class scope, a typedef specifier can be used to 1733 // redefine the name of any type declared in that scope to refer 1734 // to the type to which it already refers. 1735 if (!isa<CXXRecordDecl>(CurContext)) 1736 return; 1737 1738 // C++0x [dcl.typedef]p4: 1739 // In a given class scope, a typedef specifier can be used to redefine 1740 // any class-name declared in that scope that is not also a typedef-name 1741 // to refer to the type to which it already refers. 1742 // 1743 // This wording came in via DR424, which was a correction to the 1744 // wording in DR56, which accidentally banned code like: 1745 // 1746 // struct S { 1747 // typedef struct A { } A; 1748 // }; 1749 // 1750 // in the C++03 standard. We implement the C++0x semantics, which 1751 // allow the above but disallow 1752 // 1753 // struct S { 1754 // typedef int I; 1755 // typedef int I; 1756 // }; 1757 // 1758 // since that was the intent of DR56. 1759 if (!isa<TypedefNameDecl>(Old)) 1760 return; 1761 1762 Diag(New->getLocation(), diag::err_redefinition) 1763 << New->getDeclName(); 1764 Diag(Old->getLocation(), diag::note_previous_definition); 1765 return New->setInvalidDecl(); 1766 } 1767 1768 // Modules always permit redefinition of typedefs, as does C11. 1769 if (getLangOpts().Modules || getLangOpts().C11) 1770 return; 1771 1772 // If we have a redefinition of a typedef in C, emit a warning. This warning 1773 // is normally mapped to an error, but can be controlled with 1774 // -Wtypedef-redefinition. If either the original or the redefinition is 1775 // in a system header, don't emit this for compatibility with GCC. 1776 if (getDiagnostics().getSuppressSystemWarnings() && 1777 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1778 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1779 return; 1780 1781 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1782 << New->getDeclName(); 1783 Diag(Old->getLocation(), diag::note_previous_definition); 1784 return; 1785 } 1786 1787 /// DeclhasAttr - returns true if decl Declaration already has the target 1788 /// attribute. 1789 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1790 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1791 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1792 for (const auto *i : D->attrs()) 1793 if (i->getKind() == A->getKind()) { 1794 if (Ann) { 1795 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1796 return true; 1797 continue; 1798 } 1799 // FIXME: Don't hardcode this check 1800 if (OA && isa<OwnershipAttr>(i)) 1801 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 1802 return true; 1803 } 1804 1805 return false; 1806 } 1807 1808 static bool isAttributeTargetADefinition(Decl *D) { 1809 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1810 return VD->isThisDeclarationADefinition(); 1811 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1812 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1813 return true; 1814 } 1815 1816 /// Merge alignment attributes from \p Old to \p New, taking into account the 1817 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1818 /// 1819 /// \return \c true if any attributes were added to \p New. 1820 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1821 // Look for alignas attributes on Old, and pick out whichever attribute 1822 // specifies the strictest alignment requirement. 1823 AlignedAttr *OldAlignasAttr = 0; 1824 AlignedAttr *OldStrictestAlignAttr = 0; 1825 unsigned OldAlign = 0; 1826 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 1827 // FIXME: We have no way of representing inherited dependent alignments 1828 // in a case like: 1829 // template<int A, int B> struct alignas(A) X; 1830 // template<int A, int B> struct alignas(B) X {}; 1831 // For now, we just ignore any alignas attributes which are not on the 1832 // definition in such a case. 1833 if (I->isAlignmentDependent()) 1834 return false; 1835 1836 if (I->isAlignas()) 1837 OldAlignasAttr = I; 1838 1839 unsigned Align = I->getAlignment(S.Context); 1840 if (Align > OldAlign) { 1841 OldAlign = Align; 1842 OldStrictestAlignAttr = I; 1843 } 1844 } 1845 1846 // Look for alignas attributes on New. 1847 AlignedAttr *NewAlignasAttr = 0; 1848 unsigned NewAlign = 0; 1849 for (auto *I : New->specific_attrs<AlignedAttr>()) { 1850 if (I->isAlignmentDependent()) 1851 return false; 1852 1853 if (I->isAlignas()) 1854 NewAlignasAttr = I; 1855 1856 unsigned Align = I->getAlignment(S.Context); 1857 if (Align > NewAlign) 1858 NewAlign = Align; 1859 } 1860 1861 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1862 // Both declarations have 'alignas' attributes. We require them to match. 1863 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1864 // fall short. (If two declarations both have alignas, they must both match 1865 // every definition, and so must match each other if there is a definition.) 1866 1867 // If either declaration only contains 'alignas(0)' specifiers, then it 1868 // specifies the natural alignment for the type. 1869 if (OldAlign == 0 || NewAlign == 0) { 1870 QualType Ty; 1871 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1872 Ty = VD->getType(); 1873 else 1874 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1875 1876 if (OldAlign == 0) 1877 OldAlign = S.Context.getTypeAlign(Ty); 1878 if (NewAlign == 0) 1879 NewAlign = S.Context.getTypeAlign(Ty); 1880 } 1881 1882 if (OldAlign != NewAlign) { 1883 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1884 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1885 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1886 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1887 } 1888 } 1889 1890 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1891 // C++11 [dcl.align]p6: 1892 // if any declaration of an entity has an alignment-specifier, 1893 // every defining declaration of that entity shall specify an 1894 // equivalent alignment. 1895 // C11 6.7.5/7: 1896 // If the definition of an object does not have an alignment 1897 // specifier, any other declaration of that object shall also 1898 // have no alignment specifier. 1899 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1900 << OldAlignasAttr; 1901 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1902 << OldAlignasAttr; 1903 } 1904 1905 bool AnyAdded = false; 1906 1907 // Ensure we have an attribute representing the strictest alignment. 1908 if (OldAlign > NewAlign) { 1909 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1910 Clone->setInherited(true); 1911 New->addAttr(Clone); 1912 AnyAdded = true; 1913 } 1914 1915 // Ensure we have an alignas attribute if the old declaration had one. 1916 if (OldAlignasAttr && !NewAlignasAttr && 1917 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1918 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1919 Clone->setInherited(true); 1920 New->addAttr(Clone); 1921 AnyAdded = true; 1922 } 1923 1924 return AnyAdded; 1925 } 1926 1927 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1928 bool Override) { 1929 InheritableAttr *NewAttr = NULL; 1930 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1931 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1932 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1933 AA->getIntroduced(), AA->getDeprecated(), 1934 AA->getObsoleted(), AA->getUnavailable(), 1935 AA->getMessage(), Override, 1936 AttrSpellingListIndex); 1937 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1938 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1939 AttrSpellingListIndex); 1940 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1941 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1942 AttrSpellingListIndex); 1943 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1944 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1945 AttrSpellingListIndex); 1946 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1947 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1948 AttrSpellingListIndex); 1949 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1950 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1951 FA->getFormatIdx(), FA->getFirstArg(), 1952 AttrSpellingListIndex); 1953 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1954 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1955 AttrSpellingListIndex); 1956 else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr)) 1957 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 1958 AttrSpellingListIndex, 1959 IA->getSemanticSpelling()); 1960 else if (isa<AlignedAttr>(Attr)) 1961 // AlignedAttrs are handled separately, because we need to handle all 1962 // such attributes on a declaration at the same time. 1963 NewAttr = 0; 1964 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 1965 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1966 1967 if (NewAttr) { 1968 NewAttr->setInherited(true); 1969 D->addAttr(NewAttr); 1970 return true; 1971 } 1972 1973 return false; 1974 } 1975 1976 static const Decl *getDefinition(const Decl *D) { 1977 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1978 return TD->getDefinition(); 1979 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1980 const VarDecl *Def = VD->getDefinition(); 1981 if (Def) 1982 return Def; 1983 return VD->getActingDefinition(); 1984 } 1985 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1986 const FunctionDecl* Def; 1987 if (FD->isDefined(Def)) 1988 return Def; 1989 } 1990 return NULL; 1991 } 1992 1993 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 1994 for (const auto *Attribute : D->attrs()) 1995 if (Attribute->getKind() == Kind) 1996 return true; 1997 return false; 1998 } 1999 2000 /// checkNewAttributesAfterDef - If we already have a definition, check that 2001 /// there are no new attributes in this declaration. 2002 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2003 if (!New->hasAttrs()) 2004 return; 2005 2006 const Decl *Def = getDefinition(Old); 2007 if (!Def || Def == New) 2008 return; 2009 2010 AttrVec &NewAttributes = New->getAttrs(); 2011 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2012 const Attr *NewAttribute = NewAttributes[I]; 2013 2014 if (isa<AliasAttr>(NewAttribute)) { 2015 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2016 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2017 else { 2018 VarDecl *VD = cast<VarDecl>(New); 2019 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2020 VarDecl::TentativeDefinition 2021 ? diag::err_alias_after_tentative 2022 : diag::err_redefinition; 2023 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2024 S.Diag(Def->getLocation(), diag::note_previous_definition); 2025 VD->setInvalidDecl(); 2026 } 2027 ++I; 2028 continue; 2029 } 2030 2031 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2032 // Tentative definitions are only interesting for the alias check above. 2033 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2034 ++I; 2035 continue; 2036 } 2037 } 2038 2039 if (hasAttribute(Def, NewAttribute->getKind())) { 2040 ++I; 2041 continue; // regular attr merging will take care of validating this. 2042 } 2043 2044 if (isa<C11NoReturnAttr>(NewAttribute)) { 2045 // C's _Noreturn is allowed to be added to a function after it is defined. 2046 ++I; 2047 continue; 2048 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2049 if (AA->isAlignas()) { 2050 // C++11 [dcl.align]p6: 2051 // if any declaration of an entity has an alignment-specifier, 2052 // every defining declaration of that entity shall specify an 2053 // equivalent alignment. 2054 // C11 6.7.5/7: 2055 // If the definition of an object does not have an alignment 2056 // specifier, any other declaration of that object shall also 2057 // have no alignment specifier. 2058 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2059 << AA; 2060 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2061 << AA; 2062 NewAttributes.erase(NewAttributes.begin() + I); 2063 --E; 2064 continue; 2065 } 2066 } 2067 2068 S.Diag(NewAttribute->getLocation(), 2069 diag::warn_attribute_precede_definition); 2070 S.Diag(Def->getLocation(), diag::note_previous_definition); 2071 NewAttributes.erase(NewAttributes.begin() + I); 2072 --E; 2073 } 2074 } 2075 2076 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2077 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2078 AvailabilityMergeKind AMK) { 2079 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2080 UsedAttr *NewAttr = OldAttr->clone(Context); 2081 NewAttr->setInherited(true); 2082 New->addAttr(NewAttr); 2083 } 2084 2085 if (!Old->hasAttrs() && !New->hasAttrs()) 2086 return; 2087 2088 // attributes declared post-definition are currently ignored 2089 checkNewAttributesAfterDef(*this, New, Old); 2090 2091 if (!Old->hasAttrs()) 2092 return; 2093 2094 bool foundAny = New->hasAttrs(); 2095 2096 // Ensure that any moving of objects within the allocated map is done before 2097 // we process them. 2098 if (!foundAny) New->setAttrs(AttrVec()); 2099 2100 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2101 bool Override = false; 2102 // Ignore deprecated/unavailable/availability attributes if requested. 2103 if (isa<DeprecatedAttr>(I) || 2104 isa<UnavailableAttr>(I) || 2105 isa<AvailabilityAttr>(I)) { 2106 switch (AMK) { 2107 case AMK_None: 2108 continue; 2109 2110 case AMK_Redeclaration: 2111 break; 2112 2113 case AMK_Override: 2114 Override = true; 2115 break; 2116 } 2117 } 2118 2119 // Already handled. 2120 if (isa<UsedAttr>(I)) 2121 continue; 2122 2123 if (mergeDeclAttribute(*this, New, I, Override)) 2124 foundAny = true; 2125 } 2126 2127 if (mergeAlignedAttrs(*this, New, Old)) 2128 foundAny = true; 2129 2130 if (!foundAny) New->dropAttrs(); 2131 } 2132 2133 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2134 /// to the new one. 2135 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2136 const ParmVarDecl *oldDecl, 2137 Sema &S) { 2138 // C++11 [dcl.attr.depend]p2: 2139 // The first declaration of a function shall specify the 2140 // carries_dependency attribute for its declarator-id if any declaration 2141 // of the function specifies the carries_dependency attribute. 2142 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2143 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2144 S.Diag(CDA->getLocation(), 2145 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2146 // Find the first declaration of the parameter. 2147 // FIXME: Should we build redeclaration chains for function parameters? 2148 const FunctionDecl *FirstFD = 2149 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2150 const ParmVarDecl *FirstVD = 2151 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2152 S.Diag(FirstVD->getLocation(), 2153 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2154 } 2155 2156 if (!oldDecl->hasAttrs()) 2157 return; 2158 2159 bool foundAny = newDecl->hasAttrs(); 2160 2161 // Ensure that any moving of objects within the allocated map is 2162 // done before we process them. 2163 if (!foundAny) newDecl->setAttrs(AttrVec()); 2164 2165 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2166 if (!DeclHasAttr(newDecl, I)) { 2167 InheritableAttr *newAttr = 2168 cast<InheritableParamAttr>(I->clone(S.Context)); 2169 newAttr->setInherited(true); 2170 newDecl->addAttr(newAttr); 2171 foundAny = true; 2172 } 2173 } 2174 2175 if (!foundAny) newDecl->dropAttrs(); 2176 } 2177 2178 namespace { 2179 2180 /// Used in MergeFunctionDecl to keep track of function parameters in 2181 /// C. 2182 struct GNUCompatibleParamWarning { 2183 ParmVarDecl *OldParm; 2184 ParmVarDecl *NewParm; 2185 QualType PromotedType; 2186 }; 2187 2188 } 2189 2190 /// getSpecialMember - get the special member enum for a method. 2191 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2192 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2193 if (Ctor->isDefaultConstructor()) 2194 return Sema::CXXDefaultConstructor; 2195 2196 if (Ctor->isCopyConstructor()) 2197 return Sema::CXXCopyConstructor; 2198 2199 if (Ctor->isMoveConstructor()) 2200 return Sema::CXXMoveConstructor; 2201 } else if (isa<CXXDestructorDecl>(MD)) { 2202 return Sema::CXXDestructor; 2203 } else if (MD->isCopyAssignmentOperator()) { 2204 return Sema::CXXCopyAssignment; 2205 } else if (MD->isMoveAssignmentOperator()) { 2206 return Sema::CXXMoveAssignment; 2207 } 2208 2209 return Sema::CXXInvalid; 2210 } 2211 2212 /// canRedefineFunction - checks if a function can be redefined. Currently, 2213 /// only extern inline functions can be redefined, and even then only in 2214 /// GNU89 mode. 2215 static bool canRedefineFunction(const FunctionDecl *FD, 2216 const LangOptions& LangOpts) { 2217 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2218 !LangOpts.CPlusPlus && 2219 FD->isInlineSpecified() && 2220 FD->getStorageClass() == SC_Extern); 2221 } 2222 2223 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2224 const AttributedType *AT = T->getAs<AttributedType>(); 2225 while (AT && !AT->isCallingConv()) 2226 AT = AT->getModifiedType()->getAs<AttributedType>(); 2227 return AT; 2228 } 2229 2230 template <typename T> 2231 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2232 const DeclContext *DC = Old->getDeclContext(); 2233 if (DC->isRecord()) 2234 return false; 2235 2236 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2237 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2238 return true; 2239 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2240 return true; 2241 return false; 2242 } 2243 2244 /// MergeFunctionDecl - We just parsed a function 'New' from 2245 /// declarator D which has the same name and scope as a previous 2246 /// declaration 'Old'. Figure out how to resolve this situation, 2247 /// merging decls or emitting diagnostics as appropriate. 2248 /// 2249 /// In C++, New and Old must be declarations that are not 2250 /// overloaded. Use IsOverload to determine whether New and Old are 2251 /// overloaded, and to select the Old declaration that New should be 2252 /// merged with. 2253 /// 2254 /// Returns true if there was an error, false otherwise. 2255 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2256 Scope *S, bool MergeTypeWithOld) { 2257 // Verify the old decl was also a function. 2258 FunctionDecl *Old = OldD->getAsFunction(); 2259 if (!Old) { 2260 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2261 if (New->getFriendObjectKind()) { 2262 Diag(New->getLocation(), diag::err_using_decl_friend); 2263 Diag(Shadow->getTargetDecl()->getLocation(), 2264 diag::note_using_decl_target); 2265 Diag(Shadow->getUsingDecl()->getLocation(), 2266 diag::note_using_decl) << 0; 2267 return true; 2268 } 2269 2270 // C++11 [namespace.udecl]p14: 2271 // If a function declaration in namespace scope or block scope has the 2272 // same name and the same parameter-type-list as a function introduced 2273 // by a using-declaration, and the declarations do not declare the same 2274 // function, the program is ill-formed. 2275 2276 // Check whether the two declarations might declare the same function. 2277 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2278 if (Old && 2279 !Old->getDeclContext()->getRedeclContext()->Equals( 2280 New->getDeclContext()->getRedeclContext()) && 2281 !(Old->isExternC() && New->isExternC())) 2282 Old = 0; 2283 2284 if (!Old) { 2285 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2286 Diag(Shadow->getTargetDecl()->getLocation(), 2287 diag::note_using_decl_target); 2288 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2289 return true; 2290 } 2291 OldD = Old; 2292 } else { 2293 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2294 << New->getDeclName(); 2295 Diag(OldD->getLocation(), diag::note_previous_definition); 2296 return true; 2297 } 2298 } 2299 2300 // If the old declaration is invalid, just give up here. 2301 if (Old->isInvalidDecl()) 2302 return true; 2303 2304 // Determine whether the previous declaration was a definition, 2305 // implicit declaration, or a declaration. 2306 diag::kind PrevDiag; 2307 SourceLocation OldLocation = Old->getLocation(); 2308 if (Old->isThisDeclarationADefinition()) 2309 PrevDiag = diag::note_previous_definition; 2310 else if (Old->isImplicit()) { 2311 PrevDiag = diag::note_previous_implicit_declaration; 2312 if (OldLocation.isInvalid()) 2313 OldLocation = New->getLocation(); 2314 } else 2315 PrevDiag = diag::note_previous_declaration; 2316 2317 // Don't complain about this if we're in GNU89 mode and the old function 2318 // is an extern inline function. 2319 // Don't complain about specializations. They are not supposed to have 2320 // storage classes. 2321 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2322 New->getStorageClass() == SC_Static && 2323 Old->hasExternalFormalLinkage() && 2324 !New->getTemplateSpecializationInfo() && 2325 !canRedefineFunction(Old, getLangOpts())) { 2326 if (getLangOpts().MicrosoftExt) { 2327 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2328 Diag(OldLocation, PrevDiag); 2329 } else { 2330 Diag(New->getLocation(), diag::err_static_non_static) << New; 2331 Diag(OldLocation, PrevDiag); 2332 return true; 2333 } 2334 } 2335 2336 2337 // If a function is first declared with a calling convention, but is later 2338 // declared or defined without one, all following decls assume the calling 2339 // convention of the first. 2340 // 2341 // It's OK if a function is first declared without a calling convention, 2342 // but is later declared or defined with the default calling convention. 2343 // 2344 // To test if either decl has an explicit calling convention, we look for 2345 // AttributedType sugar nodes on the type as written. If they are missing or 2346 // were canonicalized away, we assume the calling convention was implicit. 2347 // 2348 // Note also that we DO NOT return at this point, because we still have 2349 // other tests to run. 2350 QualType OldQType = Context.getCanonicalType(Old->getType()); 2351 QualType NewQType = Context.getCanonicalType(New->getType()); 2352 const FunctionType *OldType = cast<FunctionType>(OldQType); 2353 const FunctionType *NewType = cast<FunctionType>(NewQType); 2354 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2355 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2356 bool RequiresAdjustment = false; 2357 2358 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2359 FunctionDecl *First = Old->getFirstDecl(); 2360 const FunctionType *FT = 2361 First->getType().getCanonicalType()->castAs<FunctionType>(); 2362 FunctionType::ExtInfo FI = FT->getExtInfo(); 2363 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2364 if (!NewCCExplicit) { 2365 // Inherit the CC from the previous declaration if it was specified 2366 // there but not here. 2367 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2368 RequiresAdjustment = true; 2369 } else { 2370 // Calling conventions aren't compatible, so complain. 2371 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2372 Diag(New->getLocation(), diag::err_cconv_change) 2373 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2374 << !FirstCCExplicit 2375 << (!FirstCCExplicit ? "" : 2376 FunctionType::getNameForCallConv(FI.getCC())); 2377 2378 // Put the note on the first decl, since it is the one that matters. 2379 Diag(First->getLocation(), diag::note_previous_declaration); 2380 return true; 2381 } 2382 } 2383 2384 // FIXME: diagnose the other way around? 2385 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2386 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2387 RequiresAdjustment = true; 2388 } 2389 2390 // Merge regparm attribute. 2391 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2392 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2393 if (NewTypeInfo.getHasRegParm()) { 2394 Diag(New->getLocation(), diag::err_regparm_mismatch) 2395 << NewType->getRegParmType() 2396 << OldType->getRegParmType(); 2397 Diag(OldLocation, diag::note_previous_declaration); 2398 return true; 2399 } 2400 2401 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2402 RequiresAdjustment = true; 2403 } 2404 2405 // Merge ns_returns_retained attribute. 2406 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2407 if (NewTypeInfo.getProducesResult()) { 2408 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2409 Diag(OldLocation, diag::note_previous_declaration); 2410 return true; 2411 } 2412 2413 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2414 RequiresAdjustment = true; 2415 } 2416 2417 if (RequiresAdjustment) { 2418 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2419 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2420 New->setType(QualType(AdjustedType, 0)); 2421 NewQType = Context.getCanonicalType(New->getType()); 2422 NewType = cast<FunctionType>(NewQType); 2423 } 2424 2425 // If this redeclaration makes the function inline, we may need to add it to 2426 // UndefinedButUsed. 2427 if (!Old->isInlined() && New->isInlined() && 2428 !New->hasAttr<GNUInlineAttr>() && 2429 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2430 Old->isUsed(false) && 2431 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2432 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2433 SourceLocation())); 2434 2435 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2436 // about it. 2437 if (New->hasAttr<GNUInlineAttr>() && 2438 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2439 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2440 } 2441 2442 if (getLangOpts().CPlusPlus) { 2443 // (C++98 13.1p2): 2444 // Certain function declarations cannot be overloaded: 2445 // -- Function declarations that differ only in the return type 2446 // cannot be overloaded. 2447 2448 // Go back to the type source info to compare the declared return types, 2449 // per C++1y [dcl.type.auto]p13: 2450 // Redeclarations or specializations of a function or function template 2451 // with a declared return type that uses a placeholder type shall also 2452 // use that placeholder, not a deduced type. 2453 QualType OldDeclaredReturnType = 2454 (Old->getTypeSourceInfo() 2455 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2456 : OldType)->getReturnType(); 2457 QualType NewDeclaredReturnType = 2458 (New->getTypeSourceInfo() 2459 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2460 : NewType)->getReturnType(); 2461 QualType ResQT; 2462 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2463 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2464 New->isLocalExternDecl())) { 2465 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2466 OldDeclaredReturnType->isObjCObjectPointerType()) 2467 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2468 if (ResQT.isNull()) { 2469 if (New->isCXXClassMember() && New->isOutOfLine()) 2470 Diag(New->getLocation(), 2471 diag::err_member_def_does_not_match_ret_type) << New; 2472 else 2473 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2474 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2475 return true; 2476 } 2477 else 2478 NewQType = ResQT; 2479 } 2480 2481 QualType OldReturnType = OldType->getReturnType(); 2482 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2483 if (OldReturnType != NewReturnType) { 2484 // If this function has a deduced return type and has already been 2485 // defined, copy the deduced value from the old declaration. 2486 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2487 if (OldAT && OldAT->isDeduced()) { 2488 New->setType( 2489 SubstAutoType(New->getType(), 2490 OldAT->isDependentType() ? Context.DependentTy 2491 : OldAT->getDeducedType())); 2492 NewQType = Context.getCanonicalType( 2493 SubstAutoType(NewQType, 2494 OldAT->isDependentType() ? Context.DependentTy 2495 : OldAT->getDeducedType())); 2496 } 2497 } 2498 2499 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2500 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2501 if (OldMethod && NewMethod) { 2502 // Preserve triviality. 2503 NewMethod->setTrivial(OldMethod->isTrivial()); 2504 2505 // MSVC allows explicit template specialization at class scope: 2506 // 2 CXXMethodDecls referring to the same function will be injected. 2507 // We don't want a redeclaration error. 2508 bool IsClassScopeExplicitSpecialization = 2509 OldMethod->isFunctionTemplateSpecialization() && 2510 NewMethod->isFunctionTemplateSpecialization(); 2511 bool isFriend = NewMethod->getFriendObjectKind(); 2512 2513 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2514 !IsClassScopeExplicitSpecialization) { 2515 // -- Member function declarations with the same name and the 2516 // same parameter types cannot be overloaded if any of them 2517 // is a static member function declaration. 2518 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2519 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2520 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2521 return true; 2522 } 2523 2524 // C++ [class.mem]p1: 2525 // [...] A member shall not be declared twice in the 2526 // member-specification, except that a nested class or member 2527 // class template can be declared and then later defined. 2528 if (ActiveTemplateInstantiations.empty()) { 2529 unsigned NewDiag; 2530 if (isa<CXXConstructorDecl>(OldMethod)) 2531 NewDiag = diag::err_constructor_redeclared; 2532 else if (isa<CXXDestructorDecl>(NewMethod)) 2533 NewDiag = diag::err_destructor_redeclared; 2534 else if (isa<CXXConversionDecl>(NewMethod)) 2535 NewDiag = diag::err_conv_function_redeclared; 2536 else 2537 NewDiag = diag::err_member_redeclared; 2538 2539 Diag(New->getLocation(), NewDiag); 2540 } else { 2541 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2542 << New << New->getType(); 2543 } 2544 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2545 2546 // Complain if this is an explicit declaration of a special 2547 // member that was initially declared implicitly. 2548 // 2549 // As an exception, it's okay to befriend such methods in order 2550 // to permit the implicit constructor/destructor/operator calls. 2551 } else if (OldMethod->isImplicit()) { 2552 if (isFriend) { 2553 NewMethod->setImplicit(); 2554 } else { 2555 Diag(NewMethod->getLocation(), 2556 diag::err_definition_of_implicitly_declared_member) 2557 << New << getSpecialMember(OldMethod); 2558 return true; 2559 } 2560 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2561 Diag(NewMethod->getLocation(), 2562 diag::err_definition_of_explicitly_defaulted_member) 2563 << getSpecialMember(OldMethod); 2564 return true; 2565 } 2566 } 2567 2568 // C++11 [dcl.attr.noreturn]p1: 2569 // The first declaration of a function shall specify the noreturn 2570 // attribute if any declaration of that function specifies the noreturn 2571 // attribute. 2572 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2573 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2574 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2575 Diag(Old->getFirstDecl()->getLocation(), 2576 diag::note_noreturn_missing_first_decl); 2577 } 2578 2579 // C++11 [dcl.attr.depend]p2: 2580 // The first declaration of a function shall specify the 2581 // carries_dependency attribute for its declarator-id if any declaration 2582 // of the function specifies the carries_dependency attribute. 2583 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2584 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2585 Diag(CDA->getLocation(), 2586 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2587 Diag(Old->getFirstDecl()->getLocation(), 2588 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2589 } 2590 2591 // (C++98 8.3.5p3): 2592 // All declarations for a function shall agree exactly in both the 2593 // return type and the parameter-type-list. 2594 // We also want to respect all the extended bits except noreturn. 2595 2596 // noreturn should now match unless the old type info didn't have it. 2597 QualType OldQTypeForComparison = OldQType; 2598 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2599 assert(OldQType == QualType(OldType, 0)); 2600 const FunctionType *OldTypeForComparison 2601 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2602 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2603 assert(OldQTypeForComparison.isCanonical()); 2604 } 2605 2606 if (haveIncompatibleLanguageLinkages(Old, New)) { 2607 // As a special case, retain the language linkage from previous 2608 // declarations of a friend function as an extension. 2609 // 2610 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2611 // and is useful because there's otherwise no way to specify language 2612 // linkage within class scope. 2613 // 2614 // Check cautiously as the friend object kind isn't yet complete. 2615 if (New->getFriendObjectKind() != Decl::FOK_None) { 2616 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2617 Diag(OldLocation, PrevDiag); 2618 } else { 2619 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2620 Diag(OldLocation, PrevDiag); 2621 return true; 2622 } 2623 } 2624 2625 if (OldQTypeForComparison == NewQType) 2626 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2627 2628 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2629 New->isLocalExternDecl()) { 2630 // It's OK if we couldn't merge types for a local function declaraton 2631 // if either the old or new type is dependent. We'll merge the types 2632 // when we instantiate the function. 2633 return false; 2634 } 2635 2636 // Fall through for conflicting redeclarations and redefinitions. 2637 } 2638 2639 // C: Function types need to be compatible, not identical. This handles 2640 // duplicate function decls like "void f(int); void f(enum X);" properly. 2641 if (!getLangOpts().CPlusPlus && 2642 Context.typesAreCompatible(OldQType, NewQType)) { 2643 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2644 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2645 const FunctionProtoType *OldProto = 0; 2646 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2647 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2648 // The old declaration provided a function prototype, but the 2649 // new declaration does not. Merge in the prototype. 2650 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2651 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2652 NewQType = 2653 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2654 OldProto->getExtProtoInfo()); 2655 New->setType(NewQType); 2656 New->setHasInheritedPrototype(); 2657 2658 // Synthesize a parameter for each argument type. 2659 SmallVector<ParmVarDecl*, 16> Params; 2660 for (const auto &ParamType : OldProto->param_types()) { 2661 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2662 SourceLocation(), 0, ParamType, 2663 /*TInfo=*/0, SC_None, 0); 2664 Param->setScopeInfo(0, Params.size()); 2665 Param->setImplicit(); 2666 Params.push_back(Param); 2667 } 2668 2669 New->setParams(Params); 2670 } 2671 2672 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2673 } 2674 2675 // GNU C permits a K&R definition to follow a prototype declaration 2676 // if the declared types of the parameters in the K&R definition 2677 // match the types in the prototype declaration, even when the 2678 // promoted types of the parameters from the K&R definition differ 2679 // from the types in the prototype. GCC then keeps the types from 2680 // the prototype. 2681 // 2682 // If a variadic prototype is followed by a non-variadic K&R definition, 2683 // the K&R definition becomes variadic. This is sort of an edge case, but 2684 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2685 // C99 6.9.1p8. 2686 if (!getLangOpts().CPlusPlus && 2687 Old->hasPrototype() && !New->hasPrototype() && 2688 New->getType()->getAs<FunctionProtoType>() && 2689 Old->getNumParams() == New->getNumParams()) { 2690 SmallVector<QualType, 16> ArgTypes; 2691 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2692 const FunctionProtoType *OldProto 2693 = Old->getType()->getAs<FunctionProtoType>(); 2694 const FunctionProtoType *NewProto 2695 = New->getType()->getAs<FunctionProtoType>(); 2696 2697 // Determine whether this is the GNU C extension. 2698 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2699 NewProto->getReturnType()); 2700 bool LooseCompatible = !MergedReturn.isNull(); 2701 for (unsigned Idx = 0, End = Old->getNumParams(); 2702 LooseCompatible && Idx != End; ++Idx) { 2703 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2704 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2705 if (Context.typesAreCompatible(OldParm->getType(), 2706 NewProto->getParamType(Idx))) { 2707 ArgTypes.push_back(NewParm->getType()); 2708 } else if (Context.typesAreCompatible(OldParm->getType(), 2709 NewParm->getType(), 2710 /*CompareUnqualified=*/true)) { 2711 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2712 NewProto->getParamType(Idx) }; 2713 Warnings.push_back(Warn); 2714 ArgTypes.push_back(NewParm->getType()); 2715 } else 2716 LooseCompatible = false; 2717 } 2718 2719 if (LooseCompatible) { 2720 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2721 Diag(Warnings[Warn].NewParm->getLocation(), 2722 diag::ext_param_promoted_not_compatible_with_prototype) 2723 << Warnings[Warn].PromotedType 2724 << Warnings[Warn].OldParm->getType(); 2725 if (Warnings[Warn].OldParm->getLocation().isValid()) 2726 Diag(Warnings[Warn].OldParm->getLocation(), 2727 diag::note_previous_declaration); 2728 } 2729 2730 if (MergeTypeWithOld) 2731 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2732 OldProto->getExtProtoInfo())); 2733 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2734 } 2735 2736 // Fall through to diagnose conflicting types. 2737 } 2738 2739 // A function that has already been declared has been redeclared or 2740 // defined with a different type; show an appropriate diagnostic. 2741 2742 // If the previous declaration was an implicitly-generated builtin 2743 // declaration, then at the very least we should use a specialized note. 2744 unsigned BuiltinID; 2745 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2746 // If it's actually a library-defined builtin function like 'malloc' 2747 // or 'printf', just warn about the incompatible redeclaration. 2748 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2749 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2750 Diag(OldLocation, diag::note_previous_builtin_declaration) 2751 << Old << Old->getType(); 2752 2753 // If this is a global redeclaration, just forget hereafter 2754 // about the "builtin-ness" of the function. 2755 // 2756 // Doing this for local extern declarations is problematic. If 2757 // the builtin declaration remains visible, a second invalid 2758 // local declaration will produce a hard error; if it doesn't 2759 // remain visible, a single bogus local redeclaration (which is 2760 // actually only a warning) could break all the downstream code. 2761 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2762 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2763 2764 return false; 2765 } 2766 2767 PrevDiag = diag::note_previous_builtin_declaration; 2768 } 2769 2770 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2771 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2772 return true; 2773 } 2774 2775 /// \brief Completes the merge of two function declarations that are 2776 /// known to be compatible. 2777 /// 2778 /// This routine handles the merging of attributes and other 2779 /// properties of function declarations from the old declaration to 2780 /// the new declaration, once we know that New is in fact a 2781 /// redeclaration of Old. 2782 /// 2783 /// \returns false 2784 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2785 Scope *S, bool MergeTypeWithOld) { 2786 // Merge the attributes 2787 mergeDeclAttributes(New, Old); 2788 2789 // Merge "pure" flag. 2790 if (Old->isPure()) 2791 New->setPure(); 2792 2793 // Merge "used" flag. 2794 if (Old->getMostRecentDecl()->isUsed(false)) 2795 New->setIsUsed(); 2796 2797 // Merge attributes from the parameters. These can mismatch with K&R 2798 // declarations. 2799 if (New->getNumParams() == Old->getNumParams()) 2800 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2801 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2802 *this); 2803 2804 if (getLangOpts().CPlusPlus) 2805 return MergeCXXFunctionDecl(New, Old, S); 2806 2807 // Merge the function types so the we get the composite types for the return 2808 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2809 // was visible. 2810 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2811 if (!Merged.isNull() && MergeTypeWithOld) 2812 New->setType(Merged); 2813 2814 return false; 2815 } 2816 2817 2818 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2819 ObjCMethodDecl *oldMethod) { 2820 2821 // Merge the attributes, including deprecated/unavailable 2822 AvailabilityMergeKind MergeKind = 2823 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2824 : AMK_Override; 2825 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2826 2827 // Merge attributes from the parameters. 2828 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2829 oe = oldMethod->param_end(); 2830 for (ObjCMethodDecl::param_iterator 2831 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2832 ni != ne && oi != oe; ++ni, ++oi) 2833 mergeParamDeclAttributes(*ni, *oi, *this); 2834 2835 CheckObjCMethodOverride(newMethod, oldMethod); 2836 } 2837 2838 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2839 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2840 /// emitting diagnostics as appropriate. 2841 /// 2842 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2843 /// to here in AddInitializerToDecl. We can't check them before the initializer 2844 /// is attached. 2845 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2846 bool MergeTypeWithOld) { 2847 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2848 return; 2849 2850 QualType MergedT; 2851 if (getLangOpts().CPlusPlus) { 2852 if (New->getType()->isUndeducedType()) { 2853 // We don't know what the new type is until the initializer is attached. 2854 return; 2855 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2856 // These could still be something that needs exception specs checked. 2857 return MergeVarDeclExceptionSpecs(New, Old); 2858 } 2859 // C++ [basic.link]p10: 2860 // [...] the types specified by all declarations referring to a given 2861 // object or function shall be identical, except that declarations for an 2862 // array object can specify array types that differ by the presence or 2863 // absence of a major array bound (8.3.4). 2864 else if (Old->getType()->isIncompleteArrayType() && 2865 New->getType()->isArrayType()) { 2866 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2867 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2868 if (Context.hasSameType(OldArray->getElementType(), 2869 NewArray->getElementType())) 2870 MergedT = New->getType(); 2871 } else if (Old->getType()->isArrayType() && 2872 New->getType()->isIncompleteArrayType()) { 2873 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2874 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2875 if (Context.hasSameType(OldArray->getElementType(), 2876 NewArray->getElementType())) 2877 MergedT = Old->getType(); 2878 } else if (New->getType()->isObjCObjectPointerType() && 2879 Old->getType()->isObjCObjectPointerType()) { 2880 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2881 Old->getType()); 2882 } 2883 } else { 2884 // C 6.2.7p2: 2885 // All declarations that refer to the same object or function shall have 2886 // compatible type. 2887 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2888 } 2889 if (MergedT.isNull()) { 2890 // It's OK if we couldn't merge types if either type is dependent, for a 2891 // block-scope variable. In other cases (static data members of class 2892 // templates, variable templates, ...), we require the types to be 2893 // equivalent. 2894 // FIXME: The C++ standard doesn't say anything about this. 2895 if ((New->getType()->isDependentType() || 2896 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2897 // If the old type was dependent, we can't merge with it, so the new type 2898 // becomes dependent for now. We'll reproduce the original type when we 2899 // instantiate the TypeSourceInfo for the variable. 2900 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2901 New->setType(Context.DependentTy); 2902 return; 2903 } 2904 2905 // FIXME: Even if this merging succeeds, some other non-visible declaration 2906 // of this variable might have an incompatible type. For instance: 2907 // 2908 // extern int arr[]; 2909 // void f() { extern int arr[2]; } 2910 // void g() { extern int arr[3]; } 2911 // 2912 // Neither C nor C++ requires a diagnostic for this, but we should still try 2913 // to diagnose it. 2914 Diag(New->getLocation(), diag::err_redefinition_different_type) 2915 << New->getDeclName() << New->getType() << Old->getType(); 2916 Diag(Old->getLocation(), diag::note_previous_definition); 2917 return New->setInvalidDecl(); 2918 } 2919 2920 // Don't actually update the type on the new declaration if the old 2921 // declaration was an extern declaration in a different scope. 2922 if (MergeTypeWithOld) 2923 New->setType(MergedT); 2924 } 2925 2926 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2927 LookupResult &Previous) { 2928 // C11 6.2.7p4: 2929 // For an identifier with internal or external linkage declared 2930 // in a scope in which a prior declaration of that identifier is 2931 // visible, if the prior declaration specifies internal or 2932 // external linkage, the type of the identifier at the later 2933 // declaration becomes the composite type. 2934 // 2935 // If the variable isn't visible, we do not merge with its type. 2936 if (Previous.isShadowed()) 2937 return false; 2938 2939 if (S.getLangOpts().CPlusPlus) { 2940 // C++11 [dcl.array]p3: 2941 // If there is a preceding declaration of the entity in the same 2942 // scope in which the bound was specified, an omitted array bound 2943 // is taken to be the same as in that earlier declaration. 2944 return NewVD->isPreviousDeclInSameBlockScope() || 2945 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2946 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2947 } else { 2948 // If the old declaration was function-local, don't merge with its 2949 // type unless we're in the same function. 2950 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2951 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2952 } 2953 } 2954 2955 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2956 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2957 /// situation, merging decls or emitting diagnostics as appropriate. 2958 /// 2959 /// Tentative definition rules (C99 6.9.2p2) are checked by 2960 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2961 /// definitions here, since the initializer hasn't been attached. 2962 /// 2963 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2964 // If the new decl is already invalid, don't do any other checking. 2965 if (New->isInvalidDecl()) 2966 return; 2967 2968 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 2969 2970 // Verify the old decl was also a variable or variable template. 2971 VarDecl *Old = 0; 2972 VarTemplateDecl *OldTemplate = 0; 2973 if (Previous.isSingleResult()) { 2974 if (NewTemplate) { 2975 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 2976 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0; 2977 } else 2978 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2979 } 2980 if (!Old) { 2981 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2982 << New->getDeclName(); 2983 Diag(Previous.getRepresentativeDecl()->getLocation(), 2984 diag::note_previous_definition); 2985 return New->setInvalidDecl(); 2986 } 2987 2988 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 2989 return; 2990 2991 // Ensure the template parameters are compatible. 2992 if (NewTemplate && 2993 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 2994 OldTemplate->getTemplateParameters(), 2995 /*Complain=*/true, TPL_TemplateMatch)) 2996 return; 2997 2998 // C++ [class.mem]p1: 2999 // A member shall not be declared twice in the member-specification [...] 3000 // 3001 // Here, we need only consider static data members. 3002 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3003 Diag(New->getLocation(), diag::err_duplicate_member) 3004 << New->getIdentifier(); 3005 Diag(Old->getLocation(), diag::note_previous_declaration); 3006 New->setInvalidDecl(); 3007 } 3008 3009 mergeDeclAttributes(New, Old); 3010 // Warn if an already-declared variable is made a weak_import in a subsequent 3011 // declaration 3012 if (New->hasAttr<WeakImportAttr>() && 3013 Old->getStorageClass() == SC_None && 3014 !Old->hasAttr<WeakImportAttr>()) { 3015 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3016 Diag(Old->getLocation(), diag::note_previous_definition); 3017 // Remove weak_import attribute on new declaration. 3018 New->dropAttr<WeakImportAttr>(); 3019 } 3020 3021 // Merge the types. 3022 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3023 3024 if (New->isInvalidDecl()) 3025 return; 3026 3027 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3028 if (New->getStorageClass() == SC_Static && 3029 !New->isStaticDataMember() && 3030 Old->hasExternalFormalLinkage()) { 3031 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3032 Diag(Old->getLocation(), diag::note_previous_definition); 3033 return New->setInvalidDecl(); 3034 } 3035 // C99 6.2.2p4: 3036 // For an identifier declared with the storage-class specifier 3037 // extern in a scope in which a prior declaration of that 3038 // identifier is visible,23) if the prior declaration specifies 3039 // internal or external linkage, the linkage of the identifier at 3040 // the later declaration is the same as the linkage specified at 3041 // the prior declaration. If no prior declaration is visible, or 3042 // if the prior declaration specifies no linkage, then the 3043 // identifier has external linkage. 3044 if (New->hasExternalStorage() && Old->hasLinkage()) 3045 /* Okay */; 3046 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3047 !New->isStaticDataMember() && 3048 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3049 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3050 Diag(Old->getLocation(), diag::note_previous_definition); 3051 return New->setInvalidDecl(); 3052 } 3053 3054 // Check if extern is followed by non-extern and vice-versa. 3055 if (New->hasExternalStorage() && 3056 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3057 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3058 Diag(Old->getLocation(), diag::note_previous_definition); 3059 return New->setInvalidDecl(); 3060 } 3061 if (Old->hasLinkage() && New->isLocalVarDecl() && 3062 !New->hasExternalStorage()) { 3063 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3064 Diag(Old->getLocation(), diag::note_previous_definition); 3065 return New->setInvalidDecl(); 3066 } 3067 3068 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3069 3070 // FIXME: The test for external storage here seems wrong? We still 3071 // need to check for mismatches. 3072 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3073 // Don't complain about out-of-line definitions of static members. 3074 !(Old->getLexicalDeclContext()->isRecord() && 3075 !New->getLexicalDeclContext()->isRecord())) { 3076 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3077 Diag(Old->getLocation(), diag::note_previous_definition); 3078 return New->setInvalidDecl(); 3079 } 3080 3081 if (New->getTLSKind() != Old->getTLSKind()) { 3082 if (!Old->getTLSKind()) { 3083 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3084 Diag(Old->getLocation(), diag::note_previous_declaration); 3085 } else if (!New->getTLSKind()) { 3086 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3087 Diag(Old->getLocation(), diag::note_previous_declaration); 3088 } else { 3089 // Do not allow redeclaration to change the variable between requiring 3090 // static and dynamic initialization. 3091 // FIXME: GCC allows this, but uses the TLS keyword on the first 3092 // declaration to determine the kind. Do we need to be compatible here? 3093 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3094 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3095 Diag(Old->getLocation(), diag::note_previous_declaration); 3096 } 3097 } 3098 3099 // C++ doesn't have tentative definitions, so go right ahead and check here. 3100 const VarDecl *Def; 3101 if (getLangOpts().CPlusPlus && 3102 New->isThisDeclarationADefinition() == VarDecl::Definition && 3103 (Def = Old->getDefinition())) { 3104 Diag(New->getLocation(), diag::err_redefinition) << New; 3105 Diag(Def->getLocation(), diag::note_previous_definition); 3106 New->setInvalidDecl(); 3107 return; 3108 } 3109 3110 if (haveIncompatibleLanguageLinkages(Old, New)) { 3111 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3112 Diag(Old->getLocation(), diag::note_previous_definition); 3113 New->setInvalidDecl(); 3114 return; 3115 } 3116 3117 // Merge "used" flag. 3118 if (Old->getMostRecentDecl()->isUsed(false)) 3119 New->setIsUsed(); 3120 3121 // Keep a chain of previous declarations. 3122 New->setPreviousDecl(Old); 3123 if (NewTemplate) 3124 NewTemplate->setPreviousDecl(OldTemplate); 3125 3126 // Inherit access appropriately. 3127 New->setAccess(Old->getAccess()); 3128 if (NewTemplate) 3129 NewTemplate->setAccess(New->getAccess()); 3130 } 3131 3132 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3133 /// no declarator (e.g. "struct foo;") is parsed. 3134 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3135 DeclSpec &DS) { 3136 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3137 } 3138 3139 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3140 if (!S.Context.getLangOpts().CPlusPlus) 3141 return; 3142 3143 if (isa<CXXRecordDecl>(Tag->getParent())) { 3144 // If this tag is the direct child of a class, number it if 3145 // it is anonymous. 3146 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3147 return; 3148 MangleNumberingContext &MCtx = 3149 S.Context.getManglingNumberContext(Tag->getParent()); 3150 S.Context.setManglingNumber( 3151 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3152 return; 3153 } 3154 3155 // If this tag isn't a direct child of a class, number it if it is local. 3156 Decl *ManglingContextDecl; 3157 if (MangleNumberingContext *MCtx = 3158 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3159 ManglingContextDecl)) { 3160 S.Context.setManglingNumber( 3161 Tag, 3162 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3163 } 3164 } 3165 3166 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3167 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3168 /// parameters to cope with template friend declarations. 3169 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3170 DeclSpec &DS, 3171 MultiTemplateParamsArg TemplateParams, 3172 bool IsExplicitInstantiation) { 3173 Decl *TagD = 0; 3174 TagDecl *Tag = 0; 3175 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3176 DS.getTypeSpecType() == DeclSpec::TST_struct || 3177 DS.getTypeSpecType() == DeclSpec::TST_interface || 3178 DS.getTypeSpecType() == DeclSpec::TST_union || 3179 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3180 TagD = DS.getRepAsDecl(); 3181 3182 if (!TagD) // We probably had an error 3183 return 0; 3184 3185 // Note that the above type specs guarantee that the 3186 // type rep is a Decl, whereas in many of the others 3187 // it's a Type. 3188 if (isa<TagDecl>(TagD)) 3189 Tag = cast<TagDecl>(TagD); 3190 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3191 Tag = CTD->getTemplatedDecl(); 3192 } 3193 3194 if (Tag) { 3195 HandleTagNumbering(*this, Tag, S); 3196 Tag->setFreeStanding(); 3197 if (Tag->isInvalidDecl()) 3198 return Tag; 3199 } 3200 3201 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3202 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3203 // or incomplete types shall not be restrict-qualified." 3204 if (TypeQuals & DeclSpec::TQ_restrict) 3205 Diag(DS.getRestrictSpecLoc(), 3206 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3207 << DS.getSourceRange(); 3208 } 3209 3210 if (DS.isConstexprSpecified()) { 3211 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3212 // and definitions of functions and variables. 3213 if (Tag) 3214 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3215 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3216 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3217 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3218 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3219 else 3220 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3221 // Don't emit warnings after this error. 3222 return TagD; 3223 } 3224 3225 DiagnoseFunctionSpecifiers(DS); 3226 3227 if (DS.isFriendSpecified()) { 3228 // If we're dealing with a decl but not a TagDecl, assume that 3229 // whatever routines created it handled the friendship aspect. 3230 if (TagD && !Tag) 3231 return 0; 3232 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3233 } 3234 3235 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3236 bool IsExplicitSpecialization = 3237 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3238 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3239 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3240 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3241 // nested-name-specifier unless it is an explicit instantiation 3242 // or an explicit specialization. 3243 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3244 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3245 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3246 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3247 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3248 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3249 << SS.getRange(); 3250 return 0; 3251 } 3252 3253 // Track whether this decl-specifier declares anything. 3254 bool DeclaresAnything = true; 3255 3256 // Handle anonymous struct definitions. 3257 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3258 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3259 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3260 if (getLangOpts().CPlusPlus || 3261 Record->getDeclContext()->isRecord()) 3262 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3263 3264 DeclaresAnything = false; 3265 } 3266 } 3267 3268 // Check for Microsoft C extension: anonymous struct member. 3269 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3270 CurContext->isRecord() && 3271 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3272 // Handle 2 kinds of anonymous struct: 3273 // struct STRUCT; 3274 // and 3275 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3276 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3277 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3278 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3279 DS.getRepAsType().get()->isStructureType())) { 3280 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3281 << DS.getSourceRange(); 3282 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3283 } 3284 } 3285 3286 // Skip all the checks below if we have a type error. 3287 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3288 (TagD && TagD->isInvalidDecl())) 3289 return TagD; 3290 3291 if (getLangOpts().CPlusPlus && 3292 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3293 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3294 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3295 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3296 DeclaresAnything = false; 3297 3298 if (!DS.isMissingDeclaratorOk()) { 3299 // Customize diagnostic for a typedef missing a name. 3300 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3301 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3302 << DS.getSourceRange(); 3303 else 3304 DeclaresAnything = false; 3305 } 3306 3307 if (DS.isModulePrivateSpecified() && 3308 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3309 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3310 << Tag->getTagKind() 3311 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3312 3313 ActOnDocumentableDecl(TagD); 3314 3315 // C 6.7/2: 3316 // A declaration [...] shall declare at least a declarator [...], a tag, 3317 // or the members of an enumeration. 3318 // C++ [dcl.dcl]p3: 3319 // [If there are no declarators], and except for the declaration of an 3320 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3321 // names into the program, or shall redeclare a name introduced by a 3322 // previous declaration. 3323 if (!DeclaresAnything) { 3324 // In C, we allow this as a (popular) extension / bug. Don't bother 3325 // producing further diagnostics for redundant qualifiers after this. 3326 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3327 return TagD; 3328 } 3329 3330 // C++ [dcl.stc]p1: 3331 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3332 // init-declarator-list of the declaration shall not be empty. 3333 // C++ [dcl.fct.spec]p1: 3334 // If a cv-qualifier appears in a decl-specifier-seq, the 3335 // init-declarator-list of the declaration shall not be empty. 3336 // 3337 // Spurious qualifiers here appear to be valid in C. 3338 unsigned DiagID = diag::warn_standalone_specifier; 3339 if (getLangOpts().CPlusPlus) 3340 DiagID = diag::ext_standalone_specifier; 3341 3342 // Note that a linkage-specification sets a storage class, but 3343 // 'extern "C" struct foo;' is actually valid and not theoretically 3344 // useless. 3345 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3346 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3347 Diag(DS.getStorageClassSpecLoc(), DiagID) 3348 << DeclSpec::getSpecifierName(SCS); 3349 3350 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3351 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3352 << DeclSpec::getSpecifierName(TSCS); 3353 if (DS.getTypeQualifiers()) { 3354 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3355 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3356 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3357 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3358 // Restrict is covered above. 3359 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3360 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3361 } 3362 3363 // Warn about ignored type attributes, for example: 3364 // __attribute__((aligned)) struct A; 3365 // Attributes should be placed after tag to apply to type declaration. 3366 if (!DS.getAttributes().empty()) { 3367 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3368 if (TypeSpecType == DeclSpec::TST_class || 3369 TypeSpecType == DeclSpec::TST_struct || 3370 TypeSpecType == DeclSpec::TST_interface || 3371 TypeSpecType == DeclSpec::TST_union || 3372 TypeSpecType == DeclSpec::TST_enum) { 3373 AttributeList* attrs = DS.getAttributes().getList(); 3374 while (attrs) { 3375 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3376 << attrs->getName() 3377 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3378 TypeSpecType == DeclSpec::TST_struct ? 1 : 3379 TypeSpecType == DeclSpec::TST_union ? 2 : 3380 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3381 attrs = attrs->getNext(); 3382 } 3383 } 3384 } 3385 3386 return TagD; 3387 } 3388 3389 /// We are trying to inject an anonymous member into the given scope; 3390 /// check if there's an existing declaration that can't be overloaded. 3391 /// 3392 /// \return true if this is a forbidden redeclaration 3393 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3394 Scope *S, 3395 DeclContext *Owner, 3396 DeclarationName Name, 3397 SourceLocation NameLoc, 3398 unsigned diagnostic) { 3399 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3400 Sema::ForRedeclaration); 3401 if (!SemaRef.LookupName(R, S)) return false; 3402 3403 if (R.getAsSingle<TagDecl>()) 3404 return false; 3405 3406 // Pick a representative declaration. 3407 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3408 assert(PrevDecl && "Expected a non-null Decl"); 3409 3410 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3411 return false; 3412 3413 SemaRef.Diag(NameLoc, diagnostic) << Name; 3414 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3415 3416 return true; 3417 } 3418 3419 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3420 /// anonymous struct or union AnonRecord into the owning context Owner 3421 /// and scope S. This routine will be invoked just after we realize 3422 /// that an unnamed union or struct is actually an anonymous union or 3423 /// struct, e.g., 3424 /// 3425 /// @code 3426 /// union { 3427 /// int i; 3428 /// float f; 3429 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3430 /// // f into the surrounding scope.x 3431 /// @endcode 3432 /// 3433 /// This routine is recursive, injecting the names of nested anonymous 3434 /// structs/unions into the owning context and scope as well. 3435 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3436 DeclContext *Owner, 3437 RecordDecl *AnonRecord, 3438 AccessSpecifier AS, 3439 SmallVectorImpl<NamedDecl *> &Chaining, 3440 bool MSAnonStruct) { 3441 unsigned diagKind 3442 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3443 : diag::err_anonymous_struct_member_redecl; 3444 3445 bool Invalid = false; 3446 3447 // Look every FieldDecl and IndirectFieldDecl with a name. 3448 for (auto *D : AnonRecord->decls()) { 3449 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3450 cast<NamedDecl>(D)->getDeclName()) { 3451 ValueDecl *VD = cast<ValueDecl>(D); 3452 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3453 VD->getLocation(), diagKind)) { 3454 // C++ [class.union]p2: 3455 // The names of the members of an anonymous union shall be 3456 // distinct from the names of any other entity in the 3457 // scope in which the anonymous union is declared. 3458 Invalid = true; 3459 } else { 3460 // C++ [class.union]p2: 3461 // For the purpose of name lookup, after the anonymous union 3462 // definition, the members of the anonymous union are 3463 // considered to have been defined in the scope in which the 3464 // anonymous union is declared. 3465 unsigned OldChainingSize = Chaining.size(); 3466 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3467 for (auto *PI : IF->chain()) 3468 Chaining.push_back(PI); 3469 else 3470 Chaining.push_back(VD); 3471 3472 assert(Chaining.size() >= 2); 3473 NamedDecl **NamedChain = 3474 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3475 for (unsigned i = 0; i < Chaining.size(); i++) 3476 NamedChain[i] = Chaining[i]; 3477 3478 IndirectFieldDecl* IndirectField = 3479 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3480 VD->getIdentifier(), VD->getType(), 3481 NamedChain, Chaining.size()); 3482 3483 IndirectField->setAccess(AS); 3484 IndirectField->setImplicit(); 3485 SemaRef.PushOnScopeChains(IndirectField, S); 3486 3487 // That includes picking up the appropriate access specifier. 3488 if (AS != AS_none) IndirectField->setAccess(AS); 3489 3490 Chaining.resize(OldChainingSize); 3491 } 3492 } 3493 } 3494 3495 return Invalid; 3496 } 3497 3498 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3499 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3500 /// illegal input values are mapped to SC_None. 3501 static StorageClass 3502 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3503 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3504 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3505 "Parser allowed 'typedef' as storage class VarDecl."); 3506 switch (StorageClassSpec) { 3507 case DeclSpec::SCS_unspecified: return SC_None; 3508 case DeclSpec::SCS_extern: 3509 if (DS.isExternInLinkageSpec()) 3510 return SC_None; 3511 return SC_Extern; 3512 case DeclSpec::SCS_static: return SC_Static; 3513 case DeclSpec::SCS_auto: return SC_Auto; 3514 case DeclSpec::SCS_register: return SC_Register; 3515 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3516 // Illegal SCSs map to None: error reporting is up to the caller. 3517 case DeclSpec::SCS_mutable: // Fall through. 3518 case DeclSpec::SCS_typedef: return SC_None; 3519 } 3520 llvm_unreachable("unknown storage class specifier"); 3521 } 3522 3523 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3524 assert(Record->hasInClassInitializer()); 3525 3526 for (const auto *I : Record->decls()) { 3527 const auto *FD = dyn_cast<FieldDecl>(I); 3528 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3529 FD = IFD->getAnonField(); 3530 if (FD && FD->hasInClassInitializer()) 3531 return FD->getLocation(); 3532 } 3533 3534 llvm_unreachable("couldn't find in-class initializer"); 3535 } 3536 3537 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3538 SourceLocation DefaultInitLoc) { 3539 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3540 return; 3541 3542 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3543 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3544 } 3545 3546 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3547 CXXRecordDecl *AnonUnion) { 3548 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3549 return; 3550 3551 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3552 } 3553 3554 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3555 /// anonymous structure or union. Anonymous unions are a C++ feature 3556 /// (C++ [class.union]) and a C11 feature; anonymous structures 3557 /// are a C11 feature and GNU C++ extension. 3558 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3559 AccessSpecifier AS, 3560 RecordDecl *Record, 3561 const PrintingPolicy &Policy) { 3562 DeclContext *Owner = Record->getDeclContext(); 3563 3564 // Diagnose whether this anonymous struct/union is an extension. 3565 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3566 Diag(Record->getLocation(), diag::ext_anonymous_union); 3567 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3568 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3569 else if (!Record->isUnion() && !getLangOpts().C11) 3570 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3571 3572 // C and C++ require different kinds of checks for anonymous 3573 // structs/unions. 3574 bool Invalid = false; 3575 if (getLangOpts().CPlusPlus) { 3576 const char* PrevSpec = 0; 3577 unsigned DiagID; 3578 if (Record->isUnion()) { 3579 // C++ [class.union]p6: 3580 // Anonymous unions declared in a named namespace or in the 3581 // global namespace shall be declared static. 3582 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3583 (isa<TranslationUnitDecl>(Owner) || 3584 (isa<NamespaceDecl>(Owner) && 3585 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3586 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3587 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3588 3589 // Recover by adding 'static'. 3590 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3591 PrevSpec, DiagID, Policy); 3592 } 3593 // C++ [class.union]p6: 3594 // A storage class is not allowed in a declaration of an 3595 // anonymous union in a class scope. 3596 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3597 isa<RecordDecl>(Owner)) { 3598 Diag(DS.getStorageClassSpecLoc(), 3599 diag::err_anonymous_union_with_storage_spec) 3600 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3601 3602 // Recover by removing the storage specifier. 3603 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3604 SourceLocation(), 3605 PrevSpec, DiagID, Context.getPrintingPolicy()); 3606 } 3607 } 3608 3609 // Ignore const/volatile/restrict qualifiers. 3610 if (DS.getTypeQualifiers()) { 3611 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3612 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3613 << Record->isUnion() << "const" 3614 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3615 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3616 Diag(DS.getVolatileSpecLoc(), 3617 diag::ext_anonymous_struct_union_qualified) 3618 << Record->isUnion() << "volatile" 3619 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3620 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3621 Diag(DS.getRestrictSpecLoc(), 3622 diag::ext_anonymous_struct_union_qualified) 3623 << Record->isUnion() << "restrict" 3624 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3625 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3626 Diag(DS.getAtomicSpecLoc(), 3627 diag::ext_anonymous_struct_union_qualified) 3628 << Record->isUnion() << "_Atomic" 3629 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3630 3631 DS.ClearTypeQualifiers(); 3632 } 3633 3634 // C++ [class.union]p2: 3635 // The member-specification of an anonymous union shall only 3636 // define non-static data members. [Note: nested types and 3637 // functions cannot be declared within an anonymous union. ] 3638 for (auto *Mem : Record->decls()) { 3639 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3640 // C++ [class.union]p3: 3641 // An anonymous union shall not have private or protected 3642 // members (clause 11). 3643 assert(FD->getAccess() != AS_none); 3644 if (FD->getAccess() != AS_public) { 3645 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3646 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3647 Invalid = true; 3648 } 3649 3650 // C++ [class.union]p1 3651 // An object of a class with a non-trivial constructor, a non-trivial 3652 // copy constructor, a non-trivial destructor, or a non-trivial copy 3653 // assignment operator cannot be a member of a union, nor can an 3654 // array of such objects. 3655 if (CheckNontrivialField(FD)) 3656 Invalid = true; 3657 } else if (Mem->isImplicit()) { 3658 // Any implicit members are fine. 3659 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3660 // This is a type that showed up in an 3661 // elaborated-type-specifier inside the anonymous struct or 3662 // union, but which actually declares a type outside of the 3663 // anonymous struct or union. It's okay. 3664 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3665 if (!MemRecord->isAnonymousStructOrUnion() && 3666 MemRecord->getDeclName()) { 3667 // Visual C++ allows type definition in anonymous struct or union. 3668 if (getLangOpts().MicrosoftExt) 3669 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3670 << (int)Record->isUnion(); 3671 else { 3672 // This is a nested type declaration. 3673 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3674 << (int)Record->isUnion(); 3675 Invalid = true; 3676 } 3677 } else { 3678 // This is an anonymous type definition within another anonymous type. 3679 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3680 // not part of standard C++. 3681 Diag(MemRecord->getLocation(), 3682 diag::ext_anonymous_record_with_anonymous_type) 3683 << (int)Record->isUnion(); 3684 } 3685 } else if (isa<AccessSpecDecl>(Mem)) { 3686 // Any access specifier is fine. 3687 } else { 3688 // We have something that isn't a non-static data 3689 // member. Complain about it. 3690 unsigned DK = diag::err_anonymous_record_bad_member; 3691 if (isa<TypeDecl>(Mem)) 3692 DK = diag::err_anonymous_record_with_type; 3693 else if (isa<FunctionDecl>(Mem)) 3694 DK = diag::err_anonymous_record_with_function; 3695 else if (isa<VarDecl>(Mem)) 3696 DK = diag::err_anonymous_record_with_static; 3697 3698 // Visual C++ allows type definition in anonymous struct or union. 3699 if (getLangOpts().MicrosoftExt && 3700 DK == diag::err_anonymous_record_with_type) 3701 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3702 << (int)Record->isUnion(); 3703 else { 3704 Diag(Mem->getLocation(), DK) 3705 << (int)Record->isUnion(); 3706 Invalid = true; 3707 } 3708 } 3709 } 3710 3711 // C++11 [class.union]p8 (DR1460): 3712 // At most one variant member of a union may have a 3713 // brace-or-equal-initializer. 3714 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3715 Owner->isRecord()) 3716 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3717 cast<CXXRecordDecl>(Record)); 3718 } 3719 3720 if (!Record->isUnion() && !Owner->isRecord()) { 3721 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3722 << (int)getLangOpts().CPlusPlus; 3723 Invalid = true; 3724 } 3725 3726 // Mock up a declarator. 3727 Declarator Dc(DS, Declarator::MemberContext); 3728 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3729 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3730 3731 // Create a declaration for this anonymous struct/union. 3732 NamedDecl *Anon = 0; 3733 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3734 Anon = FieldDecl::Create(Context, OwningClass, 3735 DS.getLocStart(), 3736 Record->getLocation(), 3737 /*IdentifierInfo=*/0, 3738 Context.getTypeDeclType(Record), 3739 TInfo, 3740 /*BitWidth=*/0, /*Mutable=*/false, 3741 /*InitStyle=*/ICIS_NoInit); 3742 Anon->setAccess(AS); 3743 if (getLangOpts().CPlusPlus) 3744 FieldCollector->Add(cast<FieldDecl>(Anon)); 3745 } else { 3746 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3747 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3748 if (SCSpec == DeclSpec::SCS_mutable) { 3749 // mutable can only appear on non-static class members, so it's always 3750 // an error here 3751 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3752 Invalid = true; 3753 SC = SC_None; 3754 } 3755 3756 Anon = VarDecl::Create(Context, Owner, 3757 DS.getLocStart(), 3758 Record->getLocation(), /*IdentifierInfo=*/0, 3759 Context.getTypeDeclType(Record), 3760 TInfo, SC); 3761 3762 // Default-initialize the implicit variable. This initialization will be 3763 // trivial in almost all cases, except if a union member has an in-class 3764 // initializer: 3765 // union { int n = 0; }; 3766 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3767 } 3768 Anon->setImplicit(); 3769 3770 // Mark this as an anonymous struct/union type. 3771 Record->setAnonymousStructOrUnion(true); 3772 3773 // Add the anonymous struct/union object to the current 3774 // context. We'll be referencing this object when we refer to one of 3775 // its members. 3776 Owner->addDecl(Anon); 3777 3778 // Inject the members of the anonymous struct/union into the owning 3779 // context and into the identifier resolver chain for name lookup 3780 // purposes. 3781 SmallVector<NamedDecl*, 2> Chain; 3782 Chain.push_back(Anon); 3783 3784 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3785 Chain, false)) 3786 Invalid = true; 3787 3788 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 3789 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 3790 Decl *ManglingContextDecl; 3791 if (MangleNumberingContext *MCtx = 3792 getCurrentMangleNumberContext(NewVD->getDeclContext(), 3793 ManglingContextDecl)) { 3794 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 3795 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 3796 } 3797 } 3798 } 3799 3800 if (Invalid) 3801 Anon->setInvalidDecl(); 3802 3803 return Anon; 3804 } 3805 3806 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3807 /// Microsoft C anonymous structure. 3808 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3809 /// Example: 3810 /// 3811 /// struct A { int a; }; 3812 /// struct B { struct A; int b; }; 3813 /// 3814 /// void foo() { 3815 /// B var; 3816 /// var.a = 3; 3817 /// } 3818 /// 3819 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3820 RecordDecl *Record) { 3821 3822 // If there is no Record, get the record via the typedef. 3823 if (!Record) 3824 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3825 3826 // Mock up a declarator. 3827 Declarator Dc(DS, Declarator::TypeNameContext); 3828 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3829 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3830 3831 // Create a declaration for this anonymous struct. 3832 NamedDecl* Anon = FieldDecl::Create(Context, 3833 cast<RecordDecl>(CurContext), 3834 DS.getLocStart(), 3835 DS.getLocStart(), 3836 /*IdentifierInfo=*/0, 3837 Context.getTypeDeclType(Record), 3838 TInfo, 3839 /*BitWidth=*/0, /*Mutable=*/false, 3840 /*InitStyle=*/ICIS_NoInit); 3841 Anon->setImplicit(); 3842 3843 // Add the anonymous struct object to the current context. 3844 CurContext->addDecl(Anon); 3845 3846 // Inject the members of the anonymous struct into the current 3847 // context and into the identifier resolver chain for name lookup 3848 // purposes. 3849 SmallVector<NamedDecl*, 2> Chain; 3850 Chain.push_back(Anon); 3851 3852 RecordDecl *RecordDef = Record->getDefinition(); 3853 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3854 RecordDef, AS_none, 3855 Chain, true)) 3856 Anon->setInvalidDecl(); 3857 3858 return Anon; 3859 } 3860 3861 /// GetNameForDeclarator - Determine the full declaration name for the 3862 /// given Declarator. 3863 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3864 return GetNameFromUnqualifiedId(D.getName()); 3865 } 3866 3867 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3868 DeclarationNameInfo 3869 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3870 DeclarationNameInfo NameInfo; 3871 NameInfo.setLoc(Name.StartLocation); 3872 3873 switch (Name.getKind()) { 3874 3875 case UnqualifiedId::IK_ImplicitSelfParam: 3876 case UnqualifiedId::IK_Identifier: 3877 NameInfo.setName(Name.Identifier); 3878 NameInfo.setLoc(Name.StartLocation); 3879 return NameInfo; 3880 3881 case UnqualifiedId::IK_OperatorFunctionId: 3882 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3883 Name.OperatorFunctionId.Operator)); 3884 NameInfo.setLoc(Name.StartLocation); 3885 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3886 = Name.OperatorFunctionId.SymbolLocations[0]; 3887 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3888 = Name.EndLocation.getRawEncoding(); 3889 return NameInfo; 3890 3891 case UnqualifiedId::IK_LiteralOperatorId: 3892 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3893 Name.Identifier)); 3894 NameInfo.setLoc(Name.StartLocation); 3895 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3896 return NameInfo; 3897 3898 case UnqualifiedId::IK_ConversionFunctionId: { 3899 TypeSourceInfo *TInfo; 3900 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3901 if (Ty.isNull()) 3902 return DeclarationNameInfo(); 3903 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3904 Context.getCanonicalType(Ty))); 3905 NameInfo.setLoc(Name.StartLocation); 3906 NameInfo.setNamedTypeInfo(TInfo); 3907 return NameInfo; 3908 } 3909 3910 case UnqualifiedId::IK_ConstructorName: { 3911 TypeSourceInfo *TInfo; 3912 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3913 if (Ty.isNull()) 3914 return DeclarationNameInfo(); 3915 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3916 Context.getCanonicalType(Ty))); 3917 NameInfo.setLoc(Name.StartLocation); 3918 NameInfo.setNamedTypeInfo(TInfo); 3919 return NameInfo; 3920 } 3921 3922 case UnqualifiedId::IK_ConstructorTemplateId: { 3923 // In well-formed code, we can only have a constructor 3924 // template-id that refers to the current context, so go there 3925 // to find the actual type being constructed. 3926 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3927 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3928 return DeclarationNameInfo(); 3929 3930 // Determine the type of the class being constructed. 3931 QualType CurClassType = Context.getTypeDeclType(CurClass); 3932 3933 // FIXME: Check two things: that the template-id names the same type as 3934 // CurClassType, and that the template-id does not occur when the name 3935 // was qualified. 3936 3937 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3938 Context.getCanonicalType(CurClassType))); 3939 NameInfo.setLoc(Name.StartLocation); 3940 // FIXME: should we retrieve TypeSourceInfo? 3941 NameInfo.setNamedTypeInfo(0); 3942 return NameInfo; 3943 } 3944 3945 case UnqualifiedId::IK_DestructorName: { 3946 TypeSourceInfo *TInfo; 3947 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3948 if (Ty.isNull()) 3949 return DeclarationNameInfo(); 3950 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3951 Context.getCanonicalType(Ty))); 3952 NameInfo.setLoc(Name.StartLocation); 3953 NameInfo.setNamedTypeInfo(TInfo); 3954 return NameInfo; 3955 } 3956 3957 case UnqualifiedId::IK_TemplateId: { 3958 TemplateName TName = Name.TemplateId->Template.get(); 3959 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3960 return Context.getNameForTemplate(TName, TNameLoc); 3961 } 3962 3963 } // switch (Name.getKind()) 3964 3965 llvm_unreachable("Unknown name kind"); 3966 } 3967 3968 static QualType getCoreType(QualType Ty) { 3969 do { 3970 if (Ty->isPointerType() || Ty->isReferenceType()) 3971 Ty = Ty->getPointeeType(); 3972 else if (Ty->isArrayType()) 3973 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3974 else 3975 return Ty.withoutLocalFastQualifiers(); 3976 } while (true); 3977 } 3978 3979 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3980 /// and Definition have "nearly" matching parameters. This heuristic is 3981 /// used to improve diagnostics in the case where an out-of-line function 3982 /// definition doesn't match any declaration within the class or namespace. 3983 /// Also sets Params to the list of indices to the parameters that differ 3984 /// between the declaration and the definition. If hasSimilarParameters 3985 /// returns true and Params is empty, then all of the parameters match. 3986 static bool hasSimilarParameters(ASTContext &Context, 3987 FunctionDecl *Declaration, 3988 FunctionDecl *Definition, 3989 SmallVectorImpl<unsigned> &Params) { 3990 Params.clear(); 3991 if (Declaration->param_size() != Definition->param_size()) 3992 return false; 3993 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3994 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3995 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3996 3997 // The parameter types are identical 3998 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3999 continue; 4000 4001 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4002 QualType DefParamBaseTy = getCoreType(DefParamTy); 4003 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4004 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4005 4006 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4007 (DeclTyName && DeclTyName == DefTyName)) 4008 Params.push_back(Idx); 4009 else // The two parameters aren't even close 4010 return false; 4011 } 4012 4013 return true; 4014 } 4015 4016 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4017 /// declarator needs to be rebuilt in the current instantiation. 4018 /// Any bits of declarator which appear before the name are valid for 4019 /// consideration here. That's specifically the type in the decl spec 4020 /// and the base type in any member-pointer chunks. 4021 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4022 DeclarationName Name) { 4023 // The types we specifically need to rebuild are: 4024 // - typenames, typeofs, and decltypes 4025 // - types which will become injected class names 4026 // Of course, we also need to rebuild any type referencing such a 4027 // type. It's safest to just say "dependent", but we call out a 4028 // few cases here. 4029 4030 DeclSpec &DS = D.getMutableDeclSpec(); 4031 switch (DS.getTypeSpecType()) { 4032 case DeclSpec::TST_typename: 4033 case DeclSpec::TST_typeofType: 4034 case DeclSpec::TST_underlyingType: 4035 case DeclSpec::TST_atomic: { 4036 // Grab the type from the parser. 4037 TypeSourceInfo *TSI = 0; 4038 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4039 if (T.isNull() || !T->isDependentType()) break; 4040 4041 // Make sure there's a type source info. This isn't really much 4042 // of a waste; most dependent types should have type source info 4043 // attached already. 4044 if (!TSI) 4045 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4046 4047 // Rebuild the type in the current instantiation. 4048 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4049 if (!TSI) return true; 4050 4051 // Store the new type back in the decl spec. 4052 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4053 DS.UpdateTypeRep(LocType); 4054 break; 4055 } 4056 4057 case DeclSpec::TST_decltype: 4058 case DeclSpec::TST_typeofExpr: { 4059 Expr *E = DS.getRepAsExpr(); 4060 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4061 if (Result.isInvalid()) return true; 4062 DS.UpdateExprRep(Result.get()); 4063 break; 4064 } 4065 4066 default: 4067 // Nothing to do for these decl specs. 4068 break; 4069 } 4070 4071 // It doesn't matter what order we do this in. 4072 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4073 DeclaratorChunk &Chunk = D.getTypeObject(I); 4074 4075 // The only type information in the declarator which can come 4076 // before the declaration name is the base type of a member 4077 // pointer. 4078 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4079 continue; 4080 4081 // Rebuild the scope specifier in-place. 4082 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4083 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4084 return true; 4085 } 4086 4087 return false; 4088 } 4089 4090 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4091 D.setFunctionDefinitionKind(FDK_Declaration); 4092 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4093 4094 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4095 Dcl && Dcl->getDeclContext()->isFileContext()) 4096 Dcl->setTopLevelDeclInObjCContainer(); 4097 4098 return Dcl; 4099 } 4100 4101 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4102 /// If T is the name of a class, then each of the following shall have a 4103 /// name different from T: 4104 /// - every static data member of class T; 4105 /// - every member function of class T 4106 /// - every member of class T that is itself a type; 4107 /// \returns true if the declaration name violates these rules. 4108 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4109 DeclarationNameInfo NameInfo) { 4110 DeclarationName Name = NameInfo.getName(); 4111 4112 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4113 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4114 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4115 return true; 4116 } 4117 4118 return false; 4119 } 4120 4121 /// \brief Diagnose a declaration whose declarator-id has the given 4122 /// nested-name-specifier. 4123 /// 4124 /// \param SS The nested-name-specifier of the declarator-id. 4125 /// 4126 /// \param DC The declaration context to which the nested-name-specifier 4127 /// resolves. 4128 /// 4129 /// \param Name The name of the entity being declared. 4130 /// 4131 /// \param Loc The location of the name of the entity being declared. 4132 /// 4133 /// \returns true if we cannot safely recover from this error, false otherwise. 4134 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4135 DeclarationName Name, 4136 SourceLocation Loc) { 4137 DeclContext *Cur = CurContext; 4138 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4139 Cur = Cur->getParent(); 4140 4141 // If the user provided a superfluous scope specifier that refers back to the 4142 // class in which the entity is already declared, diagnose and ignore it. 4143 // 4144 // class X { 4145 // void X::f(); 4146 // }; 4147 // 4148 // Note, it was once ill-formed to give redundant qualification in all 4149 // contexts, but that rule was removed by DR482. 4150 if (Cur->Equals(DC)) { 4151 if (Cur->isRecord()) { 4152 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4153 : diag::err_member_extra_qualification) 4154 << Name << FixItHint::CreateRemoval(SS.getRange()); 4155 SS.clear(); 4156 } else { 4157 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4158 } 4159 return false; 4160 } 4161 4162 // Check whether the qualifying scope encloses the scope of the original 4163 // declaration. 4164 if (!Cur->Encloses(DC)) { 4165 if (Cur->isRecord()) 4166 Diag(Loc, diag::err_member_qualification) 4167 << Name << SS.getRange(); 4168 else if (isa<TranslationUnitDecl>(DC)) 4169 Diag(Loc, diag::err_invalid_declarator_global_scope) 4170 << Name << SS.getRange(); 4171 else if (isa<FunctionDecl>(Cur)) 4172 Diag(Loc, diag::err_invalid_declarator_in_function) 4173 << Name << SS.getRange(); 4174 else if (isa<BlockDecl>(Cur)) 4175 Diag(Loc, diag::err_invalid_declarator_in_block) 4176 << Name << SS.getRange(); 4177 else 4178 Diag(Loc, diag::err_invalid_declarator_scope) 4179 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4180 4181 return true; 4182 } 4183 4184 if (Cur->isRecord()) { 4185 // Cannot qualify members within a class. 4186 Diag(Loc, diag::err_member_qualification) 4187 << Name << SS.getRange(); 4188 SS.clear(); 4189 4190 // C++ constructors and destructors with incorrect scopes can break 4191 // our AST invariants by having the wrong underlying types. If 4192 // that's the case, then drop this declaration entirely. 4193 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4194 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4195 !Context.hasSameType(Name.getCXXNameType(), 4196 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4197 return true; 4198 4199 return false; 4200 } 4201 4202 // C++11 [dcl.meaning]p1: 4203 // [...] "The nested-name-specifier of the qualified declarator-id shall 4204 // not begin with a decltype-specifer" 4205 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4206 while (SpecLoc.getPrefix()) 4207 SpecLoc = SpecLoc.getPrefix(); 4208 if (dyn_cast_or_null<DecltypeType>( 4209 SpecLoc.getNestedNameSpecifier()->getAsType())) 4210 Diag(Loc, diag::err_decltype_in_declarator) 4211 << SpecLoc.getTypeLoc().getSourceRange(); 4212 4213 return false; 4214 } 4215 4216 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4217 MultiTemplateParamsArg TemplateParamLists) { 4218 // TODO: consider using NameInfo for diagnostic. 4219 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4220 DeclarationName Name = NameInfo.getName(); 4221 4222 // All of these full declarators require an identifier. If it doesn't have 4223 // one, the ParsedFreeStandingDeclSpec action should be used. 4224 if (!Name) { 4225 if (!D.isInvalidType()) // Reject this if we think it is valid. 4226 Diag(D.getDeclSpec().getLocStart(), 4227 diag::err_declarator_need_ident) 4228 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4229 return 0; 4230 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4231 return 0; 4232 4233 // The scope passed in may not be a decl scope. Zip up the scope tree until 4234 // we find one that is. 4235 while ((S->getFlags() & Scope::DeclScope) == 0 || 4236 (S->getFlags() & Scope::TemplateParamScope) != 0) 4237 S = S->getParent(); 4238 4239 DeclContext *DC = CurContext; 4240 if (D.getCXXScopeSpec().isInvalid()) 4241 D.setInvalidType(); 4242 else if (D.getCXXScopeSpec().isSet()) { 4243 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4244 UPPC_DeclarationQualifier)) 4245 return 0; 4246 4247 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4248 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4249 if (!DC || isa<EnumDecl>(DC)) { 4250 // If we could not compute the declaration context, it's because the 4251 // declaration context is dependent but does not refer to a class, 4252 // class template, or class template partial specialization. Complain 4253 // and return early, to avoid the coming semantic disaster. 4254 Diag(D.getIdentifierLoc(), 4255 diag::err_template_qualified_declarator_no_match) 4256 << D.getCXXScopeSpec().getScopeRep() 4257 << D.getCXXScopeSpec().getRange(); 4258 return 0; 4259 } 4260 bool IsDependentContext = DC->isDependentContext(); 4261 4262 if (!IsDependentContext && 4263 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4264 return 0; 4265 4266 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4267 Diag(D.getIdentifierLoc(), 4268 diag::err_member_def_undefined_record) 4269 << Name << DC << D.getCXXScopeSpec().getRange(); 4270 D.setInvalidType(); 4271 } else if (!D.getDeclSpec().isFriendSpecified()) { 4272 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4273 Name, D.getIdentifierLoc())) { 4274 if (DC->isRecord()) 4275 return 0; 4276 4277 D.setInvalidType(); 4278 } 4279 } 4280 4281 // Check whether we need to rebuild the type of the given 4282 // declaration in the current instantiation. 4283 if (EnteringContext && IsDependentContext && 4284 TemplateParamLists.size() != 0) { 4285 ContextRAII SavedContext(*this, DC); 4286 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4287 D.setInvalidType(); 4288 } 4289 } 4290 4291 if (DiagnoseClassNameShadow(DC, NameInfo)) 4292 // If this is a typedef, we'll end up spewing multiple diagnostics. 4293 // Just return early; it's safer. 4294 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4295 return 0; 4296 4297 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4298 QualType R = TInfo->getType(); 4299 4300 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4301 UPPC_DeclarationType)) 4302 D.setInvalidType(); 4303 4304 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4305 ForRedeclaration); 4306 4307 // See if this is a redefinition of a variable in the same scope. 4308 if (!D.getCXXScopeSpec().isSet()) { 4309 bool IsLinkageLookup = false; 4310 bool CreateBuiltins = false; 4311 4312 // If the declaration we're planning to build will be a function 4313 // or object with linkage, then look for another declaration with 4314 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4315 // 4316 // If the declaration we're planning to build will be declared with 4317 // external linkage in the translation unit, create any builtin with 4318 // the same name. 4319 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4320 /* Do nothing*/; 4321 else if (CurContext->isFunctionOrMethod() && 4322 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4323 R->isFunctionType())) { 4324 IsLinkageLookup = true; 4325 CreateBuiltins = 4326 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4327 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4328 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4329 CreateBuiltins = true; 4330 4331 if (IsLinkageLookup) 4332 Previous.clear(LookupRedeclarationWithLinkage); 4333 4334 LookupName(Previous, S, CreateBuiltins); 4335 } else { // Something like "int foo::x;" 4336 LookupQualifiedName(Previous, DC); 4337 4338 // C++ [dcl.meaning]p1: 4339 // When the declarator-id is qualified, the declaration shall refer to a 4340 // previously declared member of the class or namespace to which the 4341 // qualifier refers (or, in the case of a namespace, of an element of the 4342 // inline namespace set of that namespace (7.3.1)) or to a specialization 4343 // thereof; [...] 4344 // 4345 // Note that we already checked the context above, and that we do not have 4346 // enough information to make sure that Previous contains the declaration 4347 // we want to match. For example, given: 4348 // 4349 // class X { 4350 // void f(); 4351 // void f(float); 4352 // }; 4353 // 4354 // void X::f(int) { } // ill-formed 4355 // 4356 // In this case, Previous will point to the overload set 4357 // containing the two f's declared in X, but neither of them 4358 // matches. 4359 4360 // C++ [dcl.meaning]p1: 4361 // [...] the member shall not merely have been introduced by a 4362 // using-declaration in the scope of the class or namespace nominated by 4363 // the nested-name-specifier of the declarator-id. 4364 RemoveUsingDecls(Previous); 4365 } 4366 4367 if (Previous.isSingleResult() && 4368 Previous.getFoundDecl()->isTemplateParameter()) { 4369 // Maybe we will complain about the shadowed template parameter. 4370 if (!D.isInvalidType()) 4371 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4372 Previous.getFoundDecl()); 4373 4374 // Just pretend that we didn't see the previous declaration. 4375 Previous.clear(); 4376 } 4377 4378 // In C++, the previous declaration we find might be a tag type 4379 // (class or enum). In this case, the new declaration will hide the 4380 // tag type. Note that this does does not apply if we're declaring a 4381 // typedef (C++ [dcl.typedef]p4). 4382 if (Previous.isSingleTagDecl() && 4383 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4384 Previous.clear(); 4385 4386 // Check that there are no default arguments other than in the parameters 4387 // of a function declaration (C++ only). 4388 if (getLangOpts().CPlusPlus) 4389 CheckExtraCXXDefaultArguments(D); 4390 4391 NamedDecl *New; 4392 4393 bool AddToScope = true; 4394 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4395 if (TemplateParamLists.size()) { 4396 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4397 return 0; 4398 } 4399 4400 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4401 } else if (R->isFunctionType()) { 4402 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4403 TemplateParamLists, 4404 AddToScope); 4405 } else { 4406 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4407 AddToScope); 4408 } 4409 4410 if (New == 0) 4411 return 0; 4412 4413 // If this has an identifier and is not an invalid redeclaration or 4414 // function template specialization, add it to the scope stack. 4415 if (New->getDeclName() && AddToScope && 4416 !(D.isRedeclaration() && New->isInvalidDecl())) { 4417 // Only make a locally-scoped extern declaration visible if it is the first 4418 // declaration of this entity. Qualified lookup for such an entity should 4419 // only find this declaration if there is no visible declaration of it. 4420 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4421 PushOnScopeChains(New, S, AddToContext); 4422 if (!AddToContext) 4423 CurContext->addHiddenDecl(New); 4424 } 4425 4426 return New; 4427 } 4428 4429 /// Helper method to turn variable array types into constant array 4430 /// types in certain situations which would otherwise be errors (for 4431 /// GCC compatibility). 4432 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4433 ASTContext &Context, 4434 bool &SizeIsNegative, 4435 llvm::APSInt &Oversized) { 4436 // This method tries to turn a variable array into a constant 4437 // array even when the size isn't an ICE. This is necessary 4438 // for compatibility with code that depends on gcc's buggy 4439 // constant expression folding, like struct {char x[(int)(char*)2];} 4440 SizeIsNegative = false; 4441 Oversized = 0; 4442 4443 if (T->isDependentType()) 4444 return QualType(); 4445 4446 QualifierCollector Qs; 4447 const Type *Ty = Qs.strip(T); 4448 4449 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4450 QualType Pointee = PTy->getPointeeType(); 4451 QualType FixedType = 4452 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4453 Oversized); 4454 if (FixedType.isNull()) return FixedType; 4455 FixedType = Context.getPointerType(FixedType); 4456 return Qs.apply(Context, FixedType); 4457 } 4458 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4459 QualType Inner = PTy->getInnerType(); 4460 QualType FixedType = 4461 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4462 Oversized); 4463 if (FixedType.isNull()) return FixedType; 4464 FixedType = Context.getParenType(FixedType); 4465 return Qs.apply(Context, FixedType); 4466 } 4467 4468 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4469 if (!VLATy) 4470 return QualType(); 4471 // FIXME: We should probably handle this case 4472 if (VLATy->getElementType()->isVariablyModifiedType()) 4473 return QualType(); 4474 4475 llvm::APSInt Res; 4476 if (!VLATy->getSizeExpr() || 4477 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4478 return QualType(); 4479 4480 // Check whether the array size is negative. 4481 if (Res.isSigned() && Res.isNegative()) { 4482 SizeIsNegative = true; 4483 return QualType(); 4484 } 4485 4486 // Check whether the array is too large to be addressed. 4487 unsigned ActiveSizeBits 4488 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4489 Res); 4490 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4491 Oversized = Res; 4492 return QualType(); 4493 } 4494 4495 return Context.getConstantArrayType(VLATy->getElementType(), 4496 Res, ArrayType::Normal, 0); 4497 } 4498 4499 static void 4500 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4501 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4502 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4503 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4504 DstPTL.getPointeeLoc()); 4505 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4506 return; 4507 } 4508 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4509 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4510 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4511 DstPTL.getInnerLoc()); 4512 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4513 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4514 return; 4515 } 4516 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4517 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4518 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4519 TypeLoc DstElemTL = DstATL.getElementLoc(); 4520 DstElemTL.initializeFullCopy(SrcElemTL); 4521 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4522 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4523 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4524 } 4525 4526 /// Helper method to turn variable array types into constant array 4527 /// types in certain situations which would otherwise be errors (for 4528 /// GCC compatibility). 4529 static TypeSourceInfo* 4530 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4531 ASTContext &Context, 4532 bool &SizeIsNegative, 4533 llvm::APSInt &Oversized) { 4534 QualType FixedTy 4535 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4536 SizeIsNegative, Oversized); 4537 if (FixedTy.isNull()) 4538 return 0; 4539 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4540 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4541 FixedTInfo->getTypeLoc()); 4542 return FixedTInfo; 4543 } 4544 4545 /// \brief Register the given locally-scoped extern "C" declaration so 4546 /// that it can be found later for redeclarations. We include any extern "C" 4547 /// declaration that is not visible in the translation unit here, not just 4548 /// function-scope declarations. 4549 void 4550 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4551 if (!getLangOpts().CPlusPlus && 4552 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4553 // Don't need to track declarations in the TU in C. 4554 return; 4555 4556 // Note that we have a locally-scoped external with this name. 4557 // FIXME: There can be multiple such declarations if they are functions marked 4558 // __attribute__((overloadable)) declared in function scope in C. 4559 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4560 } 4561 4562 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4563 if (ExternalSource) { 4564 // Load locally-scoped external decls from the external source. 4565 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4566 SmallVector<NamedDecl *, 4> Decls; 4567 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4568 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4569 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4570 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4571 if (Pos == LocallyScopedExternCDecls.end()) 4572 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4573 } 4574 } 4575 4576 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4577 return D ? D->getMostRecentDecl() : 0; 4578 } 4579 4580 /// \brief Diagnose function specifiers on a declaration of an identifier that 4581 /// does not identify a function. 4582 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4583 // FIXME: We should probably indicate the identifier in question to avoid 4584 // confusion for constructs like "inline int a(), b;" 4585 if (DS.isInlineSpecified()) 4586 Diag(DS.getInlineSpecLoc(), 4587 diag::err_inline_non_function); 4588 4589 if (DS.isVirtualSpecified()) 4590 Diag(DS.getVirtualSpecLoc(), 4591 diag::err_virtual_non_function); 4592 4593 if (DS.isExplicitSpecified()) 4594 Diag(DS.getExplicitSpecLoc(), 4595 diag::err_explicit_non_function); 4596 4597 if (DS.isNoreturnSpecified()) 4598 Diag(DS.getNoreturnSpecLoc(), 4599 diag::err_noreturn_non_function); 4600 } 4601 4602 NamedDecl* 4603 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4604 TypeSourceInfo *TInfo, LookupResult &Previous) { 4605 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4606 if (D.getCXXScopeSpec().isSet()) { 4607 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4608 << D.getCXXScopeSpec().getRange(); 4609 D.setInvalidType(); 4610 // Pretend we didn't see the scope specifier. 4611 DC = CurContext; 4612 Previous.clear(); 4613 } 4614 4615 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4616 4617 if (D.getDeclSpec().isConstexprSpecified()) 4618 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4619 << 1; 4620 4621 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4622 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4623 << D.getName().getSourceRange(); 4624 return 0; 4625 } 4626 4627 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4628 if (!NewTD) return 0; 4629 4630 // Handle attributes prior to checking for duplicates in MergeVarDecl 4631 ProcessDeclAttributes(S, NewTD, D); 4632 4633 CheckTypedefForVariablyModifiedType(S, NewTD); 4634 4635 bool Redeclaration = D.isRedeclaration(); 4636 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4637 D.setRedeclaration(Redeclaration); 4638 return ND; 4639 } 4640 4641 void 4642 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4643 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4644 // then it shall have block scope. 4645 // Note that variably modified types must be fixed before merging the decl so 4646 // that redeclarations will match. 4647 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4648 QualType T = TInfo->getType(); 4649 if (T->isVariablyModifiedType()) { 4650 getCurFunction()->setHasBranchProtectedScope(); 4651 4652 if (S->getFnParent() == 0) { 4653 bool SizeIsNegative; 4654 llvm::APSInt Oversized; 4655 TypeSourceInfo *FixedTInfo = 4656 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4657 SizeIsNegative, 4658 Oversized); 4659 if (FixedTInfo) { 4660 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4661 NewTD->setTypeSourceInfo(FixedTInfo); 4662 } else { 4663 if (SizeIsNegative) 4664 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4665 else if (T->isVariableArrayType()) 4666 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4667 else if (Oversized.getBoolValue()) 4668 Diag(NewTD->getLocation(), diag::err_array_too_large) 4669 << Oversized.toString(10); 4670 else 4671 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4672 NewTD->setInvalidDecl(); 4673 } 4674 } 4675 } 4676 } 4677 4678 4679 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4680 /// declares a typedef-name, either using the 'typedef' type specifier or via 4681 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4682 NamedDecl* 4683 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4684 LookupResult &Previous, bool &Redeclaration) { 4685 // Merge the decl with the existing one if appropriate. If the decl is 4686 // in an outer scope, it isn't the same thing. 4687 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4688 /*AllowInlineNamespace*/false); 4689 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4690 if (!Previous.empty()) { 4691 Redeclaration = true; 4692 MergeTypedefNameDecl(NewTD, Previous); 4693 } 4694 4695 // If this is the C FILE type, notify the AST context. 4696 if (IdentifierInfo *II = NewTD->getIdentifier()) 4697 if (!NewTD->isInvalidDecl() && 4698 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4699 if (II->isStr("FILE")) 4700 Context.setFILEDecl(NewTD); 4701 else if (II->isStr("jmp_buf")) 4702 Context.setjmp_bufDecl(NewTD); 4703 else if (II->isStr("sigjmp_buf")) 4704 Context.setsigjmp_bufDecl(NewTD); 4705 else if (II->isStr("ucontext_t")) 4706 Context.setucontext_tDecl(NewTD); 4707 } 4708 4709 return NewTD; 4710 } 4711 4712 /// \brief Determines whether the given declaration is an out-of-scope 4713 /// previous declaration. 4714 /// 4715 /// This routine should be invoked when name lookup has found a 4716 /// previous declaration (PrevDecl) that is not in the scope where a 4717 /// new declaration by the same name is being introduced. If the new 4718 /// declaration occurs in a local scope, previous declarations with 4719 /// linkage may still be considered previous declarations (C99 4720 /// 6.2.2p4-5, C++ [basic.link]p6). 4721 /// 4722 /// \param PrevDecl the previous declaration found by name 4723 /// lookup 4724 /// 4725 /// \param DC the context in which the new declaration is being 4726 /// declared. 4727 /// 4728 /// \returns true if PrevDecl is an out-of-scope previous declaration 4729 /// for a new delcaration with the same name. 4730 static bool 4731 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4732 ASTContext &Context) { 4733 if (!PrevDecl) 4734 return false; 4735 4736 if (!PrevDecl->hasLinkage()) 4737 return false; 4738 4739 if (Context.getLangOpts().CPlusPlus) { 4740 // C++ [basic.link]p6: 4741 // If there is a visible declaration of an entity with linkage 4742 // having the same name and type, ignoring entities declared 4743 // outside the innermost enclosing namespace scope, the block 4744 // scope declaration declares that same entity and receives the 4745 // linkage of the previous declaration. 4746 DeclContext *OuterContext = DC->getRedeclContext(); 4747 if (!OuterContext->isFunctionOrMethod()) 4748 // This rule only applies to block-scope declarations. 4749 return false; 4750 4751 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4752 if (PrevOuterContext->isRecord()) 4753 // We found a member function: ignore it. 4754 return false; 4755 4756 // Find the innermost enclosing namespace for the new and 4757 // previous declarations. 4758 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4759 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4760 4761 // The previous declaration is in a different namespace, so it 4762 // isn't the same function. 4763 if (!OuterContext->Equals(PrevOuterContext)) 4764 return false; 4765 } 4766 4767 return true; 4768 } 4769 4770 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4771 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4772 if (!SS.isSet()) return; 4773 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4774 } 4775 4776 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4777 QualType type = decl->getType(); 4778 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4779 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4780 // Various kinds of declaration aren't allowed to be __autoreleasing. 4781 unsigned kind = -1U; 4782 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4783 if (var->hasAttr<BlocksAttr>()) 4784 kind = 0; // __block 4785 else if (!var->hasLocalStorage()) 4786 kind = 1; // global 4787 } else if (isa<ObjCIvarDecl>(decl)) { 4788 kind = 3; // ivar 4789 } else if (isa<FieldDecl>(decl)) { 4790 kind = 2; // field 4791 } 4792 4793 if (kind != -1U) { 4794 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4795 << kind; 4796 } 4797 } else if (lifetime == Qualifiers::OCL_None) { 4798 // Try to infer lifetime. 4799 if (!type->isObjCLifetimeType()) 4800 return false; 4801 4802 lifetime = type->getObjCARCImplicitLifetime(); 4803 type = Context.getLifetimeQualifiedType(type, lifetime); 4804 decl->setType(type); 4805 } 4806 4807 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4808 // Thread-local variables cannot have lifetime. 4809 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4810 var->getTLSKind()) { 4811 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4812 << var->getType(); 4813 return true; 4814 } 4815 } 4816 4817 return false; 4818 } 4819 4820 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4821 // Ensure that an auto decl is deduced otherwise the checks below might cache 4822 // the wrong linkage. 4823 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4824 4825 // 'weak' only applies to declarations with external linkage. 4826 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4827 if (!ND.isExternallyVisible()) { 4828 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4829 ND.dropAttr<WeakAttr>(); 4830 } 4831 } 4832 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4833 if (ND.isExternallyVisible()) { 4834 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4835 ND.dropAttr<WeakRefAttr>(); 4836 } 4837 } 4838 4839 // 'selectany' only applies to externally visible varable declarations. 4840 // It does not apply to functions. 4841 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4842 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4843 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4844 ND.dropAttr<SelectAnyAttr>(); 4845 } 4846 } 4847 4848 // dll attributes require external linkage. 4849 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) { 4850 if (!ND.isExternallyVisible()) { 4851 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4852 << &ND << Attr; 4853 ND.setInvalidDecl(); 4854 } 4855 } 4856 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) { 4857 if (!ND.isExternallyVisible()) { 4858 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4859 << &ND << Attr; 4860 ND.setInvalidDecl(); 4861 } 4862 } 4863 } 4864 4865 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 4866 NamedDecl *NewDecl, 4867 bool IsSpecialization) { 4868 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 4869 OldDecl = OldTD->getTemplatedDecl(); 4870 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 4871 NewDecl = NewTD->getTemplatedDecl(); 4872 4873 if (!OldDecl || !NewDecl) 4874 return; 4875 4876 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 4877 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 4878 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 4879 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 4880 4881 // dllimport and dllexport are inheritable attributes so we have to exclude 4882 // inherited attribute instances. 4883 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 4884 (NewExportAttr && !NewExportAttr->isInherited()); 4885 4886 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 4887 // the only exception being explicit specializations. 4888 // Implicitly generated declarations are also excluded for now because there 4889 // is no other way to switch these to use dllimport or dllexport. 4890 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 4891 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 4892 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration) 4893 << NewDecl 4894 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 4895 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4896 NewDecl->setInvalidDecl(); 4897 return; 4898 } 4899 4900 // A redeclaration is not allowed to drop a dllimport attribute, the only 4901 // exception being inline function definitions. 4902 // FIXME: Handle inline functions. 4903 // NB: MSVC converts such a declaration to dllexport. 4904 if (OldImportAttr && !HasNewAttr) { 4905 S.Diag(NewDecl->getLocation(), 4906 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4907 << NewDecl << OldImportAttr; 4908 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4909 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 4910 OldDecl->dropAttr<DLLImportAttr>(); 4911 NewDecl->dropAttr<DLLImportAttr>(); 4912 } 4913 } 4914 4915 /// Given that we are within the definition of the given function, 4916 /// will that definition behave like C99's 'inline', where the 4917 /// definition is discarded except for optimization purposes? 4918 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4919 // Try to avoid calling GetGVALinkageForFunction. 4920 4921 // All cases of this require the 'inline' keyword. 4922 if (!FD->isInlined()) return false; 4923 4924 // This is only possible in C++ with the gnu_inline attribute. 4925 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4926 return false; 4927 4928 // Okay, go ahead and call the relatively-more-expensive function. 4929 4930 #ifndef NDEBUG 4931 // AST quite reasonably asserts that it's working on a function 4932 // definition. We don't really have a way to tell it that we're 4933 // currently defining the function, so just lie to it in +Asserts 4934 // builds. This is an awful hack. 4935 FD->setLazyBody(1); 4936 #endif 4937 4938 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4939 4940 #ifndef NDEBUG 4941 FD->setLazyBody(0); 4942 #endif 4943 4944 return isC99Inline; 4945 } 4946 4947 /// Determine whether a variable is extern "C" prior to attaching 4948 /// an initializer. We can't just call isExternC() here, because that 4949 /// will also compute and cache whether the declaration is externally 4950 /// visible, which might change when we attach the initializer. 4951 /// 4952 /// This can only be used if the declaration is known to not be a 4953 /// redeclaration of an internal linkage declaration. 4954 /// 4955 /// For instance: 4956 /// 4957 /// auto x = []{}; 4958 /// 4959 /// Attaching the initializer here makes this declaration not externally 4960 /// visible, because its type has internal linkage. 4961 /// 4962 /// FIXME: This is a hack. 4963 template<typename T> 4964 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4965 if (S.getLangOpts().CPlusPlus) { 4966 // In C++, the overloadable attribute negates the effects of extern "C". 4967 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4968 return false; 4969 } 4970 return D->isExternC(); 4971 } 4972 4973 static bool shouldConsiderLinkage(const VarDecl *VD) { 4974 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4975 if (DC->isFunctionOrMethod()) 4976 return VD->hasExternalStorage(); 4977 if (DC->isFileContext()) 4978 return true; 4979 if (DC->isRecord()) 4980 return false; 4981 llvm_unreachable("Unexpected context"); 4982 } 4983 4984 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4985 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4986 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4987 return true; 4988 if (DC->isRecord()) 4989 return false; 4990 llvm_unreachable("Unexpected context"); 4991 } 4992 4993 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 4994 AttributeList::Kind Kind) { 4995 for (const AttributeList *L = AttrList; L; L = L->getNext()) 4996 if (L->getKind() == Kind) 4997 return true; 4998 return false; 4999 } 5000 5001 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5002 AttributeList::Kind Kind) { 5003 // Check decl attributes on the DeclSpec. 5004 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5005 return true; 5006 5007 // Walk the declarator structure, checking decl attributes that were in a type 5008 // position to the decl itself. 5009 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5010 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5011 return true; 5012 } 5013 5014 // Finally, check attributes on the decl itself. 5015 return hasParsedAttr(S, PD.getAttributes(), Kind); 5016 } 5017 5018 /// Adjust the \c DeclContext for a function or variable that might be a 5019 /// function-local external declaration. 5020 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5021 if (!DC->isFunctionOrMethod()) 5022 return false; 5023 5024 // If this is a local extern function or variable declared within a function 5025 // template, don't add it into the enclosing namespace scope until it is 5026 // instantiated; it might have a dependent type right now. 5027 if (DC->isDependentContext()) 5028 return true; 5029 5030 // C++11 [basic.link]p7: 5031 // When a block scope declaration of an entity with linkage is not found to 5032 // refer to some other declaration, then that entity is a member of the 5033 // innermost enclosing namespace. 5034 // 5035 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5036 // semantically-enclosing namespace, not a lexically-enclosing one. 5037 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5038 DC = DC->getParent(); 5039 return true; 5040 } 5041 5042 NamedDecl * 5043 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5044 TypeSourceInfo *TInfo, LookupResult &Previous, 5045 MultiTemplateParamsArg TemplateParamLists, 5046 bool &AddToScope) { 5047 QualType R = TInfo->getType(); 5048 DeclarationName Name = GetNameForDeclarator(D).getName(); 5049 5050 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5051 VarDecl::StorageClass SC = 5052 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5053 5054 // dllimport globals without explicit storage class are treated as extern. We 5055 // have to change the storage class this early to get the right DeclContext. 5056 if (SC == SC_None && !DC->isRecord() && 5057 hasParsedAttr(S, D, AttributeList::AT_DLLImport)) 5058 SC = SC_Extern; 5059 5060 DeclContext *OriginalDC = DC; 5061 bool IsLocalExternDecl = SC == SC_Extern && 5062 adjustContextForLocalExternDecl(DC); 5063 5064 if (getLangOpts().OpenCL) { 5065 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5066 QualType NR = R; 5067 while (NR->isPointerType()) { 5068 if (NR->isFunctionPointerType()) { 5069 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5070 D.setInvalidType(); 5071 break; 5072 } 5073 NR = NR->getPointeeType(); 5074 } 5075 5076 if (!getOpenCLOptions().cl_khr_fp16) { 5077 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5078 // half array type (unless the cl_khr_fp16 extension is enabled). 5079 if (Context.getBaseElementType(R)->isHalfType()) { 5080 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5081 D.setInvalidType(); 5082 } 5083 } 5084 } 5085 5086 if (SCSpec == DeclSpec::SCS_mutable) { 5087 // mutable can only appear on non-static class members, so it's always 5088 // an error here 5089 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5090 D.setInvalidType(); 5091 SC = SC_None; 5092 } 5093 5094 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5095 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5096 D.getDeclSpec().getStorageClassSpecLoc())) { 5097 // In C++11, the 'register' storage class specifier is deprecated. 5098 // Suppress the warning in system macros, it's used in macros in some 5099 // popular C system headers, such as in glibc's htonl() macro. 5100 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5101 diag::warn_deprecated_register) 5102 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5103 } 5104 5105 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5106 if (!II) { 5107 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5108 << Name; 5109 return 0; 5110 } 5111 5112 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5113 5114 if (!DC->isRecord() && S->getFnParent() == 0) { 5115 // C99 6.9p2: The storage-class specifiers auto and register shall not 5116 // appear in the declaration specifiers in an external declaration. 5117 if (SC == SC_Auto || SC == SC_Register) { 5118 // If this is a register variable with an asm label specified, then this 5119 // is a GNU extension. 5120 if (SC == SC_Register && D.getAsmLabel()) 5121 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 5122 else 5123 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5124 D.setInvalidType(); 5125 } 5126 } 5127 5128 if (getLangOpts().OpenCL) { 5129 // Set up the special work-group-local storage class for variables in the 5130 // OpenCL __local address space. 5131 if (R.getAddressSpace() == LangAS::opencl_local) { 5132 SC = SC_OpenCLWorkGroupLocal; 5133 } 5134 5135 // OpenCL v1.2 s6.9.b p4: 5136 // The sampler type cannot be used with the __local and __global address 5137 // space qualifiers. 5138 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5139 R.getAddressSpace() == LangAS::opencl_global)) { 5140 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5141 } 5142 5143 // OpenCL 1.2 spec, p6.9 r: 5144 // The event type cannot be used to declare a program scope variable. 5145 // The event type cannot be used with the __local, __constant and __global 5146 // address space qualifiers. 5147 if (R->isEventT()) { 5148 if (S->getParent() == 0) { 5149 Diag(D.getLocStart(), diag::err_event_t_global_var); 5150 D.setInvalidType(); 5151 } 5152 5153 if (R.getAddressSpace()) { 5154 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5155 D.setInvalidType(); 5156 } 5157 } 5158 } 5159 5160 bool IsExplicitSpecialization = false; 5161 bool IsVariableTemplateSpecialization = false; 5162 bool IsPartialSpecialization = false; 5163 bool IsVariableTemplate = false; 5164 VarDecl *NewVD = 0; 5165 VarTemplateDecl *NewTemplate = 0; 5166 TemplateParameterList *TemplateParams = 0; 5167 if (!getLangOpts().CPlusPlus) { 5168 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5169 D.getIdentifierLoc(), II, 5170 R, TInfo, SC); 5171 5172 if (D.isInvalidType()) 5173 NewVD->setInvalidDecl(); 5174 } else { 5175 bool Invalid = false; 5176 5177 if (DC->isRecord() && !CurContext->isRecord()) { 5178 // This is an out-of-line definition of a static data member. 5179 switch (SC) { 5180 case SC_None: 5181 break; 5182 case SC_Static: 5183 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5184 diag::err_static_out_of_line) 5185 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5186 break; 5187 case SC_Auto: 5188 case SC_Register: 5189 case SC_Extern: 5190 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5191 // to names of variables declared in a block or to function parameters. 5192 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5193 // of class members 5194 5195 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5196 diag::err_storage_class_for_static_member) 5197 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5198 break; 5199 case SC_PrivateExtern: 5200 llvm_unreachable("C storage class in c++!"); 5201 case SC_OpenCLWorkGroupLocal: 5202 llvm_unreachable("OpenCL storage class in c++!"); 5203 } 5204 } 5205 5206 if (SC == SC_Static && CurContext->isRecord()) { 5207 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5208 if (RD->isLocalClass()) 5209 Diag(D.getIdentifierLoc(), 5210 diag::err_static_data_member_not_allowed_in_local_class) 5211 << Name << RD->getDeclName(); 5212 5213 // C++98 [class.union]p1: If a union contains a static data member, 5214 // the program is ill-formed. C++11 drops this restriction. 5215 if (RD->isUnion()) 5216 Diag(D.getIdentifierLoc(), 5217 getLangOpts().CPlusPlus11 5218 ? diag::warn_cxx98_compat_static_data_member_in_union 5219 : diag::ext_static_data_member_in_union) << Name; 5220 // We conservatively disallow static data members in anonymous structs. 5221 else if (!RD->getDeclName()) 5222 Diag(D.getIdentifierLoc(), 5223 diag::err_static_data_member_not_allowed_in_anon_struct) 5224 << Name << RD->isUnion(); 5225 } 5226 } 5227 5228 // Match up the template parameter lists with the scope specifier, then 5229 // determine whether we have a template or a template specialization. 5230 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5231 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5232 D.getCXXScopeSpec(), TemplateParamLists, 5233 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5234 5235 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId && 5236 !TemplateParams) { 5237 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5238 5239 // We have encountered something that the user meant to be a 5240 // specialization (because it has explicitly-specified template 5241 // arguments) but that was not introduced with a "template<>" (or had 5242 // too few of them). 5243 // FIXME: Differentiate between attempts for explicit instantiations 5244 // (starting with "template") and the rest. 5245 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5246 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5247 << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(), 5248 "template<> "); 5249 IsExplicitSpecialization = true; 5250 TemplateParams = TemplateParameterList::Create(Context, SourceLocation(), 5251 SourceLocation(), 0, 0, 5252 SourceLocation()); 5253 } 5254 5255 if (TemplateParams) { 5256 if (!TemplateParams->size() && 5257 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5258 // There is an extraneous 'template<>' for this variable. Complain 5259 // about it, but allow the declaration of the variable. 5260 Diag(TemplateParams->getTemplateLoc(), 5261 diag::err_template_variable_noparams) 5262 << II 5263 << SourceRange(TemplateParams->getTemplateLoc(), 5264 TemplateParams->getRAngleLoc()); 5265 TemplateParams = 0; 5266 } else { 5267 // Only C++1y supports variable templates (N3651). 5268 Diag(D.getIdentifierLoc(), 5269 getLangOpts().CPlusPlus1y 5270 ? diag::warn_cxx11_compat_variable_template 5271 : diag::ext_variable_template); 5272 5273 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5274 // This is an explicit specialization or a partial specialization. 5275 // FIXME: Check that we can declare a specialization here. 5276 IsVariableTemplateSpecialization = true; 5277 IsPartialSpecialization = TemplateParams->size() > 0; 5278 } else { // if (TemplateParams->size() > 0) 5279 // This is a template declaration. 5280 IsVariableTemplate = true; 5281 5282 // Check that we can declare a template here. 5283 if (CheckTemplateDeclScope(S, TemplateParams)) 5284 return 0; 5285 } 5286 } 5287 } 5288 5289 if (IsVariableTemplateSpecialization) { 5290 SourceLocation TemplateKWLoc = 5291 TemplateParamLists.size() > 0 5292 ? TemplateParamLists[0]->getTemplateLoc() 5293 : SourceLocation(); 5294 DeclResult Res = ActOnVarTemplateSpecialization( 5295 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5296 IsPartialSpecialization); 5297 if (Res.isInvalid()) 5298 return 0; 5299 NewVD = cast<VarDecl>(Res.get()); 5300 AddToScope = false; 5301 } else 5302 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5303 D.getIdentifierLoc(), II, R, TInfo, SC); 5304 5305 // If this is supposed to be a variable template, create it as such. 5306 if (IsVariableTemplate) { 5307 NewTemplate = 5308 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5309 TemplateParams, NewVD); 5310 NewVD->setDescribedVarTemplate(NewTemplate); 5311 } 5312 5313 // If this decl has an auto type in need of deduction, make a note of the 5314 // Decl so we can diagnose uses of it in its own initializer. 5315 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5316 ParsingInitForAutoVars.insert(NewVD); 5317 5318 if (D.isInvalidType() || Invalid) { 5319 NewVD->setInvalidDecl(); 5320 if (NewTemplate) 5321 NewTemplate->setInvalidDecl(); 5322 } 5323 5324 SetNestedNameSpecifier(NewVD, D); 5325 5326 // If we have any template parameter lists that don't directly belong to 5327 // the variable (matching the scope specifier), store them. 5328 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5329 if (TemplateParamLists.size() > VDTemplateParamLists) 5330 NewVD->setTemplateParameterListsInfo( 5331 Context, TemplateParamLists.size() - VDTemplateParamLists, 5332 TemplateParamLists.data()); 5333 5334 if (D.getDeclSpec().isConstexprSpecified()) 5335 NewVD->setConstexpr(true); 5336 } 5337 5338 // Set the lexical context. If the declarator has a C++ scope specifier, the 5339 // lexical context will be different from the semantic context. 5340 NewVD->setLexicalDeclContext(CurContext); 5341 if (NewTemplate) 5342 NewTemplate->setLexicalDeclContext(CurContext); 5343 5344 if (IsLocalExternDecl) 5345 NewVD->setLocalExternDecl(); 5346 5347 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5348 if (NewVD->hasLocalStorage()) { 5349 // C++11 [dcl.stc]p4: 5350 // When thread_local is applied to a variable of block scope the 5351 // storage-class-specifier static is implied if it does not appear 5352 // explicitly. 5353 // Core issue: 'static' is not implied if the variable is declared 5354 // 'extern'. 5355 if (SCSpec == DeclSpec::SCS_unspecified && 5356 TSCS == DeclSpec::TSCS_thread_local && 5357 DC->isFunctionOrMethod()) 5358 NewVD->setTSCSpec(TSCS); 5359 else 5360 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5361 diag::err_thread_non_global) 5362 << DeclSpec::getSpecifierName(TSCS); 5363 } else if (!Context.getTargetInfo().isTLSSupported()) 5364 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5365 diag::err_thread_unsupported); 5366 else 5367 NewVD->setTSCSpec(TSCS); 5368 } 5369 5370 // C99 6.7.4p3 5371 // An inline definition of a function with external linkage shall 5372 // not contain a definition of a modifiable object with static or 5373 // thread storage duration... 5374 // We only apply this when the function is required to be defined 5375 // elsewhere, i.e. when the function is not 'extern inline'. Note 5376 // that a local variable with thread storage duration still has to 5377 // be marked 'static'. Also note that it's possible to get these 5378 // semantics in C++ using __attribute__((gnu_inline)). 5379 if (SC == SC_Static && S->getFnParent() != 0 && 5380 !NewVD->getType().isConstQualified()) { 5381 FunctionDecl *CurFD = getCurFunctionDecl(); 5382 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5383 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5384 diag::warn_static_local_in_extern_inline); 5385 MaybeSuggestAddingStaticToDecl(CurFD); 5386 } 5387 } 5388 5389 if (D.getDeclSpec().isModulePrivateSpecified()) { 5390 if (IsVariableTemplateSpecialization) 5391 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5392 << (IsPartialSpecialization ? 1 : 0) 5393 << FixItHint::CreateRemoval( 5394 D.getDeclSpec().getModulePrivateSpecLoc()); 5395 else if (IsExplicitSpecialization) 5396 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5397 << 2 5398 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5399 else if (NewVD->hasLocalStorage()) 5400 Diag(NewVD->getLocation(), diag::err_module_private_local) 5401 << 0 << NewVD->getDeclName() 5402 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5403 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5404 else { 5405 NewVD->setModulePrivate(); 5406 if (NewTemplate) 5407 NewTemplate->setModulePrivate(); 5408 } 5409 } 5410 5411 // Handle attributes prior to checking for duplicates in MergeVarDecl 5412 ProcessDeclAttributes(S, NewVD, D); 5413 5414 if (getLangOpts().CUDA) { 5415 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5416 // storage [duration]." 5417 if (SC == SC_None && S->getFnParent() != 0 && 5418 (NewVD->hasAttr<CUDASharedAttr>() || 5419 NewVD->hasAttr<CUDAConstantAttr>())) { 5420 NewVD->setStorageClass(SC_Static); 5421 } 5422 } 5423 5424 // Ensure that dllimport globals without explicit storage class are treated as 5425 // extern. The storage class is set above using parsed attributes. Now we can 5426 // check the VarDecl itself. 5427 assert(!NewVD->hasAttr<DLLImportAttr>() || 5428 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5429 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5430 5431 // In auto-retain/release, infer strong retension for variables of 5432 // retainable type. 5433 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5434 NewVD->setInvalidDecl(); 5435 5436 // Handle GNU asm-label extension (encoded as an attribute). 5437 if (Expr *E = (Expr*)D.getAsmLabel()) { 5438 // The parser guarantees this is a string. 5439 StringLiteral *SE = cast<StringLiteral>(E); 5440 StringRef Label = SE->getString(); 5441 if (S->getFnParent() != 0) { 5442 switch (SC) { 5443 case SC_None: 5444 case SC_Auto: 5445 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5446 break; 5447 case SC_Register: 5448 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5449 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5450 break; 5451 case SC_Static: 5452 case SC_Extern: 5453 case SC_PrivateExtern: 5454 case SC_OpenCLWorkGroupLocal: 5455 break; 5456 } 5457 } 5458 5459 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5460 Context, Label, 0)); 5461 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5462 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5463 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5464 if (I != ExtnameUndeclaredIdentifiers.end()) { 5465 NewVD->addAttr(I->second); 5466 ExtnameUndeclaredIdentifiers.erase(I); 5467 } 5468 } 5469 5470 // Diagnose shadowed variables before filtering for scope. 5471 if (D.getCXXScopeSpec().isEmpty()) 5472 CheckShadow(S, NewVD, Previous); 5473 5474 // Don't consider existing declarations that are in a different 5475 // scope and are out-of-semantic-context declarations (if the new 5476 // declaration has linkage). 5477 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5478 D.getCXXScopeSpec().isNotEmpty() || 5479 IsExplicitSpecialization || 5480 IsVariableTemplateSpecialization); 5481 5482 // Check whether the previous declaration is in the same block scope. This 5483 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5484 if (getLangOpts().CPlusPlus && 5485 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5486 NewVD->setPreviousDeclInSameBlockScope( 5487 Previous.isSingleResult() && !Previous.isShadowed() && 5488 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5489 5490 if (!getLangOpts().CPlusPlus) { 5491 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5492 } else { 5493 // If this is an explicit specialization of a static data member, check it. 5494 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5495 CheckMemberSpecialization(NewVD, Previous)) 5496 NewVD->setInvalidDecl(); 5497 5498 // Merge the decl with the existing one if appropriate. 5499 if (!Previous.empty()) { 5500 if (Previous.isSingleResult() && 5501 isa<FieldDecl>(Previous.getFoundDecl()) && 5502 D.getCXXScopeSpec().isSet()) { 5503 // The user tried to define a non-static data member 5504 // out-of-line (C++ [dcl.meaning]p1). 5505 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5506 << D.getCXXScopeSpec().getRange(); 5507 Previous.clear(); 5508 NewVD->setInvalidDecl(); 5509 } 5510 } else if (D.getCXXScopeSpec().isSet()) { 5511 // No previous declaration in the qualifying scope. 5512 Diag(D.getIdentifierLoc(), diag::err_no_member) 5513 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5514 << D.getCXXScopeSpec().getRange(); 5515 NewVD->setInvalidDecl(); 5516 } 5517 5518 if (!IsVariableTemplateSpecialization) 5519 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5520 5521 if (NewTemplate) { 5522 VarTemplateDecl *PrevVarTemplate = 5523 NewVD->getPreviousDecl() 5524 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5525 : 0; 5526 5527 // Check the template parameter list of this declaration, possibly 5528 // merging in the template parameter list from the previous variable 5529 // template declaration. 5530 if (CheckTemplateParameterList( 5531 TemplateParams, 5532 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5533 : 0, 5534 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5535 DC->isDependentContext()) 5536 ? TPC_ClassTemplateMember 5537 : TPC_VarTemplate)) 5538 NewVD->setInvalidDecl(); 5539 5540 // If we are providing an explicit specialization of a static variable 5541 // template, make a note of that. 5542 if (PrevVarTemplate && 5543 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5544 PrevVarTemplate->setMemberSpecialization(); 5545 } 5546 } 5547 5548 ProcessPragmaWeak(S, NewVD); 5549 5550 // If this is the first declaration of an extern C variable, update 5551 // the map of such variables. 5552 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5553 isIncompleteDeclExternC(*this, NewVD)) 5554 RegisterLocallyScopedExternCDecl(NewVD, S); 5555 5556 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5557 Decl *ManglingContextDecl; 5558 if (MangleNumberingContext *MCtx = 5559 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5560 ManglingContextDecl)) { 5561 Context.setManglingNumber( 5562 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5563 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5564 } 5565 } 5566 5567 if (D.isRedeclaration() && !Previous.empty()) { 5568 checkDLLAttributeRedeclaration( 5569 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5570 IsExplicitSpecialization); 5571 } 5572 5573 if (NewTemplate) { 5574 if (NewVD->isInvalidDecl()) 5575 NewTemplate->setInvalidDecl(); 5576 ActOnDocumentableDecl(NewTemplate); 5577 return NewTemplate; 5578 } 5579 5580 return NewVD; 5581 } 5582 5583 /// \brief Diagnose variable or built-in function shadowing. Implements 5584 /// -Wshadow. 5585 /// 5586 /// This method is called whenever a VarDecl is added to a "useful" 5587 /// scope. 5588 /// 5589 /// \param S the scope in which the shadowing name is being declared 5590 /// \param R the lookup of the name 5591 /// 5592 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5593 // Return if warning is ignored. 5594 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5595 DiagnosticsEngine::Ignored) 5596 return; 5597 5598 // Don't diagnose declarations at file scope. 5599 if (D->hasGlobalStorage()) 5600 return; 5601 5602 DeclContext *NewDC = D->getDeclContext(); 5603 5604 // Only diagnose if we're shadowing an unambiguous field or variable. 5605 if (R.getResultKind() != LookupResult::Found) 5606 return; 5607 5608 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5609 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5610 return; 5611 5612 // Fields are not shadowed by variables in C++ static methods. 5613 if (isa<FieldDecl>(ShadowedDecl)) 5614 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5615 if (MD->isStatic()) 5616 return; 5617 5618 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5619 if (shadowedVar->isExternC()) { 5620 // For shadowing external vars, make sure that we point to the global 5621 // declaration, not a locally scoped extern declaration. 5622 for (auto I : shadowedVar->redecls()) 5623 if (I->isFileVarDecl()) { 5624 ShadowedDecl = I; 5625 break; 5626 } 5627 } 5628 5629 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5630 5631 // Only warn about certain kinds of shadowing for class members. 5632 if (NewDC && NewDC->isRecord()) { 5633 // In particular, don't warn about shadowing non-class members. 5634 if (!OldDC->isRecord()) 5635 return; 5636 5637 // TODO: should we warn about static data members shadowing 5638 // static data members from base classes? 5639 5640 // TODO: don't diagnose for inaccessible shadowed members. 5641 // This is hard to do perfectly because we might friend the 5642 // shadowing context, but that's just a false negative. 5643 } 5644 5645 // Determine what kind of declaration we're shadowing. 5646 unsigned Kind; 5647 if (isa<RecordDecl>(OldDC)) { 5648 if (isa<FieldDecl>(ShadowedDecl)) 5649 Kind = 3; // field 5650 else 5651 Kind = 2; // static data member 5652 } else if (OldDC->isFileContext()) 5653 Kind = 1; // global 5654 else 5655 Kind = 0; // local 5656 5657 DeclarationName Name = R.getLookupName(); 5658 5659 // Emit warning and note. 5660 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5661 return; 5662 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5663 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5664 } 5665 5666 /// \brief Check -Wshadow without the advantage of a previous lookup. 5667 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5668 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5669 DiagnosticsEngine::Ignored) 5670 return; 5671 5672 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5673 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5674 LookupName(R, S); 5675 CheckShadow(S, D, R); 5676 } 5677 5678 /// Check for conflict between this global or extern "C" declaration and 5679 /// previous global or extern "C" declarations. This is only used in C++. 5680 template<typename T> 5681 static bool checkGlobalOrExternCConflict( 5682 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5683 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5684 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5685 5686 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5687 // The common case: this global doesn't conflict with any extern "C" 5688 // declaration. 5689 return false; 5690 } 5691 5692 if (Prev) { 5693 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5694 // Both the old and new declarations have C language linkage. This is a 5695 // redeclaration. 5696 Previous.clear(); 5697 Previous.addDecl(Prev); 5698 return true; 5699 } 5700 5701 // This is a global, non-extern "C" declaration, and there is a previous 5702 // non-global extern "C" declaration. Diagnose if this is a variable 5703 // declaration. 5704 if (!isa<VarDecl>(ND)) 5705 return false; 5706 } else { 5707 // The declaration is extern "C". Check for any declaration in the 5708 // translation unit which might conflict. 5709 if (IsGlobal) { 5710 // We have already performed the lookup into the translation unit. 5711 IsGlobal = false; 5712 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5713 I != E; ++I) { 5714 if (isa<VarDecl>(*I)) { 5715 Prev = *I; 5716 break; 5717 } 5718 } 5719 } else { 5720 DeclContext::lookup_result R = 5721 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5722 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5723 I != E; ++I) { 5724 if (isa<VarDecl>(*I)) { 5725 Prev = *I; 5726 break; 5727 } 5728 // FIXME: If we have any other entity with this name in global scope, 5729 // the declaration is ill-formed, but that is a defect: it breaks the 5730 // 'stat' hack, for instance. Only variables can have mangled name 5731 // clashes with extern "C" declarations, so only they deserve a 5732 // diagnostic. 5733 } 5734 } 5735 5736 if (!Prev) 5737 return false; 5738 } 5739 5740 // Use the first declaration's location to ensure we point at something which 5741 // is lexically inside an extern "C" linkage-spec. 5742 assert(Prev && "should have found a previous declaration to diagnose"); 5743 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5744 Prev = FD->getFirstDecl(); 5745 else 5746 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5747 5748 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5749 << IsGlobal << ND; 5750 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5751 << IsGlobal; 5752 return false; 5753 } 5754 5755 /// Apply special rules for handling extern "C" declarations. Returns \c true 5756 /// if we have found that this is a redeclaration of some prior entity. 5757 /// 5758 /// Per C++ [dcl.link]p6: 5759 /// Two declarations [for a function or variable] with C language linkage 5760 /// with the same name that appear in different scopes refer to the same 5761 /// [entity]. An entity with C language linkage shall not be declared with 5762 /// the same name as an entity in global scope. 5763 template<typename T> 5764 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5765 LookupResult &Previous) { 5766 if (!S.getLangOpts().CPlusPlus) { 5767 // In C, when declaring a global variable, look for a corresponding 'extern' 5768 // variable declared in function scope. We don't need this in C++, because 5769 // we find local extern decls in the surrounding file-scope DeclContext. 5770 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5771 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5772 Previous.clear(); 5773 Previous.addDecl(Prev); 5774 return true; 5775 } 5776 } 5777 return false; 5778 } 5779 5780 // A declaration in the translation unit can conflict with an extern "C" 5781 // declaration. 5782 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5783 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5784 5785 // An extern "C" declaration can conflict with a declaration in the 5786 // translation unit or can be a redeclaration of an extern "C" declaration 5787 // in another scope. 5788 if (isIncompleteDeclExternC(S,ND)) 5789 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5790 5791 // Neither global nor extern "C": nothing to do. 5792 return false; 5793 } 5794 5795 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5796 // If the decl is already known invalid, don't check it. 5797 if (NewVD->isInvalidDecl()) 5798 return; 5799 5800 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5801 QualType T = TInfo->getType(); 5802 5803 // Defer checking an 'auto' type until its initializer is attached. 5804 if (T->isUndeducedType()) 5805 return; 5806 5807 if (NewVD->hasAttrs()) 5808 CheckAlignasUnderalignment(NewVD); 5809 5810 if (T->isObjCObjectType()) { 5811 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5812 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5813 T = Context.getObjCObjectPointerType(T); 5814 NewVD->setType(T); 5815 } 5816 5817 // Emit an error if an address space was applied to decl with local storage. 5818 // This includes arrays of objects with address space qualifiers, but not 5819 // automatic variables that point to other address spaces. 5820 // ISO/IEC TR 18037 S5.1.2 5821 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5822 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5823 NewVD->setInvalidDecl(); 5824 return; 5825 } 5826 5827 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5828 // __constant address space. 5829 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5830 && T.getAddressSpace() != LangAS::opencl_constant 5831 && !T->isSamplerT()){ 5832 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5833 NewVD->setInvalidDecl(); 5834 return; 5835 } 5836 5837 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5838 // scope. 5839 if ((getLangOpts().OpenCLVersion >= 120) 5840 && NewVD->isStaticLocal()) { 5841 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5842 NewVD->setInvalidDecl(); 5843 return; 5844 } 5845 5846 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5847 && !NewVD->hasAttr<BlocksAttr>()) { 5848 if (getLangOpts().getGC() != LangOptions::NonGC) 5849 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5850 else { 5851 assert(!getLangOpts().ObjCAutoRefCount); 5852 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5853 } 5854 } 5855 5856 bool isVM = T->isVariablyModifiedType(); 5857 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5858 NewVD->hasAttr<BlocksAttr>()) 5859 getCurFunction()->setHasBranchProtectedScope(); 5860 5861 if ((isVM && NewVD->hasLinkage()) || 5862 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5863 bool SizeIsNegative; 5864 llvm::APSInt Oversized; 5865 TypeSourceInfo *FixedTInfo = 5866 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5867 SizeIsNegative, Oversized); 5868 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5869 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5870 // FIXME: This won't give the correct result for 5871 // int a[10][n]; 5872 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5873 5874 if (NewVD->isFileVarDecl()) 5875 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5876 << SizeRange; 5877 else if (NewVD->isStaticLocal()) 5878 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5879 << SizeRange; 5880 else 5881 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5882 << SizeRange; 5883 NewVD->setInvalidDecl(); 5884 return; 5885 } 5886 5887 if (FixedTInfo == 0) { 5888 if (NewVD->isFileVarDecl()) 5889 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5890 else 5891 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5892 NewVD->setInvalidDecl(); 5893 return; 5894 } 5895 5896 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5897 NewVD->setType(FixedTInfo->getType()); 5898 NewVD->setTypeSourceInfo(FixedTInfo); 5899 } 5900 5901 if (T->isVoidType()) { 5902 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5903 // of objects and functions. 5904 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5905 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5906 << T; 5907 NewVD->setInvalidDecl(); 5908 return; 5909 } 5910 } 5911 5912 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5913 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5914 NewVD->setInvalidDecl(); 5915 return; 5916 } 5917 5918 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5919 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5920 NewVD->setInvalidDecl(); 5921 return; 5922 } 5923 5924 if (NewVD->isConstexpr() && !T->isDependentType() && 5925 RequireLiteralType(NewVD->getLocation(), T, 5926 diag::err_constexpr_var_non_literal)) { 5927 NewVD->setInvalidDecl(); 5928 return; 5929 } 5930 } 5931 5932 /// \brief Perform semantic checking on a newly-created variable 5933 /// declaration. 5934 /// 5935 /// This routine performs all of the type-checking required for a 5936 /// variable declaration once it has been built. It is used both to 5937 /// check variables after they have been parsed and their declarators 5938 /// have been translated into a declaration, and to check variables 5939 /// that have been instantiated from a template. 5940 /// 5941 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5942 /// 5943 /// Returns true if the variable declaration is a redeclaration. 5944 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5945 CheckVariableDeclarationType(NewVD); 5946 5947 // If the decl is already known invalid, don't check it. 5948 if (NewVD->isInvalidDecl()) 5949 return false; 5950 5951 // If we did not find anything by this name, look for a non-visible 5952 // extern "C" declaration with the same name. 5953 if (Previous.empty() && 5954 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5955 Previous.setShadowed(); 5956 5957 // Filter out any non-conflicting previous declarations. 5958 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5959 5960 if (!Previous.empty()) { 5961 MergeVarDecl(NewVD, Previous); 5962 return true; 5963 } 5964 return false; 5965 } 5966 5967 /// \brief Data used with FindOverriddenMethod 5968 struct FindOverriddenMethodData { 5969 Sema *S; 5970 CXXMethodDecl *Method; 5971 }; 5972 5973 /// \brief Member lookup function that determines whether a given C++ 5974 /// method overrides a method in a base class, to be used with 5975 /// CXXRecordDecl::lookupInBases(). 5976 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5977 CXXBasePath &Path, 5978 void *UserData) { 5979 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5980 5981 FindOverriddenMethodData *Data 5982 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5983 5984 DeclarationName Name = Data->Method->getDeclName(); 5985 5986 // FIXME: Do we care about other names here too? 5987 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5988 // We really want to find the base class destructor here. 5989 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5990 CanQualType CT = Data->S->Context.getCanonicalType(T); 5991 5992 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5993 } 5994 5995 for (Path.Decls = BaseRecord->lookup(Name); 5996 !Path.Decls.empty(); 5997 Path.Decls = Path.Decls.slice(1)) { 5998 NamedDecl *D = Path.Decls.front(); 5999 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6000 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6001 return true; 6002 } 6003 } 6004 6005 return false; 6006 } 6007 6008 namespace { 6009 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6010 } 6011 /// \brief Report an error regarding overriding, along with any relevant 6012 /// overriden methods. 6013 /// 6014 /// \param DiagID the primary error to report. 6015 /// \param MD the overriding method. 6016 /// \param OEK which overrides to include as notes. 6017 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6018 OverrideErrorKind OEK = OEK_All) { 6019 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6020 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6021 E = MD->end_overridden_methods(); 6022 I != E; ++I) { 6023 // This check (& the OEK parameter) could be replaced by a predicate, but 6024 // without lambdas that would be overkill. This is still nicer than writing 6025 // out the diag loop 3 times. 6026 if ((OEK == OEK_All) || 6027 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6028 (OEK == OEK_Deleted && (*I)->isDeleted())) 6029 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6030 } 6031 } 6032 6033 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6034 /// and if so, check that it's a valid override and remember it. 6035 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6036 // Look for virtual methods in base classes that this method might override. 6037 CXXBasePaths Paths; 6038 FindOverriddenMethodData Data; 6039 Data.Method = MD; 6040 Data.S = this; 6041 bool hasDeletedOverridenMethods = false; 6042 bool hasNonDeletedOverridenMethods = false; 6043 bool AddedAny = false; 6044 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6045 for (auto *I : Paths.found_decls()) { 6046 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6047 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6048 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6049 !CheckOverridingFunctionAttributes(MD, OldMD) && 6050 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6051 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6052 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6053 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6054 AddedAny = true; 6055 } 6056 } 6057 } 6058 } 6059 6060 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6061 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6062 } 6063 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6064 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6065 } 6066 6067 return AddedAny; 6068 } 6069 6070 namespace { 6071 // Struct for holding all of the extra arguments needed by 6072 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6073 struct ActOnFDArgs { 6074 Scope *S; 6075 Declarator &D; 6076 MultiTemplateParamsArg TemplateParamLists; 6077 bool AddToScope; 6078 }; 6079 } 6080 6081 namespace { 6082 6083 // Callback to only accept typo corrections that have a non-zero edit distance. 6084 // Also only accept corrections that have the same parent decl. 6085 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6086 public: 6087 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6088 CXXRecordDecl *Parent) 6089 : Context(Context), OriginalFD(TypoFD), 6090 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 6091 6092 bool ValidateCandidate(const TypoCorrection &candidate) override { 6093 if (candidate.getEditDistance() == 0) 6094 return false; 6095 6096 SmallVector<unsigned, 1> MismatchedParams; 6097 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6098 CDeclEnd = candidate.end(); 6099 CDecl != CDeclEnd; ++CDecl) { 6100 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6101 6102 if (FD && !FD->hasBody() && 6103 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6104 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6105 CXXRecordDecl *Parent = MD->getParent(); 6106 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6107 return true; 6108 } else if (!ExpectedParent) { 6109 return true; 6110 } 6111 } 6112 } 6113 6114 return false; 6115 } 6116 6117 private: 6118 ASTContext &Context; 6119 FunctionDecl *OriginalFD; 6120 CXXRecordDecl *ExpectedParent; 6121 }; 6122 6123 } 6124 6125 /// \brief Generate diagnostics for an invalid function redeclaration. 6126 /// 6127 /// This routine handles generating the diagnostic messages for an invalid 6128 /// function redeclaration, including finding possible similar declarations 6129 /// or performing typo correction if there are no previous declarations with 6130 /// the same name. 6131 /// 6132 /// Returns a NamedDecl iff typo correction was performed and substituting in 6133 /// the new declaration name does not cause new errors. 6134 static NamedDecl *DiagnoseInvalidRedeclaration( 6135 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6136 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6137 DeclarationName Name = NewFD->getDeclName(); 6138 DeclContext *NewDC = NewFD->getDeclContext(); 6139 SmallVector<unsigned, 1> MismatchedParams; 6140 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6141 TypoCorrection Correction; 6142 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6143 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6144 : diag::err_member_decl_does_not_match; 6145 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6146 IsLocalFriend ? Sema::LookupLocalFriendName 6147 : Sema::LookupOrdinaryName, 6148 Sema::ForRedeclaration); 6149 6150 NewFD->setInvalidDecl(); 6151 if (IsLocalFriend) 6152 SemaRef.LookupName(Prev, S); 6153 else 6154 SemaRef.LookupQualifiedName(Prev, NewDC); 6155 assert(!Prev.isAmbiguous() && 6156 "Cannot have an ambiguity in previous-declaration lookup"); 6157 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6158 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6159 MD ? MD->getParent() : 0); 6160 if (!Prev.empty()) { 6161 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6162 Func != FuncEnd; ++Func) { 6163 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6164 if (FD && 6165 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6166 // Add 1 to the index so that 0 can mean the mismatch didn't 6167 // involve a parameter 6168 unsigned ParamNum = 6169 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6170 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6171 } 6172 } 6173 // If the qualified name lookup yielded nothing, try typo correction 6174 } else if ((Correction = SemaRef.CorrectTypo( 6175 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6176 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6177 IsLocalFriend ? 0 : NewDC))) { 6178 // Set up everything for the call to ActOnFunctionDeclarator 6179 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6180 ExtraArgs.D.getIdentifierLoc()); 6181 Previous.clear(); 6182 Previous.setLookupName(Correction.getCorrection()); 6183 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6184 CDeclEnd = Correction.end(); 6185 CDecl != CDeclEnd; ++CDecl) { 6186 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6187 if (FD && !FD->hasBody() && 6188 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6189 Previous.addDecl(FD); 6190 } 6191 } 6192 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6193 6194 NamedDecl *Result; 6195 // Retry building the function declaration with the new previous 6196 // declarations, and with errors suppressed. 6197 { 6198 // Trap errors. 6199 Sema::SFINAETrap Trap(SemaRef); 6200 6201 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6202 // pieces need to verify the typo-corrected C++ declaration and hopefully 6203 // eliminate the need for the parameter pack ExtraArgs. 6204 Result = SemaRef.ActOnFunctionDeclarator( 6205 ExtraArgs.S, ExtraArgs.D, 6206 Correction.getCorrectionDecl()->getDeclContext(), 6207 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6208 ExtraArgs.AddToScope); 6209 6210 if (Trap.hasErrorOccurred()) 6211 Result = 0; 6212 } 6213 6214 if (Result) { 6215 // Determine which correction we picked. 6216 Decl *Canonical = Result->getCanonicalDecl(); 6217 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6218 I != E; ++I) 6219 if ((*I)->getCanonicalDecl() == Canonical) 6220 Correction.setCorrectionDecl(*I); 6221 6222 SemaRef.diagnoseTypo( 6223 Correction, 6224 SemaRef.PDiag(IsLocalFriend 6225 ? diag::err_no_matching_local_friend_suggest 6226 : diag::err_member_decl_does_not_match_suggest) 6227 << Name << NewDC << IsDefinition); 6228 return Result; 6229 } 6230 6231 // Pretend the typo correction never occurred 6232 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6233 ExtraArgs.D.getIdentifierLoc()); 6234 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6235 Previous.clear(); 6236 Previous.setLookupName(Name); 6237 } 6238 6239 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6240 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6241 6242 bool NewFDisConst = false; 6243 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6244 NewFDisConst = NewMD->isConst(); 6245 6246 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6247 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6248 NearMatch != NearMatchEnd; ++NearMatch) { 6249 FunctionDecl *FD = NearMatch->first; 6250 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6251 bool FDisConst = MD && MD->isConst(); 6252 bool IsMember = MD || !IsLocalFriend; 6253 6254 // FIXME: These notes are poorly worded for the local friend case. 6255 if (unsigned Idx = NearMatch->second) { 6256 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6257 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6258 if (Loc.isInvalid()) Loc = FD->getLocation(); 6259 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6260 : diag::note_local_decl_close_param_match) 6261 << Idx << FDParam->getType() 6262 << NewFD->getParamDecl(Idx - 1)->getType(); 6263 } else if (FDisConst != NewFDisConst) { 6264 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6265 << NewFDisConst << FD->getSourceRange().getEnd(); 6266 } else 6267 SemaRef.Diag(FD->getLocation(), 6268 IsMember ? diag::note_member_def_close_match 6269 : diag::note_local_decl_close_match); 6270 } 6271 return 0; 6272 } 6273 6274 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6275 Declarator &D) { 6276 switch (D.getDeclSpec().getStorageClassSpec()) { 6277 default: llvm_unreachable("Unknown storage class!"); 6278 case DeclSpec::SCS_auto: 6279 case DeclSpec::SCS_register: 6280 case DeclSpec::SCS_mutable: 6281 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6282 diag::err_typecheck_sclass_func); 6283 D.setInvalidType(); 6284 break; 6285 case DeclSpec::SCS_unspecified: break; 6286 case DeclSpec::SCS_extern: 6287 if (D.getDeclSpec().isExternInLinkageSpec()) 6288 return SC_None; 6289 return SC_Extern; 6290 case DeclSpec::SCS_static: { 6291 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6292 // C99 6.7.1p5: 6293 // The declaration of an identifier for a function that has 6294 // block scope shall have no explicit storage-class specifier 6295 // other than extern 6296 // See also (C++ [dcl.stc]p4). 6297 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6298 diag::err_static_block_func); 6299 break; 6300 } else 6301 return SC_Static; 6302 } 6303 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6304 } 6305 6306 // No explicit storage class has already been returned 6307 return SC_None; 6308 } 6309 6310 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6311 DeclContext *DC, QualType &R, 6312 TypeSourceInfo *TInfo, 6313 FunctionDecl::StorageClass SC, 6314 bool &IsVirtualOkay) { 6315 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6316 DeclarationName Name = NameInfo.getName(); 6317 6318 FunctionDecl *NewFD = 0; 6319 bool isInline = D.getDeclSpec().isInlineSpecified(); 6320 6321 if (!SemaRef.getLangOpts().CPlusPlus) { 6322 // Determine whether the function was written with a 6323 // prototype. This true when: 6324 // - there is a prototype in the declarator, or 6325 // - the type R of the function is some kind of typedef or other reference 6326 // to a type name (which eventually refers to a function type). 6327 bool HasPrototype = 6328 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6329 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6330 6331 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6332 D.getLocStart(), NameInfo, R, 6333 TInfo, SC, isInline, 6334 HasPrototype, false); 6335 if (D.isInvalidType()) 6336 NewFD->setInvalidDecl(); 6337 6338 // Set the lexical context. 6339 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6340 6341 return NewFD; 6342 } 6343 6344 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6345 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6346 6347 // Check that the return type is not an abstract class type. 6348 // For record types, this is done by the AbstractClassUsageDiagnoser once 6349 // the class has been completely parsed. 6350 if (!DC->isRecord() && 6351 SemaRef.RequireNonAbstractType( 6352 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6353 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6354 D.setInvalidType(); 6355 6356 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6357 // This is a C++ constructor declaration. 6358 assert(DC->isRecord() && 6359 "Constructors can only be declared in a member context"); 6360 6361 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6362 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6363 D.getLocStart(), NameInfo, 6364 R, TInfo, isExplicit, isInline, 6365 /*isImplicitlyDeclared=*/false, 6366 isConstexpr); 6367 6368 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6369 // This is a C++ destructor declaration. 6370 if (DC->isRecord()) { 6371 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6372 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6373 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6374 SemaRef.Context, Record, 6375 D.getLocStart(), 6376 NameInfo, R, TInfo, isInline, 6377 /*isImplicitlyDeclared=*/false); 6378 6379 // If the class is complete, then we now create the implicit exception 6380 // specification. If the class is incomplete or dependent, we can't do 6381 // it yet. 6382 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6383 Record->getDefinition() && !Record->isBeingDefined() && 6384 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6385 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6386 } 6387 6388 IsVirtualOkay = true; 6389 return NewDD; 6390 6391 } else { 6392 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6393 D.setInvalidType(); 6394 6395 // Create a FunctionDecl to satisfy the function definition parsing 6396 // code path. 6397 return FunctionDecl::Create(SemaRef.Context, DC, 6398 D.getLocStart(), 6399 D.getIdentifierLoc(), Name, R, TInfo, 6400 SC, isInline, 6401 /*hasPrototype=*/true, isConstexpr); 6402 } 6403 6404 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6405 if (!DC->isRecord()) { 6406 SemaRef.Diag(D.getIdentifierLoc(), 6407 diag::err_conv_function_not_member); 6408 return 0; 6409 } 6410 6411 SemaRef.CheckConversionDeclarator(D, R, SC); 6412 IsVirtualOkay = true; 6413 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6414 D.getLocStart(), NameInfo, 6415 R, TInfo, isInline, isExplicit, 6416 isConstexpr, SourceLocation()); 6417 6418 } else if (DC->isRecord()) { 6419 // If the name of the function is the same as the name of the record, 6420 // then this must be an invalid constructor that has a return type. 6421 // (The parser checks for a return type and makes the declarator a 6422 // constructor if it has no return type). 6423 if (Name.getAsIdentifierInfo() && 6424 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6425 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6426 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6427 << SourceRange(D.getIdentifierLoc()); 6428 return 0; 6429 } 6430 6431 // This is a C++ method declaration. 6432 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6433 cast<CXXRecordDecl>(DC), 6434 D.getLocStart(), NameInfo, R, 6435 TInfo, SC, isInline, 6436 isConstexpr, SourceLocation()); 6437 IsVirtualOkay = !Ret->isStatic(); 6438 return Ret; 6439 } else { 6440 // Determine whether the function was written with a 6441 // prototype. This true when: 6442 // - we're in C++ (where every function has a prototype), 6443 return FunctionDecl::Create(SemaRef.Context, DC, 6444 D.getLocStart(), 6445 NameInfo, R, TInfo, SC, isInline, 6446 true/*HasPrototype*/, isConstexpr); 6447 } 6448 } 6449 6450 enum OpenCLParamType { 6451 ValidKernelParam, 6452 PtrPtrKernelParam, 6453 PtrKernelParam, 6454 PrivatePtrKernelParam, 6455 InvalidKernelParam, 6456 RecordKernelParam 6457 }; 6458 6459 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6460 if (PT->isPointerType()) { 6461 QualType PointeeType = PT->getPointeeType(); 6462 if (PointeeType->isPointerType()) 6463 return PtrPtrKernelParam; 6464 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6465 : PtrKernelParam; 6466 } 6467 6468 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6469 // be used as builtin types. 6470 6471 if (PT->isImageType()) 6472 return PtrKernelParam; 6473 6474 if (PT->isBooleanType()) 6475 return InvalidKernelParam; 6476 6477 if (PT->isEventT()) 6478 return InvalidKernelParam; 6479 6480 if (PT->isHalfType()) 6481 return InvalidKernelParam; 6482 6483 if (PT->isRecordType()) 6484 return RecordKernelParam; 6485 6486 return ValidKernelParam; 6487 } 6488 6489 static void checkIsValidOpenCLKernelParameter( 6490 Sema &S, 6491 Declarator &D, 6492 ParmVarDecl *Param, 6493 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6494 QualType PT = Param->getType(); 6495 6496 // Cache the valid types we encounter to avoid rechecking structs that are 6497 // used again 6498 if (ValidTypes.count(PT.getTypePtr())) 6499 return; 6500 6501 switch (getOpenCLKernelParameterType(PT)) { 6502 case PtrPtrKernelParam: 6503 // OpenCL v1.2 s6.9.a: 6504 // A kernel function argument cannot be declared as a 6505 // pointer to a pointer type. 6506 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6507 D.setInvalidType(); 6508 return; 6509 6510 case PrivatePtrKernelParam: 6511 // OpenCL v1.2 s6.9.a: 6512 // A kernel function argument cannot be declared as a 6513 // pointer to the private address space. 6514 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6515 D.setInvalidType(); 6516 return; 6517 6518 // OpenCL v1.2 s6.9.k: 6519 // Arguments to kernel functions in a program cannot be declared with the 6520 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6521 // uintptr_t or a struct and/or union that contain fields declared to be 6522 // one of these built-in scalar types. 6523 6524 case InvalidKernelParam: 6525 // OpenCL v1.2 s6.8 n: 6526 // A kernel function argument cannot be declared 6527 // of event_t type. 6528 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6529 D.setInvalidType(); 6530 return; 6531 6532 case PtrKernelParam: 6533 case ValidKernelParam: 6534 ValidTypes.insert(PT.getTypePtr()); 6535 return; 6536 6537 case RecordKernelParam: 6538 break; 6539 } 6540 6541 // Track nested structs we will inspect 6542 SmallVector<const Decl *, 4> VisitStack; 6543 6544 // Track where we are in the nested structs. Items will migrate from 6545 // VisitStack to HistoryStack as we do the DFS for bad field. 6546 SmallVector<const FieldDecl *, 4> HistoryStack; 6547 HistoryStack.push_back((const FieldDecl *) 0); 6548 6549 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6550 VisitStack.push_back(PD); 6551 6552 assert(VisitStack.back() && "First decl null?"); 6553 6554 do { 6555 const Decl *Next = VisitStack.pop_back_val(); 6556 if (!Next) { 6557 assert(!HistoryStack.empty()); 6558 // Found a marker, we have gone up a level 6559 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6560 ValidTypes.insert(Hist->getType().getTypePtr()); 6561 6562 continue; 6563 } 6564 6565 // Adds everything except the original parameter declaration (which is not a 6566 // field itself) to the history stack. 6567 const RecordDecl *RD; 6568 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6569 HistoryStack.push_back(Field); 6570 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6571 } else { 6572 RD = cast<RecordDecl>(Next); 6573 } 6574 6575 // Add a null marker so we know when we've gone back up a level 6576 VisitStack.push_back((const Decl *) 0); 6577 6578 for (const auto *FD : RD->fields()) { 6579 QualType QT = FD->getType(); 6580 6581 if (ValidTypes.count(QT.getTypePtr())) 6582 continue; 6583 6584 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6585 if (ParamType == ValidKernelParam) 6586 continue; 6587 6588 if (ParamType == RecordKernelParam) { 6589 VisitStack.push_back(FD); 6590 continue; 6591 } 6592 6593 // OpenCL v1.2 s6.9.p: 6594 // Arguments to kernel functions that are declared to be a struct or union 6595 // do not allow OpenCL objects to be passed as elements of the struct or 6596 // union. 6597 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6598 ParamType == PrivatePtrKernelParam) { 6599 S.Diag(Param->getLocation(), 6600 diag::err_record_with_pointers_kernel_param) 6601 << PT->isUnionType() 6602 << PT; 6603 } else { 6604 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6605 } 6606 6607 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6608 << PD->getDeclName(); 6609 6610 // We have an error, now let's go back up through history and show where 6611 // the offending field came from 6612 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6613 E = HistoryStack.end(); I != E; ++I) { 6614 const FieldDecl *OuterField = *I; 6615 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6616 << OuterField->getType(); 6617 } 6618 6619 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6620 << QT->isPointerType() 6621 << QT; 6622 D.setInvalidType(); 6623 return; 6624 } 6625 } while (!VisitStack.empty()); 6626 } 6627 6628 NamedDecl* 6629 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6630 TypeSourceInfo *TInfo, LookupResult &Previous, 6631 MultiTemplateParamsArg TemplateParamLists, 6632 bool &AddToScope) { 6633 QualType R = TInfo->getType(); 6634 6635 assert(R.getTypePtr()->isFunctionType()); 6636 6637 // TODO: consider using NameInfo for diagnostic. 6638 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6639 DeclarationName Name = NameInfo.getName(); 6640 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6641 6642 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6643 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6644 diag::err_invalid_thread) 6645 << DeclSpec::getSpecifierName(TSCS); 6646 6647 if (D.isFirstDeclarationOfMember()) 6648 adjustMemberFunctionCC(R, D.isStaticMember()); 6649 6650 bool isFriend = false; 6651 FunctionTemplateDecl *FunctionTemplate = 0; 6652 bool isExplicitSpecialization = false; 6653 bool isFunctionTemplateSpecialization = false; 6654 6655 bool isDependentClassScopeExplicitSpecialization = false; 6656 bool HasExplicitTemplateArgs = false; 6657 TemplateArgumentListInfo TemplateArgs; 6658 6659 bool isVirtualOkay = false; 6660 6661 DeclContext *OriginalDC = DC; 6662 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6663 6664 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6665 isVirtualOkay); 6666 if (!NewFD) return 0; 6667 6668 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6669 NewFD->setTopLevelDeclInObjCContainer(); 6670 6671 // Set the lexical context. If this is a function-scope declaration, or has a 6672 // C++ scope specifier, or is the object of a friend declaration, the lexical 6673 // context will be different from the semantic context. 6674 NewFD->setLexicalDeclContext(CurContext); 6675 6676 if (IsLocalExternDecl) 6677 NewFD->setLocalExternDecl(); 6678 6679 if (getLangOpts().CPlusPlus) { 6680 bool isInline = D.getDeclSpec().isInlineSpecified(); 6681 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6682 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6683 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6684 isFriend = D.getDeclSpec().isFriendSpecified(); 6685 if (isFriend && !isInline && D.isFunctionDefinition()) { 6686 // C++ [class.friend]p5 6687 // A function can be defined in a friend declaration of a 6688 // class . . . . Such a function is implicitly inline. 6689 NewFD->setImplicitlyInline(); 6690 } 6691 6692 // If this is a method defined in an __interface, and is not a constructor 6693 // or an overloaded operator, then set the pure flag (isVirtual will already 6694 // return true). 6695 if (const CXXRecordDecl *Parent = 6696 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6697 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6698 NewFD->setPure(true); 6699 } 6700 6701 SetNestedNameSpecifier(NewFD, D); 6702 isExplicitSpecialization = false; 6703 isFunctionTemplateSpecialization = false; 6704 if (D.isInvalidType()) 6705 NewFD->setInvalidDecl(); 6706 6707 // Match up the template parameter lists with the scope specifier, then 6708 // determine whether we have a template or a template specialization. 6709 bool Invalid = false; 6710 if (TemplateParameterList *TemplateParams = 6711 MatchTemplateParametersToScopeSpecifier( 6712 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6713 D.getCXXScopeSpec(), TemplateParamLists, isFriend, 6714 isExplicitSpecialization, Invalid)) { 6715 if (TemplateParams->size() > 0) { 6716 // This is a function template 6717 6718 // Check that we can declare a template here. 6719 if (CheckTemplateDeclScope(S, TemplateParams)) 6720 return 0; 6721 6722 // A destructor cannot be a template. 6723 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6724 Diag(NewFD->getLocation(), diag::err_destructor_template); 6725 return 0; 6726 } 6727 6728 // If we're adding a template to a dependent context, we may need to 6729 // rebuilding some of the types used within the template parameter list, 6730 // now that we know what the current instantiation is. 6731 if (DC->isDependentContext()) { 6732 ContextRAII SavedContext(*this, DC); 6733 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6734 Invalid = true; 6735 } 6736 6737 6738 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6739 NewFD->getLocation(), 6740 Name, TemplateParams, 6741 NewFD); 6742 FunctionTemplate->setLexicalDeclContext(CurContext); 6743 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6744 6745 // For source fidelity, store the other template param lists. 6746 if (TemplateParamLists.size() > 1) { 6747 NewFD->setTemplateParameterListsInfo(Context, 6748 TemplateParamLists.size() - 1, 6749 TemplateParamLists.data()); 6750 } 6751 } else { 6752 // This is a function template specialization. 6753 isFunctionTemplateSpecialization = true; 6754 // For source fidelity, store all the template param lists. 6755 NewFD->setTemplateParameterListsInfo(Context, 6756 TemplateParamLists.size(), 6757 TemplateParamLists.data()); 6758 6759 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6760 if (isFriend) { 6761 // We want to remove the "template<>", found here. 6762 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6763 6764 // If we remove the template<> and the name is not a 6765 // template-id, we're actually silently creating a problem: 6766 // the friend declaration will refer to an untemplated decl, 6767 // and clearly the user wants a template specialization. So 6768 // we need to insert '<>' after the name. 6769 SourceLocation InsertLoc; 6770 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6771 InsertLoc = D.getName().getSourceRange().getEnd(); 6772 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6773 } 6774 6775 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6776 << Name << RemoveRange 6777 << FixItHint::CreateRemoval(RemoveRange) 6778 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6779 } 6780 } 6781 } 6782 else { 6783 // All template param lists were matched against the scope specifier: 6784 // this is NOT (an explicit specialization of) a template. 6785 if (TemplateParamLists.size() > 0) 6786 // For source fidelity, store all the template param lists. 6787 NewFD->setTemplateParameterListsInfo(Context, 6788 TemplateParamLists.size(), 6789 TemplateParamLists.data()); 6790 } 6791 6792 if (Invalid) { 6793 NewFD->setInvalidDecl(); 6794 if (FunctionTemplate) 6795 FunctionTemplate->setInvalidDecl(); 6796 } 6797 6798 // C++ [dcl.fct.spec]p5: 6799 // The virtual specifier shall only be used in declarations of 6800 // nonstatic class member functions that appear within a 6801 // member-specification of a class declaration; see 10.3. 6802 // 6803 if (isVirtual && !NewFD->isInvalidDecl()) { 6804 if (!isVirtualOkay) { 6805 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6806 diag::err_virtual_non_function); 6807 } else if (!CurContext->isRecord()) { 6808 // 'virtual' was specified outside of the class. 6809 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6810 diag::err_virtual_out_of_class) 6811 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6812 } else if (NewFD->getDescribedFunctionTemplate()) { 6813 // C++ [temp.mem]p3: 6814 // A member function template shall not be virtual. 6815 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6816 diag::err_virtual_member_function_template) 6817 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6818 } else { 6819 // Okay: Add virtual to the method. 6820 NewFD->setVirtualAsWritten(true); 6821 } 6822 6823 if (getLangOpts().CPlusPlus1y && 6824 NewFD->getReturnType()->isUndeducedType()) 6825 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6826 } 6827 6828 if (getLangOpts().CPlusPlus1y && 6829 (NewFD->isDependentContext() || 6830 (isFriend && CurContext->isDependentContext())) && 6831 NewFD->getReturnType()->isUndeducedType()) { 6832 // If the function template is referenced directly (for instance, as a 6833 // member of the current instantiation), pretend it has a dependent type. 6834 // This is not really justified by the standard, but is the only sane 6835 // thing to do. 6836 // FIXME: For a friend function, we have not marked the function as being 6837 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6838 const FunctionProtoType *FPT = 6839 NewFD->getType()->castAs<FunctionProtoType>(); 6840 QualType Result = 6841 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6842 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6843 FPT->getExtProtoInfo())); 6844 } 6845 6846 // C++ [dcl.fct.spec]p3: 6847 // The inline specifier shall not appear on a block scope function 6848 // declaration. 6849 if (isInline && !NewFD->isInvalidDecl()) { 6850 if (CurContext->isFunctionOrMethod()) { 6851 // 'inline' is not allowed on block scope function declaration. 6852 Diag(D.getDeclSpec().getInlineSpecLoc(), 6853 diag::err_inline_declaration_block_scope) << Name 6854 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6855 } 6856 } 6857 6858 // C++ [dcl.fct.spec]p6: 6859 // The explicit specifier shall be used only in the declaration of a 6860 // constructor or conversion function within its class definition; 6861 // see 12.3.1 and 12.3.2. 6862 if (isExplicit && !NewFD->isInvalidDecl()) { 6863 if (!CurContext->isRecord()) { 6864 // 'explicit' was specified outside of the class. 6865 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6866 diag::err_explicit_out_of_class) 6867 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6868 } else if (!isa<CXXConstructorDecl>(NewFD) && 6869 !isa<CXXConversionDecl>(NewFD)) { 6870 // 'explicit' was specified on a function that wasn't a constructor 6871 // or conversion function. 6872 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6873 diag::err_explicit_non_ctor_or_conv_function) 6874 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6875 } 6876 } 6877 6878 if (isConstexpr) { 6879 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6880 // are implicitly inline. 6881 NewFD->setImplicitlyInline(); 6882 6883 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6884 // be either constructors or to return a literal type. Therefore, 6885 // destructors cannot be declared constexpr. 6886 if (isa<CXXDestructorDecl>(NewFD)) 6887 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6888 } 6889 6890 // If __module_private__ was specified, mark the function accordingly. 6891 if (D.getDeclSpec().isModulePrivateSpecified()) { 6892 if (isFunctionTemplateSpecialization) { 6893 SourceLocation ModulePrivateLoc 6894 = D.getDeclSpec().getModulePrivateSpecLoc(); 6895 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6896 << 0 6897 << FixItHint::CreateRemoval(ModulePrivateLoc); 6898 } else { 6899 NewFD->setModulePrivate(); 6900 if (FunctionTemplate) 6901 FunctionTemplate->setModulePrivate(); 6902 } 6903 } 6904 6905 if (isFriend) { 6906 if (FunctionTemplate) { 6907 FunctionTemplate->setObjectOfFriendDecl(); 6908 FunctionTemplate->setAccess(AS_public); 6909 } 6910 NewFD->setObjectOfFriendDecl(); 6911 NewFD->setAccess(AS_public); 6912 } 6913 6914 // If a function is defined as defaulted or deleted, mark it as such now. 6915 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6916 // definition kind to FDK_Definition. 6917 switch (D.getFunctionDefinitionKind()) { 6918 case FDK_Declaration: 6919 case FDK_Definition: 6920 break; 6921 6922 case FDK_Defaulted: 6923 NewFD->setDefaulted(); 6924 break; 6925 6926 case FDK_Deleted: 6927 NewFD->setDeletedAsWritten(); 6928 break; 6929 } 6930 6931 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6932 D.isFunctionDefinition()) { 6933 // C++ [class.mfct]p2: 6934 // A member function may be defined (8.4) in its class definition, in 6935 // which case it is an inline member function (7.1.2) 6936 NewFD->setImplicitlyInline(); 6937 } 6938 6939 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6940 !CurContext->isRecord()) { 6941 // C++ [class.static]p1: 6942 // A data or function member of a class may be declared static 6943 // in a class definition, in which case it is a static member of 6944 // the class. 6945 6946 // Complain about the 'static' specifier if it's on an out-of-line 6947 // member function definition. 6948 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6949 diag::err_static_out_of_line) 6950 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6951 } 6952 6953 // C++11 [except.spec]p15: 6954 // A deallocation function with no exception-specification is treated 6955 // as if it were specified with noexcept(true). 6956 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6957 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6958 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6959 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6960 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6961 EPI.ExceptionSpecType = EST_BasicNoexcept; 6962 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 6963 FPT->getParamTypes(), EPI)); 6964 } 6965 } 6966 6967 // Filter out previous declarations that don't match the scope. 6968 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6969 D.getCXXScopeSpec().isNotEmpty() || 6970 isExplicitSpecialization || 6971 isFunctionTemplateSpecialization); 6972 6973 // Handle GNU asm-label extension (encoded as an attribute). 6974 if (Expr *E = (Expr*) D.getAsmLabel()) { 6975 // The parser guarantees this is a string. 6976 StringLiteral *SE = cast<StringLiteral>(E); 6977 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6978 SE->getString(), 0)); 6979 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6980 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6981 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6982 if (I != ExtnameUndeclaredIdentifiers.end()) { 6983 NewFD->addAttr(I->second); 6984 ExtnameUndeclaredIdentifiers.erase(I); 6985 } 6986 } 6987 6988 // Copy the parameter declarations from the declarator D to the function 6989 // declaration NewFD, if they are available. First scavenge them into Params. 6990 SmallVector<ParmVarDecl*, 16> Params; 6991 if (D.isFunctionDeclarator()) { 6992 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6993 6994 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6995 // function that takes no arguments, not a function that takes a 6996 // single void argument. 6997 // We let through "const void" here because Sema::GetTypeForDeclarator 6998 // already checks for that case. 6999 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 && 7000 FTI.Params[0].Param && 7001 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) { 7002 // Empty arg list, don't push any params. 7003 } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) { 7004 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7005 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7006 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7007 Param->setDeclContext(NewFD); 7008 Params.push_back(Param); 7009 7010 if (Param->isInvalidDecl()) 7011 NewFD->setInvalidDecl(); 7012 } 7013 } 7014 7015 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7016 // When we're declaring a function with a typedef, typeof, etc as in the 7017 // following example, we'll need to synthesize (unnamed) 7018 // parameters for use in the declaration. 7019 // 7020 // @code 7021 // typedef void fn(int); 7022 // fn f; 7023 // @endcode 7024 7025 // Synthesize a parameter for each argument type. 7026 for (const auto &AI : FT->param_types()) { 7027 ParmVarDecl *Param = 7028 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7029 Param->setScopeInfo(0, Params.size()); 7030 Params.push_back(Param); 7031 } 7032 } else { 7033 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7034 "Should not need args for typedef of non-prototype fn"); 7035 } 7036 7037 // Finally, we know we have the right number of parameters, install them. 7038 NewFD->setParams(Params); 7039 7040 // Find all anonymous symbols defined during the declaration of this function 7041 // and add to NewFD. This lets us track decls such 'enum Y' in: 7042 // 7043 // void f(enum Y {AA} x) {} 7044 // 7045 // which would otherwise incorrectly end up in the translation unit scope. 7046 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7047 DeclsInPrototypeScope.clear(); 7048 7049 if (D.getDeclSpec().isNoreturnSpecified()) 7050 NewFD->addAttr( 7051 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7052 Context, 0)); 7053 7054 // Functions returning a variably modified type violate C99 6.7.5.2p2 7055 // because all functions have linkage. 7056 if (!NewFD->isInvalidDecl() && 7057 NewFD->getReturnType()->isVariablyModifiedType()) { 7058 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7059 NewFD->setInvalidDecl(); 7060 } 7061 7062 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7063 !NewFD->hasAttr<SectionAttr>()) { 7064 NewFD->addAttr( 7065 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7066 CodeSegStack.CurrentValue->getString(), 7067 CodeSegStack.CurrentPragmaLocation)); 7068 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7069 PSF_Implicit | PSF_Execute | PSF_Read, NewFD)) 7070 NewFD->dropAttr<SectionAttr>(); 7071 } 7072 7073 // Handle attributes. 7074 ProcessDeclAttributes(S, NewFD, D); 7075 7076 QualType RetType = NewFD->getReturnType(); 7077 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7078 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7079 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7080 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7081 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7082 // Attach WarnUnusedResult to functions returning types with that attribute. 7083 // Don't apply the attribute to that type's own non-static member functions 7084 // (to avoid warning on things like assignment operators) 7085 if (!MD || MD->getParent() != Ret) 7086 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7087 } 7088 7089 if (getLangOpts().OpenCL) { 7090 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7091 // type declaration will generate a compilation error. 7092 unsigned AddressSpace = RetType.getAddressSpace(); 7093 if (AddressSpace == LangAS::opencl_local || 7094 AddressSpace == LangAS::opencl_global || 7095 AddressSpace == LangAS::opencl_constant) { 7096 Diag(NewFD->getLocation(), 7097 diag::err_opencl_return_value_with_address_space); 7098 NewFD->setInvalidDecl(); 7099 } 7100 } 7101 7102 if (!getLangOpts().CPlusPlus) { 7103 // Perform semantic checking on the function declaration. 7104 bool isExplicitSpecialization=false; 7105 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7106 CheckMain(NewFD, D.getDeclSpec()); 7107 7108 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7109 CheckMSVCRTEntryPoint(NewFD); 7110 7111 if (!NewFD->isInvalidDecl()) 7112 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7113 isExplicitSpecialization)); 7114 else if (!Previous.empty()) 7115 // Make graceful recovery from an invalid redeclaration. 7116 D.setRedeclaration(true); 7117 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7118 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7119 "previous declaration set still overloaded"); 7120 } else { 7121 // C++11 [replacement.functions]p3: 7122 // The program's definitions shall not be specified as inline. 7123 // 7124 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7125 // 7126 // Suppress the diagnostic if the function is __attribute__((used)), since 7127 // that forces an external definition to be emitted. 7128 if (D.getDeclSpec().isInlineSpecified() && 7129 NewFD->isReplaceableGlobalAllocationFunction() && 7130 !NewFD->hasAttr<UsedAttr>()) 7131 Diag(D.getDeclSpec().getInlineSpecLoc(), 7132 diag::ext_operator_new_delete_declared_inline) 7133 << NewFD->getDeclName(); 7134 7135 // If the declarator is a template-id, translate the parser's template 7136 // argument list into our AST format. 7137 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7138 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7139 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7140 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7141 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7142 TemplateId->NumArgs); 7143 translateTemplateArguments(TemplateArgsPtr, 7144 TemplateArgs); 7145 7146 HasExplicitTemplateArgs = true; 7147 7148 if (NewFD->isInvalidDecl()) { 7149 HasExplicitTemplateArgs = false; 7150 } else if (FunctionTemplate) { 7151 // Function template with explicit template arguments. 7152 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7153 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7154 7155 HasExplicitTemplateArgs = false; 7156 } else if (!isFunctionTemplateSpecialization && 7157 !D.getDeclSpec().isFriendSpecified()) { 7158 // We have encountered something that the user meant to be a 7159 // specialization (because it has explicitly-specified template 7160 // arguments) but that was not introduced with a "template<>" (or had 7161 // too few of them). 7162 // FIXME: Differentiate between attempts for explicit instantiations 7163 // (starting with "template") and the rest. 7164 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 7165 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 7166 << FixItHint::CreateInsertion( 7167 D.getDeclSpec().getLocStart(), 7168 "template<> "); 7169 isFunctionTemplateSpecialization = true; 7170 } else { 7171 // "friend void foo<>(int);" is an implicit specialization decl. 7172 isFunctionTemplateSpecialization = true; 7173 } 7174 } else if (isFriend && isFunctionTemplateSpecialization) { 7175 // This combination is only possible in a recovery case; the user 7176 // wrote something like: 7177 // template <> friend void foo(int); 7178 // which we're recovering from as if the user had written: 7179 // friend void foo<>(int); 7180 // Go ahead and fake up a template id. 7181 HasExplicitTemplateArgs = true; 7182 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7183 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7184 } 7185 7186 // If it's a friend (and only if it's a friend), it's possible 7187 // that either the specialized function type or the specialized 7188 // template is dependent, and therefore matching will fail. In 7189 // this case, don't check the specialization yet. 7190 bool InstantiationDependent = false; 7191 if (isFunctionTemplateSpecialization && isFriend && 7192 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7193 TemplateSpecializationType::anyDependentTemplateArguments( 7194 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7195 InstantiationDependent))) { 7196 assert(HasExplicitTemplateArgs && 7197 "friend function specialization without template args"); 7198 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7199 Previous)) 7200 NewFD->setInvalidDecl(); 7201 } else if (isFunctionTemplateSpecialization) { 7202 if (CurContext->isDependentContext() && CurContext->isRecord() 7203 && !isFriend) { 7204 isDependentClassScopeExplicitSpecialization = true; 7205 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7206 diag::ext_function_specialization_in_class : 7207 diag::err_function_specialization_in_class) 7208 << NewFD->getDeclName(); 7209 } else if (CheckFunctionTemplateSpecialization(NewFD, 7210 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7211 Previous)) 7212 NewFD->setInvalidDecl(); 7213 7214 // C++ [dcl.stc]p1: 7215 // A storage-class-specifier shall not be specified in an explicit 7216 // specialization (14.7.3) 7217 FunctionTemplateSpecializationInfo *Info = 7218 NewFD->getTemplateSpecializationInfo(); 7219 if (Info && SC != SC_None) { 7220 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7221 Diag(NewFD->getLocation(), 7222 diag::err_explicit_specialization_inconsistent_storage_class) 7223 << SC 7224 << FixItHint::CreateRemoval( 7225 D.getDeclSpec().getStorageClassSpecLoc()); 7226 7227 else 7228 Diag(NewFD->getLocation(), 7229 diag::ext_explicit_specialization_storage_class) 7230 << FixItHint::CreateRemoval( 7231 D.getDeclSpec().getStorageClassSpecLoc()); 7232 } 7233 7234 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7235 if (CheckMemberSpecialization(NewFD, Previous)) 7236 NewFD->setInvalidDecl(); 7237 } 7238 7239 // Perform semantic checking on the function declaration. 7240 if (!isDependentClassScopeExplicitSpecialization) { 7241 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7242 CheckMain(NewFD, D.getDeclSpec()); 7243 7244 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7245 CheckMSVCRTEntryPoint(NewFD); 7246 7247 if (!NewFD->isInvalidDecl()) 7248 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7249 isExplicitSpecialization)); 7250 } 7251 7252 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7253 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7254 "previous declaration set still overloaded"); 7255 7256 NamedDecl *PrincipalDecl = (FunctionTemplate 7257 ? cast<NamedDecl>(FunctionTemplate) 7258 : NewFD); 7259 7260 if (isFriend && D.isRedeclaration()) { 7261 AccessSpecifier Access = AS_public; 7262 if (!NewFD->isInvalidDecl()) 7263 Access = NewFD->getPreviousDecl()->getAccess(); 7264 7265 NewFD->setAccess(Access); 7266 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7267 } 7268 7269 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7270 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7271 PrincipalDecl->setNonMemberOperator(); 7272 7273 // If we have a function template, check the template parameter 7274 // list. This will check and merge default template arguments. 7275 if (FunctionTemplate) { 7276 FunctionTemplateDecl *PrevTemplate = 7277 FunctionTemplate->getPreviousDecl(); 7278 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7279 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7280 D.getDeclSpec().isFriendSpecified() 7281 ? (D.isFunctionDefinition() 7282 ? TPC_FriendFunctionTemplateDefinition 7283 : TPC_FriendFunctionTemplate) 7284 : (D.getCXXScopeSpec().isSet() && 7285 DC && DC->isRecord() && 7286 DC->isDependentContext()) 7287 ? TPC_ClassTemplateMember 7288 : TPC_FunctionTemplate); 7289 } 7290 7291 if (NewFD->isInvalidDecl()) { 7292 // Ignore all the rest of this. 7293 } else if (!D.isRedeclaration()) { 7294 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7295 AddToScope }; 7296 // Fake up an access specifier if it's supposed to be a class member. 7297 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7298 NewFD->setAccess(AS_public); 7299 7300 // Qualified decls generally require a previous declaration. 7301 if (D.getCXXScopeSpec().isSet()) { 7302 // ...with the major exception of templated-scope or 7303 // dependent-scope friend declarations. 7304 7305 // TODO: we currently also suppress this check in dependent 7306 // contexts because (1) the parameter depth will be off when 7307 // matching friend templates and (2) we might actually be 7308 // selecting a friend based on a dependent factor. But there 7309 // are situations where these conditions don't apply and we 7310 // can actually do this check immediately. 7311 if (isFriend && 7312 (TemplateParamLists.size() || 7313 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7314 CurContext->isDependentContext())) { 7315 // ignore these 7316 } else { 7317 // The user tried to provide an out-of-line definition for a 7318 // function that is a member of a class or namespace, but there 7319 // was no such member function declared (C++ [class.mfct]p2, 7320 // C++ [namespace.memdef]p2). For example: 7321 // 7322 // class X { 7323 // void f() const; 7324 // }; 7325 // 7326 // void X::f() { } // ill-formed 7327 // 7328 // Complain about this problem, and attempt to suggest close 7329 // matches (e.g., those that differ only in cv-qualifiers and 7330 // whether the parameter types are references). 7331 7332 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7333 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7334 AddToScope = ExtraArgs.AddToScope; 7335 return Result; 7336 } 7337 } 7338 7339 // Unqualified local friend declarations are required to resolve 7340 // to something. 7341 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7342 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7343 *this, Previous, NewFD, ExtraArgs, true, S)) { 7344 AddToScope = ExtraArgs.AddToScope; 7345 return Result; 7346 } 7347 } 7348 7349 } else if (!D.isFunctionDefinition() && 7350 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7351 !isFriend && !isFunctionTemplateSpecialization && 7352 !isExplicitSpecialization) { 7353 // An out-of-line member function declaration must also be a 7354 // definition (C++ [class.mfct]p2). 7355 // Note that this is not the case for explicit specializations of 7356 // function templates or member functions of class templates, per 7357 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7358 // extension for compatibility with old SWIG code which likes to 7359 // generate them. 7360 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7361 << D.getCXXScopeSpec().getRange(); 7362 } 7363 } 7364 7365 ProcessPragmaWeak(S, NewFD); 7366 checkAttributesAfterMerging(*this, *NewFD); 7367 7368 AddKnownFunctionAttributes(NewFD); 7369 7370 if (NewFD->hasAttr<OverloadableAttr>() && 7371 !NewFD->getType()->getAs<FunctionProtoType>()) { 7372 Diag(NewFD->getLocation(), 7373 diag::err_attribute_overloadable_no_prototype) 7374 << NewFD; 7375 7376 // Turn this into a variadic function with no parameters. 7377 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7378 FunctionProtoType::ExtProtoInfo EPI( 7379 Context.getDefaultCallingConvention(true, false)); 7380 EPI.Variadic = true; 7381 EPI.ExtInfo = FT->getExtInfo(); 7382 7383 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7384 NewFD->setType(R); 7385 } 7386 7387 // If there's a #pragma GCC visibility in scope, and this isn't a class 7388 // member, set the visibility of this function. 7389 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7390 AddPushedVisibilityAttribute(NewFD); 7391 7392 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7393 // marking the function. 7394 AddCFAuditedAttribute(NewFD); 7395 7396 // If this is the first declaration of an extern C variable, update 7397 // the map of such variables. 7398 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7399 isIncompleteDeclExternC(*this, NewFD)) 7400 RegisterLocallyScopedExternCDecl(NewFD, S); 7401 7402 // Set this FunctionDecl's range up to the right paren. 7403 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7404 7405 if (D.isRedeclaration() && !Previous.empty()) { 7406 checkDLLAttributeRedeclaration( 7407 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7408 isExplicitSpecialization || isFunctionTemplateSpecialization); 7409 } 7410 7411 if (getLangOpts().CPlusPlus) { 7412 if (FunctionTemplate) { 7413 if (NewFD->isInvalidDecl()) 7414 FunctionTemplate->setInvalidDecl(); 7415 return FunctionTemplate; 7416 } 7417 } 7418 7419 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7420 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7421 if ((getLangOpts().OpenCLVersion >= 120) 7422 && (SC == SC_Static)) { 7423 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7424 D.setInvalidType(); 7425 } 7426 7427 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7428 if (!NewFD->getReturnType()->isVoidType()) { 7429 Diag(D.getIdentifierLoc(), 7430 diag::err_expected_kernel_void_return_type); 7431 D.setInvalidType(); 7432 } 7433 7434 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7435 for (auto Param : NewFD->params()) 7436 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7437 } 7438 7439 MarkUnusedFileScopedDecl(NewFD); 7440 7441 if (getLangOpts().CUDA) 7442 if (IdentifierInfo *II = NewFD->getIdentifier()) 7443 if (!NewFD->isInvalidDecl() && 7444 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7445 if (II->isStr("cudaConfigureCall")) { 7446 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7447 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7448 7449 Context.setcudaConfigureCallDecl(NewFD); 7450 } 7451 } 7452 7453 // Here we have an function template explicit specialization at class scope. 7454 // The actually specialization will be postponed to template instatiation 7455 // time via the ClassScopeFunctionSpecializationDecl node. 7456 if (isDependentClassScopeExplicitSpecialization) { 7457 ClassScopeFunctionSpecializationDecl *NewSpec = 7458 ClassScopeFunctionSpecializationDecl::Create( 7459 Context, CurContext, SourceLocation(), 7460 cast<CXXMethodDecl>(NewFD), 7461 HasExplicitTemplateArgs, TemplateArgs); 7462 CurContext->addDecl(NewSpec); 7463 AddToScope = false; 7464 } 7465 7466 return NewFD; 7467 } 7468 7469 /// \brief Perform semantic checking of a new function declaration. 7470 /// 7471 /// Performs semantic analysis of the new function declaration 7472 /// NewFD. This routine performs all semantic checking that does not 7473 /// require the actual declarator involved in the declaration, and is 7474 /// used both for the declaration of functions as they are parsed 7475 /// (called via ActOnDeclarator) and for the declaration of functions 7476 /// that have been instantiated via C++ template instantiation (called 7477 /// via InstantiateDecl). 7478 /// 7479 /// \param IsExplicitSpecialization whether this new function declaration is 7480 /// an explicit specialization of the previous declaration. 7481 /// 7482 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7483 /// 7484 /// \returns true if the function declaration is a redeclaration. 7485 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7486 LookupResult &Previous, 7487 bool IsExplicitSpecialization) { 7488 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7489 "Variably modified return types are not handled here"); 7490 7491 // Determine whether the type of this function should be merged with 7492 // a previous visible declaration. This never happens for functions in C++, 7493 // and always happens in C if the previous declaration was visible. 7494 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7495 !Previous.isShadowed(); 7496 7497 // Filter out any non-conflicting previous declarations. 7498 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7499 7500 bool Redeclaration = false; 7501 NamedDecl *OldDecl = 0; 7502 7503 // Merge or overload the declaration with an existing declaration of 7504 // the same name, if appropriate. 7505 if (!Previous.empty()) { 7506 // Determine whether NewFD is an overload of PrevDecl or 7507 // a declaration that requires merging. If it's an overload, 7508 // there's no more work to do here; we'll just add the new 7509 // function to the scope. 7510 if (!AllowOverloadingOfFunction(Previous, Context)) { 7511 NamedDecl *Candidate = Previous.getFoundDecl(); 7512 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7513 Redeclaration = true; 7514 OldDecl = Candidate; 7515 } 7516 } else { 7517 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7518 /*NewIsUsingDecl*/ false)) { 7519 case Ovl_Match: 7520 Redeclaration = true; 7521 break; 7522 7523 case Ovl_NonFunction: 7524 Redeclaration = true; 7525 break; 7526 7527 case Ovl_Overload: 7528 Redeclaration = false; 7529 break; 7530 } 7531 7532 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7533 // If a function name is overloadable in C, then every function 7534 // with that name must be marked "overloadable". 7535 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7536 << Redeclaration << NewFD; 7537 NamedDecl *OverloadedDecl = 0; 7538 if (Redeclaration) 7539 OverloadedDecl = OldDecl; 7540 else if (!Previous.empty()) 7541 OverloadedDecl = Previous.getRepresentativeDecl(); 7542 if (OverloadedDecl) 7543 Diag(OverloadedDecl->getLocation(), 7544 diag::note_attribute_overloadable_prev_overload); 7545 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7546 } 7547 } 7548 } 7549 7550 // Check for a previous extern "C" declaration with this name. 7551 if (!Redeclaration && 7552 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7553 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7554 if (!Previous.empty()) { 7555 // This is an extern "C" declaration with the same name as a previous 7556 // declaration, and thus redeclares that entity... 7557 Redeclaration = true; 7558 OldDecl = Previous.getFoundDecl(); 7559 MergeTypeWithPrevious = false; 7560 7561 // ... except in the presence of __attribute__((overloadable)). 7562 if (OldDecl->hasAttr<OverloadableAttr>()) { 7563 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7564 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7565 << Redeclaration << NewFD; 7566 Diag(Previous.getFoundDecl()->getLocation(), 7567 diag::note_attribute_overloadable_prev_overload); 7568 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7569 } 7570 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7571 Redeclaration = false; 7572 OldDecl = 0; 7573 } 7574 } 7575 } 7576 } 7577 7578 // C++11 [dcl.constexpr]p8: 7579 // A constexpr specifier for a non-static member function that is not 7580 // a constructor declares that member function to be const. 7581 // 7582 // This needs to be delayed until we know whether this is an out-of-line 7583 // definition of a static member function. 7584 // 7585 // This rule is not present in C++1y, so we produce a backwards 7586 // compatibility warning whenever it happens in C++11. 7587 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7588 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7589 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7590 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7591 CXXMethodDecl *OldMD = 0; 7592 if (OldDecl) 7593 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7594 if (!OldMD || !OldMD->isStatic()) { 7595 const FunctionProtoType *FPT = 7596 MD->getType()->castAs<FunctionProtoType>(); 7597 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7598 EPI.TypeQuals |= Qualifiers::Const; 7599 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7600 FPT->getParamTypes(), EPI)); 7601 7602 // Warn that we did this, if we're not performing template instantiation. 7603 // In that case, we'll have warned already when the template was defined. 7604 if (ActiveTemplateInstantiations.empty()) { 7605 SourceLocation AddConstLoc; 7606 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7607 .IgnoreParens().getAs<FunctionTypeLoc>()) 7608 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7609 7610 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7611 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7612 } 7613 } 7614 } 7615 7616 if (Redeclaration) { 7617 // NewFD and OldDecl represent declarations that need to be 7618 // merged. 7619 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7620 NewFD->setInvalidDecl(); 7621 return Redeclaration; 7622 } 7623 7624 Previous.clear(); 7625 Previous.addDecl(OldDecl); 7626 7627 if (FunctionTemplateDecl *OldTemplateDecl 7628 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7629 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7630 FunctionTemplateDecl *NewTemplateDecl 7631 = NewFD->getDescribedFunctionTemplate(); 7632 assert(NewTemplateDecl && "Template/non-template mismatch"); 7633 if (CXXMethodDecl *Method 7634 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7635 Method->setAccess(OldTemplateDecl->getAccess()); 7636 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7637 } 7638 7639 // If this is an explicit specialization of a member that is a function 7640 // template, mark it as a member specialization. 7641 if (IsExplicitSpecialization && 7642 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7643 NewTemplateDecl->setMemberSpecialization(); 7644 assert(OldTemplateDecl->isMemberSpecialization()); 7645 } 7646 7647 } else { 7648 // This needs to happen first so that 'inline' propagates. 7649 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7650 7651 if (isa<CXXMethodDecl>(NewFD)) { 7652 // A valid redeclaration of a C++ method must be out-of-line, 7653 // but (unfortunately) it's not necessarily a definition 7654 // because of templates, which means that the previous 7655 // declaration is not necessarily from the class definition. 7656 7657 // For just setting the access, that doesn't matter. 7658 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7659 NewFD->setAccess(oldMethod->getAccess()); 7660 7661 // Update the key-function state if necessary for this ABI. 7662 if (NewFD->isInlined() && 7663 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7664 // setNonKeyFunction needs to work with the original 7665 // declaration from the class definition, and isVirtual() is 7666 // just faster in that case, so map back to that now. 7667 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7668 if (oldMethod->isVirtual()) { 7669 Context.setNonKeyFunction(oldMethod); 7670 } 7671 } 7672 } 7673 } 7674 } 7675 7676 // Semantic checking for this function declaration (in isolation). 7677 if (getLangOpts().CPlusPlus) { 7678 // C++-specific checks. 7679 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7680 CheckConstructor(Constructor); 7681 } else if (CXXDestructorDecl *Destructor = 7682 dyn_cast<CXXDestructorDecl>(NewFD)) { 7683 CXXRecordDecl *Record = Destructor->getParent(); 7684 QualType ClassType = Context.getTypeDeclType(Record); 7685 7686 // FIXME: Shouldn't we be able to perform this check even when the class 7687 // type is dependent? Both gcc and edg can handle that. 7688 if (!ClassType->isDependentType()) { 7689 DeclarationName Name 7690 = Context.DeclarationNames.getCXXDestructorName( 7691 Context.getCanonicalType(ClassType)); 7692 if (NewFD->getDeclName() != Name) { 7693 Diag(NewFD->getLocation(), diag::err_destructor_name); 7694 NewFD->setInvalidDecl(); 7695 return Redeclaration; 7696 } 7697 } 7698 } else if (CXXConversionDecl *Conversion 7699 = dyn_cast<CXXConversionDecl>(NewFD)) { 7700 ActOnConversionDeclarator(Conversion); 7701 } 7702 7703 // Find any virtual functions that this function overrides. 7704 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7705 if (!Method->isFunctionTemplateSpecialization() && 7706 !Method->getDescribedFunctionTemplate() && 7707 Method->isCanonicalDecl()) { 7708 if (AddOverriddenMethods(Method->getParent(), Method)) { 7709 // If the function was marked as "static", we have a problem. 7710 if (NewFD->getStorageClass() == SC_Static) { 7711 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7712 } 7713 } 7714 } 7715 7716 if (Method->isStatic()) 7717 checkThisInStaticMemberFunctionType(Method); 7718 } 7719 7720 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7721 if (NewFD->isOverloadedOperator() && 7722 CheckOverloadedOperatorDeclaration(NewFD)) { 7723 NewFD->setInvalidDecl(); 7724 return Redeclaration; 7725 } 7726 7727 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7728 if (NewFD->getLiteralIdentifier() && 7729 CheckLiteralOperatorDeclaration(NewFD)) { 7730 NewFD->setInvalidDecl(); 7731 return Redeclaration; 7732 } 7733 7734 // In C++, check default arguments now that we have merged decls. Unless 7735 // the lexical context is the class, because in this case this is done 7736 // during delayed parsing anyway. 7737 if (!CurContext->isRecord()) 7738 CheckCXXDefaultArguments(NewFD); 7739 7740 // If this function declares a builtin function, check the type of this 7741 // declaration against the expected type for the builtin. 7742 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7743 ASTContext::GetBuiltinTypeError Error; 7744 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7745 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7746 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7747 // The type of this function differs from the type of the builtin, 7748 // so forget about the builtin entirely. 7749 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7750 } 7751 } 7752 7753 // If this function is declared as being extern "C", then check to see if 7754 // the function returns a UDT (class, struct, or union type) that is not C 7755 // compatible, and if it does, warn the user. 7756 // But, issue any diagnostic on the first declaration only. 7757 if (NewFD->isExternC() && Previous.empty()) { 7758 QualType R = NewFD->getReturnType(); 7759 if (R->isIncompleteType() && !R->isVoidType()) 7760 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7761 << NewFD << R; 7762 else if (!R.isPODType(Context) && !R->isVoidType() && 7763 !R->isObjCObjectPointerType()) 7764 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7765 } 7766 } 7767 return Redeclaration; 7768 } 7769 7770 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7771 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7772 if (!TSI) 7773 return SourceRange(); 7774 7775 TypeLoc TL = TSI->getTypeLoc(); 7776 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7777 if (!FunctionTL) 7778 return SourceRange(); 7779 7780 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7781 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7782 return ResultTL.getSourceRange(); 7783 7784 return SourceRange(); 7785 } 7786 7787 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7788 // C++11 [basic.start.main]p3: 7789 // A program that [...] declares main to be inline, static or 7790 // constexpr is ill-formed. 7791 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7792 // appear in a declaration of main. 7793 // static main is not an error under C99, but we should warn about it. 7794 // We accept _Noreturn main as an extension. 7795 if (FD->getStorageClass() == SC_Static) 7796 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7797 ? diag::err_static_main : diag::warn_static_main) 7798 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7799 if (FD->isInlineSpecified()) 7800 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7801 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7802 if (DS.isNoreturnSpecified()) { 7803 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7804 SourceRange NoreturnRange(NoreturnLoc, 7805 PP.getLocForEndOfToken(NoreturnLoc)); 7806 Diag(NoreturnLoc, diag::ext_noreturn_main); 7807 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7808 << FixItHint::CreateRemoval(NoreturnRange); 7809 } 7810 if (FD->isConstexpr()) { 7811 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7812 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7813 FD->setConstexpr(false); 7814 } 7815 7816 if (getLangOpts().OpenCL) { 7817 Diag(FD->getLocation(), diag::err_opencl_no_main) 7818 << FD->hasAttr<OpenCLKernelAttr>(); 7819 FD->setInvalidDecl(); 7820 return; 7821 } 7822 7823 QualType T = FD->getType(); 7824 assert(T->isFunctionType() && "function decl is not of function type"); 7825 const FunctionType* FT = T->castAs<FunctionType>(); 7826 7827 // All the standards say that main() should should return 'int'. 7828 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7829 // In C and C++, main magically returns 0 if you fall off the end; 7830 // set the flag which tells us that. 7831 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7832 FD->setHasImplicitReturnZero(true); 7833 7834 // In C with GNU extensions we allow main() to have non-integer return 7835 // type, but we should warn about the extension, and we disable the 7836 // implicit-return-zero rule. 7837 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7838 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7839 7840 SourceRange ResultRange = getResultSourceRange(FD); 7841 if (ResultRange.isValid()) 7842 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7843 << FixItHint::CreateReplacement(ResultRange, "int"); 7844 7845 // Otherwise, this is just a flat-out error. 7846 } else { 7847 SourceRange ResultRange = getResultSourceRange(FD); 7848 if (ResultRange.isValid()) 7849 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7850 << FixItHint::CreateReplacement(ResultRange, "int"); 7851 else 7852 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7853 7854 FD->setInvalidDecl(true); 7855 } 7856 7857 // Treat protoless main() as nullary. 7858 if (isa<FunctionNoProtoType>(FT)) return; 7859 7860 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7861 unsigned nparams = FTP->getNumParams(); 7862 assert(FD->getNumParams() == nparams); 7863 7864 bool HasExtraParameters = (nparams > 3); 7865 7866 // Darwin passes an undocumented fourth argument of type char**. If 7867 // other platforms start sprouting these, the logic below will start 7868 // getting shifty. 7869 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7870 HasExtraParameters = false; 7871 7872 if (HasExtraParameters) { 7873 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7874 FD->setInvalidDecl(true); 7875 nparams = 3; 7876 } 7877 7878 // FIXME: a lot of the following diagnostics would be improved 7879 // if we had some location information about types. 7880 7881 QualType CharPP = 7882 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7883 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7884 7885 for (unsigned i = 0; i < nparams; ++i) { 7886 QualType AT = FTP->getParamType(i); 7887 7888 bool mismatch = true; 7889 7890 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7891 mismatch = false; 7892 else if (Expected[i] == CharPP) { 7893 // As an extension, the following forms are okay: 7894 // char const ** 7895 // char const * const * 7896 // char * const * 7897 7898 QualifierCollector qs; 7899 const PointerType* PT; 7900 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7901 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7902 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7903 Context.CharTy)) { 7904 qs.removeConst(); 7905 mismatch = !qs.empty(); 7906 } 7907 } 7908 7909 if (mismatch) { 7910 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7911 // TODO: suggest replacing given type with expected type 7912 FD->setInvalidDecl(true); 7913 } 7914 } 7915 7916 if (nparams == 1 && !FD->isInvalidDecl()) { 7917 Diag(FD->getLocation(), diag::warn_main_one_arg); 7918 } 7919 7920 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7921 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7922 FD->setInvalidDecl(); 7923 } 7924 } 7925 7926 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7927 QualType T = FD->getType(); 7928 assert(T->isFunctionType() && "function decl is not of function type"); 7929 const FunctionType *FT = T->castAs<FunctionType>(); 7930 7931 // Set an implicit return of 'zero' if the function can return some integral, 7932 // enumeration, pointer or nullptr type. 7933 if (FT->getReturnType()->isIntegralOrEnumerationType() || 7934 FT->getReturnType()->isAnyPointerType() || 7935 FT->getReturnType()->isNullPtrType()) 7936 // DllMain is exempt because a return value of zero means it failed. 7937 if (FD->getName() != "DllMain") 7938 FD->setHasImplicitReturnZero(true); 7939 7940 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7941 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7942 FD->setInvalidDecl(); 7943 } 7944 } 7945 7946 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7947 // FIXME: Need strict checking. In C89, we need to check for 7948 // any assignment, increment, decrement, function-calls, or 7949 // commas outside of a sizeof. In C99, it's the same list, 7950 // except that the aforementioned are allowed in unevaluated 7951 // expressions. Everything else falls under the 7952 // "may accept other forms of constant expressions" exception. 7953 // (We never end up here for C++, so the constant expression 7954 // rules there don't matter.) 7955 if (Init->isConstantInitializer(Context, false)) 7956 return false; 7957 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7958 << Init->getSourceRange(); 7959 return true; 7960 } 7961 7962 namespace { 7963 // Visits an initialization expression to see if OrigDecl is evaluated in 7964 // its own initialization and throws a warning if it does. 7965 class SelfReferenceChecker 7966 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7967 Sema &S; 7968 Decl *OrigDecl; 7969 bool isRecordType; 7970 bool isPODType; 7971 bool isReferenceType; 7972 7973 public: 7974 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7975 7976 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7977 S(S), OrigDecl(OrigDecl) { 7978 isPODType = false; 7979 isRecordType = false; 7980 isReferenceType = false; 7981 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7982 isPODType = VD->getType().isPODType(S.Context); 7983 isRecordType = VD->getType()->isRecordType(); 7984 isReferenceType = VD->getType()->isReferenceType(); 7985 } 7986 } 7987 7988 // For most expressions, the cast is directly above the DeclRefExpr. 7989 // For conditional operators, the cast can be outside the conditional 7990 // operator if both expressions are DeclRefExpr's. 7991 void HandleValue(Expr *E) { 7992 if (isReferenceType) 7993 return; 7994 E = E->IgnoreParenImpCasts(); 7995 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7996 HandleDeclRefExpr(DRE); 7997 return; 7998 } 7999 8000 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8001 HandleValue(CO->getTrueExpr()); 8002 HandleValue(CO->getFalseExpr()); 8003 return; 8004 } 8005 8006 if (isa<MemberExpr>(E)) { 8007 Expr *Base = E->IgnoreParenImpCasts(); 8008 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8009 // Check for static member variables and don't warn on them. 8010 if (!isa<FieldDecl>(ME->getMemberDecl())) 8011 return; 8012 Base = ME->getBase()->IgnoreParenImpCasts(); 8013 } 8014 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8015 HandleDeclRefExpr(DRE); 8016 return; 8017 } 8018 } 8019 8020 // Reference types are handled here since all uses of references are 8021 // bad, not just r-value uses. 8022 void VisitDeclRefExpr(DeclRefExpr *E) { 8023 if (isReferenceType) 8024 HandleDeclRefExpr(E); 8025 } 8026 8027 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8028 if (E->getCastKind() == CK_LValueToRValue || 8029 (isRecordType && E->getCastKind() == CK_NoOp)) 8030 HandleValue(E->getSubExpr()); 8031 8032 Inherited::VisitImplicitCastExpr(E); 8033 } 8034 8035 void VisitMemberExpr(MemberExpr *E) { 8036 // Don't warn on arrays since they can be treated as pointers. 8037 if (E->getType()->canDecayToPointerType()) return; 8038 8039 // Warn when a non-static method call is followed by non-static member 8040 // field accesses, which is followed by a DeclRefExpr. 8041 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8042 bool Warn = (MD && !MD->isStatic()); 8043 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8044 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8045 if (!isa<FieldDecl>(ME->getMemberDecl())) 8046 Warn = false; 8047 Base = ME->getBase()->IgnoreParenImpCasts(); 8048 } 8049 8050 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8051 if (Warn) 8052 HandleDeclRefExpr(DRE); 8053 return; 8054 } 8055 8056 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8057 // Visit that expression. 8058 Visit(Base); 8059 } 8060 8061 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8062 if (E->getNumArgs() > 0) 8063 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 8064 HandleDeclRefExpr(DRE); 8065 8066 Inherited::VisitCXXOperatorCallExpr(E); 8067 } 8068 8069 void VisitUnaryOperator(UnaryOperator *E) { 8070 // For POD record types, addresses of its own members are well-defined. 8071 if (E->getOpcode() == UO_AddrOf && isRecordType && 8072 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8073 if (!isPODType) 8074 HandleValue(E->getSubExpr()); 8075 return; 8076 } 8077 Inherited::VisitUnaryOperator(E); 8078 } 8079 8080 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8081 8082 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8083 Decl* ReferenceDecl = DRE->getDecl(); 8084 if (OrigDecl != ReferenceDecl) return; 8085 unsigned diag; 8086 if (isReferenceType) { 8087 diag = diag::warn_uninit_self_reference_in_reference_init; 8088 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8089 diag = diag::warn_static_self_reference_in_init; 8090 } else { 8091 diag = diag::warn_uninit_self_reference_in_init; 8092 } 8093 8094 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8095 S.PDiag(diag) 8096 << DRE->getNameInfo().getName() 8097 << OrigDecl->getLocation() 8098 << DRE->getSourceRange()); 8099 } 8100 }; 8101 8102 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8103 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8104 bool DirectInit) { 8105 // Parameters arguments are occassionially constructed with itself, 8106 // for instance, in recursive functions. Skip them. 8107 if (isa<ParmVarDecl>(OrigDecl)) 8108 return; 8109 8110 E = E->IgnoreParens(); 8111 8112 // Skip checking T a = a where T is not a record or reference type. 8113 // Doing so is a way to silence uninitialized warnings. 8114 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8115 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8116 if (ICE->getCastKind() == CK_LValueToRValue) 8117 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8118 if (DRE->getDecl() == OrigDecl) 8119 return; 8120 8121 SelfReferenceChecker(S, OrigDecl).Visit(E); 8122 } 8123 } 8124 8125 /// AddInitializerToDecl - Adds the initializer Init to the 8126 /// declaration dcl. If DirectInit is true, this is C++ direct 8127 /// initialization rather than copy initialization. 8128 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8129 bool DirectInit, bool TypeMayContainAuto) { 8130 // If there is no declaration, there was an error parsing it. Just ignore 8131 // the initializer. 8132 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8133 return; 8134 8135 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8136 // With declarators parsed the way they are, the parser cannot 8137 // distinguish between a normal initializer and a pure-specifier. 8138 // Thus this grotesque test. 8139 IntegerLiteral *IL; 8140 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8141 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8142 CheckPureMethod(Method, Init->getSourceRange()); 8143 else { 8144 Diag(Method->getLocation(), diag::err_member_function_initialization) 8145 << Method->getDeclName() << Init->getSourceRange(); 8146 Method->setInvalidDecl(); 8147 } 8148 return; 8149 } 8150 8151 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8152 if (!VDecl) { 8153 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8154 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8155 RealDecl->setInvalidDecl(); 8156 return; 8157 } 8158 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8159 8160 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8161 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8162 Expr *DeduceInit = Init; 8163 // Initializer could be a C++ direct-initializer. Deduction only works if it 8164 // contains exactly one expression. 8165 if (CXXDirectInit) { 8166 if (CXXDirectInit->getNumExprs() == 0) { 8167 // It isn't possible to write this directly, but it is possible to 8168 // end up in this situation with "auto x(some_pack...);" 8169 Diag(CXXDirectInit->getLocStart(), 8170 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8171 : diag::err_auto_var_init_no_expression) 8172 << VDecl->getDeclName() << VDecl->getType() 8173 << VDecl->getSourceRange(); 8174 RealDecl->setInvalidDecl(); 8175 return; 8176 } else if (CXXDirectInit->getNumExprs() > 1) { 8177 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8178 VDecl->isInitCapture() 8179 ? diag::err_init_capture_multiple_expressions 8180 : diag::err_auto_var_init_multiple_expressions) 8181 << VDecl->getDeclName() << VDecl->getType() 8182 << VDecl->getSourceRange(); 8183 RealDecl->setInvalidDecl(); 8184 return; 8185 } else { 8186 DeduceInit = CXXDirectInit->getExpr(0); 8187 if (isa<InitListExpr>(DeduceInit)) 8188 Diag(CXXDirectInit->getLocStart(), 8189 diag::err_auto_var_init_paren_braces) 8190 << VDecl->getDeclName() << VDecl->getType() 8191 << VDecl->getSourceRange(); 8192 } 8193 } 8194 8195 // Expressions default to 'id' when we're in a debugger. 8196 bool DefaultedToAuto = false; 8197 if (getLangOpts().DebuggerCastResultToId && 8198 Init->getType() == Context.UnknownAnyTy) { 8199 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8200 if (Result.isInvalid()) { 8201 VDecl->setInvalidDecl(); 8202 return; 8203 } 8204 Init = Result.take(); 8205 DefaultedToAuto = true; 8206 } 8207 8208 QualType DeducedType; 8209 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8210 DAR_Failed) 8211 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8212 if (DeducedType.isNull()) { 8213 RealDecl->setInvalidDecl(); 8214 return; 8215 } 8216 VDecl->setType(DeducedType); 8217 assert(VDecl->isLinkageValid()); 8218 8219 // In ARC, infer lifetime. 8220 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8221 VDecl->setInvalidDecl(); 8222 8223 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8224 // 'id' instead of a specific object type prevents most of our usual checks. 8225 // We only want to warn outside of template instantiations, though: 8226 // inside a template, the 'id' could have come from a parameter. 8227 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8228 DeducedType->isObjCIdType()) { 8229 SourceLocation Loc = 8230 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8231 Diag(Loc, diag::warn_auto_var_is_id) 8232 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8233 } 8234 8235 // If this is a redeclaration, check that the type we just deduced matches 8236 // the previously declared type. 8237 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8238 // We never need to merge the type, because we cannot form an incomplete 8239 // array of auto, nor deduce such a type. 8240 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8241 } 8242 8243 // Check the deduced type is valid for a variable declaration. 8244 CheckVariableDeclarationType(VDecl); 8245 if (VDecl->isInvalidDecl()) 8246 return; 8247 } 8248 8249 // dllimport cannot be used on variable definitions. 8250 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8251 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8252 VDecl->setInvalidDecl(); 8253 return; 8254 } 8255 8256 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8257 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8258 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8259 VDecl->setInvalidDecl(); 8260 return; 8261 } 8262 8263 if (!VDecl->getType()->isDependentType()) { 8264 // A definition must end up with a complete type, which means it must be 8265 // complete with the restriction that an array type might be completed by 8266 // the initializer; note that later code assumes this restriction. 8267 QualType BaseDeclType = VDecl->getType(); 8268 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8269 BaseDeclType = Array->getElementType(); 8270 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8271 diag::err_typecheck_decl_incomplete_type)) { 8272 RealDecl->setInvalidDecl(); 8273 return; 8274 } 8275 8276 // The variable can not have an abstract class type. 8277 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8278 diag::err_abstract_type_in_decl, 8279 AbstractVariableType)) 8280 VDecl->setInvalidDecl(); 8281 } 8282 8283 const VarDecl *Def; 8284 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8285 Diag(VDecl->getLocation(), diag::err_redefinition) 8286 << VDecl->getDeclName(); 8287 Diag(Def->getLocation(), diag::note_previous_definition); 8288 VDecl->setInvalidDecl(); 8289 return; 8290 } 8291 8292 const VarDecl* PrevInit = 0; 8293 if (getLangOpts().CPlusPlus) { 8294 // C++ [class.static.data]p4 8295 // If a static data member is of const integral or const 8296 // enumeration type, its declaration in the class definition can 8297 // specify a constant-initializer which shall be an integral 8298 // constant expression (5.19). In that case, the member can appear 8299 // in integral constant expressions. The member shall still be 8300 // defined in a namespace scope if it is used in the program and the 8301 // namespace scope definition shall not contain an initializer. 8302 // 8303 // We already performed a redefinition check above, but for static 8304 // data members we also need to check whether there was an in-class 8305 // declaration with an initializer. 8306 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8307 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8308 << VDecl->getDeclName(); 8309 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8310 return; 8311 } 8312 8313 if (VDecl->hasLocalStorage()) 8314 getCurFunction()->setHasBranchProtectedScope(); 8315 8316 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8317 VDecl->setInvalidDecl(); 8318 return; 8319 } 8320 } 8321 8322 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8323 // a kernel function cannot be initialized." 8324 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8325 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8326 VDecl->setInvalidDecl(); 8327 return; 8328 } 8329 8330 // Get the decls type and save a reference for later, since 8331 // CheckInitializerTypes may change it. 8332 QualType DclT = VDecl->getType(), SavT = DclT; 8333 8334 // Expressions default to 'id' when we're in a debugger 8335 // and we are assigning it to a variable of Objective-C pointer type. 8336 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8337 Init->getType() == Context.UnknownAnyTy) { 8338 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8339 if (Result.isInvalid()) { 8340 VDecl->setInvalidDecl(); 8341 return; 8342 } 8343 Init = Result.take(); 8344 } 8345 8346 // Perform the initialization. 8347 if (!VDecl->isInvalidDecl()) { 8348 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8349 InitializationKind Kind 8350 = DirectInit ? 8351 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8352 Init->getLocStart(), 8353 Init->getLocEnd()) 8354 : InitializationKind::CreateDirectList( 8355 VDecl->getLocation()) 8356 : InitializationKind::CreateCopy(VDecl->getLocation(), 8357 Init->getLocStart()); 8358 8359 MultiExprArg Args = Init; 8360 if (CXXDirectInit) 8361 Args = MultiExprArg(CXXDirectInit->getExprs(), 8362 CXXDirectInit->getNumExprs()); 8363 8364 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8365 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8366 if (Result.isInvalid()) { 8367 VDecl->setInvalidDecl(); 8368 return; 8369 } 8370 8371 Init = Result.takeAs<Expr>(); 8372 } 8373 8374 // Check for self-references within variable initializers. 8375 // Variables declared within a function/method body (except for references) 8376 // are handled by a dataflow analysis. 8377 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8378 VDecl->getType()->isReferenceType()) { 8379 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8380 } 8381 8382 // If the type changed, it means we had an incomplete type that was 8383 // completed by the initializer. For example: 8384 // int ary[] = { 1, 3, 5 }; 8385 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8386 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8387 VDecl->setType(DclT); 8388 8389 if (!VDecl->isInvalidDecl()) { 8390 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8391 8392 if (VDecl->hasAttr<BlocksAttr>()) 8393 checkRetainCycles(VDecl, Init); 8394 8395 // It is safe to assign a weak reference into a strong variable. 8396 // Although this code can still have problems: 8397 // id x = self.weakProp; 8398 // id y = self.weakProp; 8399 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8400 // paths through the function. This should be revisited if 8401 // -Wrepeated-use-of-weak is made flow-sensitive. 8402 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8403 DiagnosticsEngine::Level Level = 8404 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8405 Init->getLocStart()); 8406 if (Level != DiagnosticsEngine::Ignored) 8407 getCurFunction()->markSafeWeakUse(Init); 8408 } 8409 } 8410 8411 // The initialization is usually a full-expression. 8412 // 8413 // FIXME: If this is a braced initialization of an aggregate, it is not 8414 // an expression, and each individual field initializer is a separate 8415 // full-expression. For instance, in: 8416 // 8417 // struct Temp { ~Temp(); }; 8418 // struct S { S(Temp); }; 8419 // struct T { S a, b; } t = { Temp(), Temp() } 8420 // 8421 // we should destroy the first Temp before constructing the second. 8422 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8423 false, 8424 VDecl->isConstexpr()); 8425 if (Result.isInvalid()) { 8426 VDecl->setInvalidDecl(); 8427 return; 8428 } 8429 Init = Result.take(); 8430 8431 // Attach the initializer to the decl. 8432 VDecl->setInit(Init); 8433 8434 if (VDecl->isLocalVarDecl()) { 8435 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8436 // static storage duration shall be constant expressions or string literals. 8437 // C++ does not have this restriction. 8438 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8439 if (VDecl->getStorageClass() == SC_Static) 8440 CheckForConstantInitializer(Init, DclT); 8441 // C89 is stricter than C99 for non-static aggregate types. 8442 // C89 6.5.7p3: All the expressions [...] in an initializer list 8443 // for an object that has aggregate or union type shall be 8444 // constant expressions. 8445 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8446 isa<InitListExpr>(Init) && 8447 !Init->isConstantInitializer(Context, false)) 8448 Diag(Init->getExprLoc(), 8449 diag::ext_aggregate_init_not_constant) 8450 << Init->getSourceRange(); 8451 } 8452 } else if (VDecl->isStaticDataMember() && 8453 VDecl->getLexicalDeclContext()->isRecord()) { 8454 // This is an in-class initialization for a static data member, e.g., 8455 // 8456 // struct S { 8457 // static const int value = 17; 8458 // }; 8459 8460 // C++ [class.mem]p4: 8461 // A member-declarator can contain a constant-initializer only 8462 // if it declares a static member (9.4) of const integral or 8463 // const enumeration type, see 9.4.2. 8464 // 8465 // C++11 [class.static.data]p3: 8466 // If a non-volatile const static data member is of integral or 8467 // enumeration type, its declaration in the class definition can 8468 // specify a brace-or-equal-initializer in which every initalizer-clause 8469 // that is an assignment-expression is a constant expression. A static 8470 // data member of literal type can be declared in the class definition 8471 // with the constexpr specifier; if so, its declaration shall specify a 8472 // brace-or-equal-initializer in which every initializer-clause that is 8473 // an assignment-expression is a constant expression. 8474 8475 // Do nothing on dependent types. 8476 if (DclT->isDependentType()) { 8477 8478 // Allow any 'static constexpr' members, whether or not they are of literal 8479 // type. We separately check that every constexpr variable is of literal 8480 // type. 8481 } else if (VDecl->isConstexpr()) { 8482 8483 // Require constness. 8484 } else if (!DclT.isConstQualified()) { 8485 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8486 << Init->getSourceRange(); 8487 VDecl->setInvalidDecl(); 8488 8489 // We allow integer constant expressions in all cases. 8490 } else if (DclT->isIntegralOrEnumerationType()) { 8491 // Check whether the expression is a constant expression. 8492 SourceLocation Loc; 8493 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8494 // In C++11, a non-constexpr const static data member with an 8495 // in-class initializer cannot be volatile. 8496 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8497 else if (Init->isValueDependent()) 8498 ; // Nothing to check. 8499 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8500 ; // Ok, it's an ICE! 8501 else if (Init->isEvaluatable(Context)) { 8502 // If we can constant fold the initializer through heroics, accept it, 8503 // but report this as a use of an extension for -pedantic. 8504 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8505 << Init->getSourceRange(); 8506 } else { 8507 // Otherwise, this is some crazy unknown case. Report the issue at the 8508 // location provided by the isIntegerConstantExpr failed check. 8509 Diag(Loc, diag::err_in_class_initializer_non_constant) 8510 << Init->getSourceRange(); 8511 VDecl->setInvalidDecl(); 8512 } 8513 8514 // We allow foldable floating-point constants as an extension. 8515 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8516 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8517 // it anyway and provide a fixit to add the 'constexpr'. 8518 if (getLangOpts().CPlusPlus11) { 8519 Diag(VDecl->getLocation(), 8520 diag::ext_in_class_initializer_float_type_cxx11) 8521 << DclT << Init->getSourceRange(); 8522 Diag(VDecl->getLocStart(), 8523 diag::note_in_class_initializer_float_type_cxx11) 8524 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8525 } else { 8526 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8527 << DclT << Init->getSourceRange(); 8528 8529 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8530 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8531 << Init->getSourceRange(); 8532 VDecl->setInvalidDecl(); 8533 } 8534 } 8535 8536 // Suggest adding 'constexpr' in C++11 for literal types. 8537 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8538 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8539 << DclT << Init->getSourceRange() 8540 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8541 VDecl->setConstexpr(true); 8542 8543 } else { 8544 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8545 << DclT << Init->getSourceRange(); 8546 VDecl->setInvalidDecl(); 8547 } 8548 } else if (VDecl->isFileVarDecl()) { 8549 if (VDecl->getStorageClass() == SC_Extern && 8550 (!getLangOpts().CPlusPlus || 8551 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8552 VDecl->isExternC())) && 8553 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8554 Diag(VDecl->getLocation(), diag::warn_extern_init); 8555 8556 // C99 6.7.8p4. All file scoped initializers need to be constant. 8557 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8558 CheckForConstantInitializer(Init, DclT); 8559 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8560 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8561 !Init->isValueDependent() && !VDecl->isConstexpr() && 8562 !Init->isConstantInitializer( 8563 Context, VDecl->getType()->isReferenceType())) { 8564 // GNU C++98 edits for __thread, [basic.start.init]p4: 8565 // An object of thread storage duration shall not require dynamic 8566 // initialization. 8567 // FIXME: Need strict checking here. 8568 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8569 if (getLangOpts().CPlusPlus11) 8570 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8571 } 8572 } 8573 8574 // We will represent direct-initialization similarly to copy-initialization: 8575 // int x(1); -as-> int x = 1; 8576 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8577 // 8578 // Clients that want to distinguish between the two forms, can check for 8579 // direct initializer using VarDecl::getInitStyle(). 8580 // A major benefit is that clients that don't particularly care about which 8581 // exactly form was it (like the CodeGen) can handle both cases without 8582 // special case code. 8583 8584 // C++ 8.5p11: 8585 // The form of initialization (using parentheses or '=') is generally 8586 // insignificant, but does matter when the entity being initialized has a 8587 // class type. 8588 if (CXXDirectInit) { 8589 assert(DirectInit && "Call-style initializer must be direct init."); 8590 VDecl->setInitStyle(VarDecl::CallInit); 8591 } else if (DirectInit) { 8592 // This must be list-initialization. No other way is direct-initialization. 8593 VDecl->setInitStyle(VarDecl::ListInit); 8594 } 8595 8596 CheckCompleteVariableDeclaration(VDecl); 8597 } 8598 8599 /// ActOnInitializerError - Given that there was an error parsing an 8600 /// initializer for the given declaration, try to return to some form 8601 /// of sanity. 8602 void Sema::ActOnInitializerError(Decl *D) { 8603 // Our main concern here is re-establishing invariants like "a 8604 // variable's type is either dependent or complete". 8605 if (!D || D->isInvalidDecl()) return; 8606 8607 VarDecl *VD = dyn_cast<VarDecl>(D); 8608 if (!VD) return; 8609 8610 // Auto types are meaningless if we can't make sense of the initializer. 8611 if (ParsingInitForAutoVars.count(D)) { 8612 D->setInvalidDecl(); 8613 return; 8614 } 8615 8616 QualType Ty = VD->getType(); 8617 if (Ty->isDependentType()) return; 8618 8619 // Require a complete type. 8620 if (RequireCompleteType(VD->getLocation(), 8621 Context.getBaseElementType(Ty), 8622 diag::err_typecheck_decl_incomplete_type)) { 8623 VD->setInvalidDecl(); 8624 return; 8625 } 8626 8627 // Require an abstract type. 8628 if (RequireNonAbstractType(VD->getLocation(), Ty, 8629 diag::err_abstract_type_in_decl, 8630 AbstractVariableType)) { 8631 VD->setInvalidDecl(); 8632 return; 8633 } 8634 8635 // Don't bother complaining about constructors or destructors, 8636 // though. 8637 } 8638 8639 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8640 bool TypeMayContainAuto) { 8641 // If there is no declaration, there was an error parsing it. Just ignore it. 8642 if (RealDecl == 0) 8643 return; 8644 8645 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8646 QualType Type = Var->getType(); 8647 8648 // C++11 [dcl.spec.auto]p3 8649 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8650 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8651 << Var->getDeclName() << Type; 8652 Var->setInvalidDecl(); 8653 return; 8654 } 8655 8656 // C++11 [class.static.data]p3: A static data member can be declared with 8657 // the constexpr specifier; if so, its declaration shall specify 8658 // a brace-or-equal-initializer. 8659 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8660 // the definition of a variable [...] or the declaration of a static data 8661 // member. 8662 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8663 if (Var->isStaticDataMember()) 8664 Diag(Var->getLocation(), 8665 diag::err_constexpr_static_mem_var_requires_init) 8666 << Var->getDeclName(); 8667 else 8668 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8669 Var->setInvalidDecl(); 8670 return; 8671 } 8672 8673 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8674 // be initialized. 8675 if (!Var->isInvalidDecl() && 8676 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8677 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8678 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 8679 Var->setInvalidDecl(); 8680 return; 8681 } 8682 8683 switch (Var->isThisDeclarationADefinition()) { 8684 case VarDecl::Definition: 8685 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8686 break; 8687 8688 // We have an out-of-line definition of a static data member 8689 // that has an in-class initializer, so we type-check this like 8690 // a declaration. 8691 // 8692 // Fall through 8693 8694 case VarDecl::DeclarationOnly: 8695 // It's only a declaration. 8696 8697 // Block scope. C99 6.7p7: If an identifier for an object is 8698 // declared with no linkage (C99 6.2.2p6), the type for the 8699 // object shall be complete. 8700 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8701 !Var->hasLinkage() && !Var->isInvalidDecl() && 8702 RequireCompleteType(Var->getLocation(), Type, 8703 diag::err_typecheck_decl_incomplete_type)) 8704 Var->setInvalidDecl(); 8705 8706 // Make sure that the type is not abstract. 8707 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8708 RequireNonAbstractType(Var->getLocation(), Type, 8709 diag::err_abstract_type_in_decl, 8710 AbstractVariableType)) 8711 Var->setInvalidDecl(); 8712 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8713 Var->getStorageClass() == SC_PrivateExtern) { 8714 Diag(Var->getLocation(), diag::warn_private_extern); 8715 Diag(Var->getLocation(), diag::note_private_extern); 8716 } 8717 8718 return; 8719 8720 case VarDecl::TentativeDefinition: 8721 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8722 // object that has file scope without an initializer, and without a 8723 // storage-class specifier or with the storage-class specifier "static", 8724 // constitutes a tentative definition. Note: A tentative definition with 8725 // external linkage is valid (C99 6.2.2p5). 8726 if (!Var->isInvalidDecl()) { 8727 if (const IncompleteArrayType *ArrayT 8728 = Context.getAsIncompleteArrayType(Type)) { 8729 if (RequireCompleteType(Var->getLocation(), 8730 ArrayT->getElementType(), 8731 diag::err_illegal_decl_array_incomplete_type)) 8732 Var->setInvalidDecl(); 8733 } else if (Var->getStorageClass() == SC_Static) { 8734 // C99 6.9.2p3: If the declaration of an identifier for an object is 8735 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8736 // declared type shall not be an incomplete type. 8737 // NOTE: code such as the following 8738 // static struct s; 8739 // struct s { int a; }; 8740 // is accepted by gcc. Hence here we issue a warning instead of 8741 // an error and we do not invalidate the static declaration. 8742 // NOTE: to avoid multiple warnings, only check the first declaration. 8743 if (Var->isFirstDecl()) 8744 RequireCompleteType(Var->getLocation(), Type, 8745 diag::ext_typecheck_decl_incomplete_type); 8746 } 8747 } 8748 8749 // Record the tentative definition; we're done. 8750 if (!Var->isInvalidDecl()) 8751 TentativeDefinitions.push_back(Var); 8752 return; 8753 } 8754 8755 // Provide a specific diagnostic for uninitialized variable 8756 // definitions with incomplete array type. 8757 if (Type->isIncompleteArrayType()) { 8758 Diag(Var->getLocation(), 8759 diag::err_typecheck_incomplete_array_needs_initializer); 8760 Var->setInvalidDecl(); 8761 return; 8762 } 8763 8764 // Provide a specific diagnostic for uninitialized variable 8765 // definitions with reference type. 8766 if (Type->isReferenceType()) { 8767 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8768 << Var->getDeclName() 8769 << SourceRange(Var->getLocation(), Var->getLocation()); 8770 Var->setInvalidDecl(); 8771 return; 8772 } 8773 8774 // Do not attempt to type-check the default initializer for a 8775 // variable with dependent type. 8776 if (Type->isDependentType()) 8777 return; 8778 8779 if (Var->isInvalidDecl()) 8780 return; 8781 8782 if (RequireCompleteType(Var->getLocation(), 8783 Context.getBaseElementType(Type), 8784 diag::err_typecheck_decl_incomplete_type)) { 8785 Var->setInvalidDecl(); 8786 return; 8787 } 8788 8789 // The variable can not have an abstract class type. 8790 if (RequireNonAbstractType(Var->getLocation(), Type, 8791 diag::err_abstract_type_in_decl, 8792 AbstractVariableType)) { 8793 Var->setInvalidDecl(); 8794 return; 8795 } 8796 8797 // Check for jumps past the implicit initializer. C++0x 8798 // clarifies that this applies to a "variable with automatic 8799 // storage duration", not a "local variable". 8800 // C++11 [stmt.dcl]p3 8801 // A program that jumps from a point where a variable with automatic 8802 // storage duration is not in scope to a point where it is in scope is 8803 // ill-formed unless the variable has scalar type, class type with a 8804 // trivial default constructor and a trivial destructor, a cv-qualified 8805 // version of one of these types, or an array of one of the preceding 8806 // types and is declared without an initializer. 8807 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8808 if (const RecordType *Record 8809 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8810 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8811 // Mark the function for further checking even if the looser rules of 8812 // C++11 do not require such checks, so that we can diagnose 8813 // incompatibilities with C++98. 8814 if (!CXXRecord->isPOD()) 8815 getCurFunction()->setHasBranchProtectedScope(); 8816 } 8817 } 8818 8819 // C++03 [dcl.init]p9: 8820 // If no initializer is specified for an object, and the 8821 // object is of (possibly cv-qualified) non-POD class type (or 8822 // array thereof), the object shall be default-initialized; if 8823 // the object is of const-qualified type, the underlying class 8824 // type shall have a user-declared default 8825 // constructor. Otherwise, if no initializer is specified for 8826 // a non- static object, the object and its subobjects, if 8827 // any, have an indeterminate initial value); if the object 8828 // or any of its subobjects are of const-qualified type, the 8829 // program is ill-formed. 8830 // C++0x [dcl.init]p11: 8831 // If no initializer is specified for an object, the object is 8832 // default-initialized; [...]. 8833 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8834 InitializationKind Kind 8835 = InitializationKind::CreateDefault(Var->getLocation()); 8836 8837 InitializationSequence InitSeq(*this, Entity, Kind, None); 8838 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8839 if (Init.isInvalid()) 8840 Var->setInvalidDecl(); 8841 else if (Init.get()) { 8842 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8843 // This is important for template substitution. 8844 Var->setInitStyle(VarDecl::CallInit); 8845 } 8846 8847 CheckCompleteVariableDeclaration(Var); 8848 } 8849 } 8850 8851 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8852 VarDecl *VD = dyn_cast<VarDecl>(D); 8853 if (!VD) { 8854 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8855 D->setInvalidDecl(); 8856 return; 8857 } 8858 8859 VD->setCXXForRangeDecl(true); 8860 8861 // for-range-declaration cannot be given a storage class specifier. 8862 int Error = -1; 8863 switch (VD->getStorageClass()) { 8864 case SC_None: 8865 break; 8866 case SC_Extern: 8867 Error = 0; 8868 break; 8869 case SC_Static: 8870 Error = 1; 8871 break; 8872 case SC_PrivateExtern: 8873 Error = 2; 8874 break; 8875 case SC_Auto: 8876 Error = 3; 8877 break; 8878 case SC_Register: 8879 Error = 4; 8880 break; 8881 case SC_OpenCLWorkGroupLocal: 8882 llvm_unreachable("Unexpected storage class"); 8883 } 8884 if (VD->isConstexpr()) 8885 Error = 5; 8886 if (Error != -1) { 8887 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8888 << VD->getDeclName() << Error; 8889 D->setInvalidDecl(); 8890 } 8891 } 8892 8893 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8894 if (var->isInvalidDecl()) return; 8895 8896 // In ARC, don't allow jumps past the implicit initialization of a 8897 // local retaining variable. 8898 if (getLangOpts().ObjCAutoRefCount && 8899 var->hasLocalStorage()) { 8900 switch (var->getType().getObjCLifetime()) { 8901 case Qualifiers::OCL_None: 8902 case Qualifiers::OCL_ExplicitNone: 8903 case Qualifiers::OCL_Autoreleasing: 8904 break; 8905 8906 case Qualifiers::OCL_Weak: 8907 case Qualifiers::OCL_Strong: 8908 getCurFunction()->setHasBranchProtectedScope(); 8909 break; 8910 } 8911 } 8912 8913 // Warn about externally-visible variables being defined without a 8914 // prior declaration. We only want to do this for global 8915 // declarations, but we also specifically need to avoid doing it for 8916 // class members because the linkage of an anonymous class can 8917 // change if it's later given a typedef name. 8918 if (var->isThisDeclarationADefinition() && 8919 var->getDeclContext()->getRedeclContext()->isFileContext() && 8920 var->isExternallyVisible() && var->hasLinkage() && 8921 getDiagnostics().getDiagnosticLevel( 8922 diag::warn_missing_variable_declarations, 8923 var->getLocation())) { 8924 // Find a previous declaration that's not a definition. 8925 VarDecl *prev = var->getPreviousDecl(); 8926 while (prev && prev->isThisDeclarationADefinition()) 8927 prev = prev->getPreviousDecl(); 8928 8929 if (!prev) 8930 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8931 } 8932 8933 if (var->getTLSKind() == VarDecl::TLS_Static && 8934 var->getType().isDestructedType()) { 8935 // GNU C++98 edits for __thread, [basic.start.term]p3: 8936 // The type of an object with thread storage duration shall not 8937 // have a non-trivial destructor. 8938 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8939 if (getLangOpts().CPlusPlus11) 8940 Diag(var->getLocation(), diag::note_use_thread_local); 8941 } 8942 8943 if (var->isThisDeclarationADefinition() && 8944 ActiveTemplateInstantiations.empty()) { 8945 PragmaStack<StringLiteral *> *Stack = nullptr; 8946 int SectionFlags = PSF_Implicit | PSF_Read; 8947 if (var->getType().isConstQualified()) 8948 Stack = &ConstSegStack; 8949 else if (!var->getInit()) { 8950 Stack = &BSSSegStack; 8951 SectionFlags |= PSF_Write; 8952 } else { 8953 Stack = &DataSegStack; 8954 SectionFlags |= PSF_Write; 8955 } 8956 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 8957 var->addAttr( 8958 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8959 Stack->CurrentValue->getString(), 8960 Stack->CurrentPragmaLocation)); 8961 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 8962 if (UnifySection(SA->getName(), SectionFlags, var)) 8963 var->dropAttr<SectionAttr>(); 8964 } 8965 8966 // All the following checks are C++ only. 8967 if (!getLangOpts().CPlusPlus) return; 8968 8969 QualType type = var->getType(); 8970 if (type->isDependentType()) return; 8971 8972 // __block variables might require us to capture a copy-initializer. 8973 if (var->hasAttr<BlocksAttr>()) { 8974 // It's currently invalid to ever have a __block variable with an 8975 // array type; should we diagnose that here? 8976 8977 // Regardless, we don't want to ignore array nesting when 8978 // constructing this copy. 8979 if (type->isStructureOrClassType()) { 8980 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8981 SourceLocation poi = var->getLocation(); 8982 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8983 ExprResult result 8984 = PerformMoveOrCopyInitialization( 8985 InitializedEntity::InitializeBlock(poi, type, false), 8986 var, var->getType(), varRef, /*AllowNRVO=*/true); 8987 if (!result.isInvalid()) { 8988 result = MaybeCreateExprWithCleanups(result); 8989 Expr *init = result.takeAs<Expr>(); 8990 Context.setBlockVarCopyInits(var, init); 8991 } 8992 } 8993 } 8994 8995 Expr *Init = var->getInit(); 8996 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8997 QualType baseType = Context.getBaseElementType(type); 8998 8999 if (!var->getDeclContext()->isDependentContext() && 9000 Init && !Init->isValueDependent()) { 9001 if (IsGlobal && !var->isConstexpr() && 9002 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 9003 var->getLocation()) 9004 != DiagnosticsEngine::Ignored) { 9005 // Warn about globals which don't have a constant initializer. Don't 9006 // warn about globals with a non-trivial destructor because we already 9007 // warned about them. 9008 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9009 if (!(RD && !RD->hasTrivialDestructor()) && 9010 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9011 Diag(var->getLocation(), diag::warn_global_constructor) 9012 << Init->getSourceRange(); 9013 } 9014 9015 if (var->isConstexpr()) { 9016 SmallVector<PartialDiagnosticAt, 8> Notes; 9017 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9018 SourceLocation DiagLoc = var->getLocation(); 9019 // If the note doesn't add any useful information other than a source 9020 // location, fold it into the primary diagnostic. 9021 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9022 diag::note_invalid_subexpr_in_const_expr) { 9023 DiagLoc = Notes[0].first; 9024 Notes.clear(); 9025 } 9026 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9027 << var << Init->getSourceRange(); 9028 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9029 Diag(Notes[I].first, Notes[I].second); 9030 } 9031 } else if (var->isUsableInConstantExpressions(Context)) { 9032 // Check whether the initializer of a const variable of integral or 9033 // enumeration type is an ICE now, since we can't tell whether it was 9034 // initialized by a constant expression if we check later. 9035 var->checkInitIsICE(); 9036 } 9037 } 9038 9039 // Require the destructor. 9040 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9041 FinalizeVarWithDestructor(var, recordType); 9042 } 9043 9044 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9045 /// any semantic actions necessary after any initializer has been attached. 9046 void 9047 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9048 // Note that we are no longer parsing the initializer for this declaration. 9049 ParsingInitForAutoVars.erase(ThisDecl); 9050 9051 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9052 if (!VD) 9053 return; 9054 9055 checkAttributesAfterMerging(*this, *VD); 9056 9057 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9058 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9059 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9060 VD->dropAttr<UsedAttr>(); 9061 } 9062 } 9063 9064 if (!VD->isInvalidDecl() && 9065 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 9066 if (const VarDecl *Def = VD->getDefinition()) { 9067 if (Def->hasAttr<AliasAttr>()) { 9068 Diag(VD->getLocation(), diag::err_tentative_after_alias) 9069 << VD->getDeclName(); 9070 Diag(Def->getLocation(), diag::note_previous_definition); 9071 VD->setInvalidDecl(); 9072 } 9073 } 9074 } 9075 9076 const DeclContext *DC = VD->getDeclContext(); 9077 // If there's a #pragma GCC visibility in scope, and this isn't a class 9078 // member, set the visibility of this variable. 9079 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9080 AddPushedVisibilityAttribute(VD); 9081 9082 // FIXME: Warn on unused templates. 9083 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate()) 9084 MarkUnusedFileScopedDecl(VD); 9085 9086 // Now we have parsed the initializer and can update the table of magic 9087 // tag values. 9088 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9089 !VD->getType()->isIntegralOrEnumerationType()) 9090 return; 9091 9092 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9093 const Expr *MagicValueExpr = VD->getInit(); 9094 if (!MagicValueExpr) { 9095 continue; 9096 } 9097 llvm::APSInt MagicValueInt; 9098 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9099 Diag(I->getRange().getBegin(), 9100 diag::err_type_tag_for_datatype_not_ice) 9101 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9102 continue; 9103 } 9104 if (MagicValueInt.getActiveBits() > 64) { 9105 Diag(I->getRange().getBegin(), 9106 diag::err_type_tag_for_datatype_too_large) 9107 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9108 continue; 9109 } 9110 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9111 RegisterTypeTagForDatatype(I->getArgumentKind(), 9112 MagicValue, 9113 I->getMatchingCType(), 9114 I->getLayoutCompatible(), 9115 I->getMustBeNull()); 9116 } 9117 } 9118 9119 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9120 ArrayRef<Decl *> Group) { 9121 SmallVector<Decl*, 8> Decls; 9122 9123 if (DS.isTypeSpecOwned()) 9124 Decls.push_back(DS.getRepAsDecl()); 9125 9126 DeclaratorDecl *FirstDeclaratorInGroup = 0; 9127 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9128 if (Decl *D = Group[i]) { 9129 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9130 if (!FirstDeclaratorInGroup) 9131 FirstDeclaratorInGroup = DD; 9132 Decls.push_back(D); 9133 } 9134 9135 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9136 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9137 HandleTagNumbering(*this, Tag, S); 9138 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9139 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9140 } 9141 } 9142 9143 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9144 } 9145 9146 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9147 /// group, performing any necessary semantic checking. 9148 Sema::DeclGroupPtrTy 9149 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 9150 bool TypeMayContainAuto) { 9151 // C++0x [dcl.spec.auto]p7: 9152 // If the type deduced for the template parameter U is not the same in each 9153 // deduction, the program is ill-formed. 9154 // FIXME: When initializer-list support is added, a distinction is needed 9155 // between the deduced type U and the deduced type which 'auto' stands for. 9156 // auto a = 0, b = { 1, 2, 3 }; 9157 // is legal because the deduced type U is 'int' in both cases. 9158 if (TypeMayContainAuto && Group.size() > 1) { 9159 QualType Deduced; 9160 CanQualType DeducedCanon; 9161 VarDecl *DeducedDecl = 0; 9162 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9163 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9164 AutoType *AT = D->getType()->getContainedAutoType(); 9165 // Don't reissue diagnostics when instantiating a template. 9166 if (AT && D->isInvalidDecl()) 9167 break; 9168 QualType U = AT ? AT->getDeducedType() : QualType(); 9169 if (!U.isNull()) { 9170 CanQualType UCanon = Context.getCanonicalType(U); 9171 if (Deduced.isNull()) { 9172 Deduced = U; 9173 DeducedCanon = UCanon; 9174 DeducedDecl = D; 9175 } else if (DeducedCanon != UCanon) { 9176 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9177 diag::err_auto_different_deductions) 9178 << (AT->isDecltypeAuto() ? 1 : 0) 9179 << Deduced << DeducedDecl->getDeclName() 9180 << U << D->getDeclName() 9181 << DeducedDecl->getInit()->getSourceRange() 9182 << D->getInit()->getSourceRange(); 9183 D->setInvalidDecl(); 9184 break; 9185 } 9186 } 9187 } 9188 } 9189 } 9190 9191 ActOnDocumentableDecls(Group); 9192 9193 return DeclGroupPtrTy::make( 9194 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9195 } 9196 9197 void Sema::ActOnDocumentableDecl(Decl *D) { 9198 ActOnDocumentableDecls(D); 9199 } 9200 9201 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9202 // Don't parse the comment if Doxygen diagnostics are ignored. 9203 if (Group.empty() || !Group[0]) 9204 return; 9205 9206 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9207 Group[0]->getLocation()) 9208 == DiagnosticsEngine::Ignored) 9209 return; 9210 9211 if (Group.size() >= 2) { 9212 // This is a decl group. Normally it will contain only declarations 9213 // produced from declarator list. But in case we have any definitions or 9214 // additional declaration references: 9215 // 'typedef struct S {} S;' 9216 // 'typedef struct S *S;' 9217 // 'struct S *pS;' 9218 // FinalizeDeclaratorGroup adds these as separate declarations. 9219 Decl *MaybeTagDecl = Group[0]; 9220 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9221 Group = Group.slice(1); 9222 } 9223 } 9224 9225 // See if there are any new comments that are not attached to a decl. 9226 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9227 if (!Comments.empty() && 9228 !Comments.back()->isAttached()) { 9229 // There is at least one comment that not attached to a decl. 9230 // Maybe it should be attached to one of these decls? 9231 // 9232 // Note that this way we pick up not only comments that precede the 9233 // declaration, but also comments that *follow* the declaration -- thanks to 9234 // the lookahead in the lexer: we've consumed the semicolon and looked 9235 // ahead through comments. 9236 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9237 Context.getCommentForDecl(Group[i], &PP); 9238 } 9239 } 9240 9241 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9242 /// to introduce parameters into function prototype scope. 9243 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9244 const DeclSpec &DS = D.getDeclSpec(); 9245 9246 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9247 9248 // C++03 [dcl.stc]p2 also permits 'auto'. 9249 VarDecl::StorageClass StorageClass = SC_None; 9250 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9251 StorageClass = SC_Register; 9252 } else if (getLangOpts().CPlusPlus && 9253 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9254 StorageClass = SC_Auto; 9255 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9256 Diag(DS.getStorageClassSpecLoc(), 9257 diag::err_invalid_storage_class_in_func_decl); 9258 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9259 } 9260 9261 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9262 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9263 << DeclSpec::getSpecifierName(TSCS); 9264 if (DS.isConstexprSpecified()) 9265 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9266 << 0; 9267 9268 DiagnoseFunctionSpecifiers(DS); 9269 9270 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9271 QualType parmDeclType = TInfo->getType(); 9272 9273 if (getLangOpts().CPlusPlus) { 9274 // Check that there are no default arguments inside the type of this 9275 // parameter. 9276 CheckExtraCXXDefaultArguments(D); 9277 9278 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9279 if (D.getCXXScopeSpec().isSet()) { 9280 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9281 << D.getCXXScopeSpec().getRange(); 9282 D.getCXXScopeSpec().clear(); 9283 } 9284 } 9285 9286 // Ensure we have a valid name 9287 IdentifierInfo *II = 0; 9288 if (D.hasName()) { 9289 II = D.getIdentifier(); 9290 if (!II) { 9291 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9292 << GetNameForDeclarator(D).getName(); 9293 D.setInvalidType(true); 9294 } 9295 } 9296 9297 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9298 if (II) { 9299 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9300 ForRedeclaration); 9301 LookupName(R, S); 9302 if (R.isSingleResult()) { 9303 NamedDecl *PrevDecl = R.getFoundDecl(); 9304 if (PrevDecl->isTemplateParameter()) { 9305 // Maybe we will complain about the shadowed template parameter. 9306 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9307 // Just pretend that we didn't see the previous declaration. 9308 PrevDecl = 0; 9309 } else if (S->isDeclScope(PrevDecl)) { 9310 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9311 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9312 9313 // Recover by removing the name 9314 II = 0; 9315 D.SetIdentifier(0, D.getIdentifierLoc()); 9316 D.setInvalidType(true); 9317 } 9318 } 9319 } 9320 9321 // Temporarily put parameter variables in the translation unit, not 9322 // the enclosing context. This prevents them from accidentally 9323 // looking like class members in C++. 9324 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9325 D.getLocStart(), 9326 D.getIdentifierLoc(), II, 9327 parmDeclType, TInfo, 9328 StorageClass); 9329 9330 if (D.isInvalidType()) 9331 New->setInvalidDecl(); 9332 9333 assert(S->isFunctionPrototypeScope()); 9334 assert(S->getFunctionPrototypeDepth() >= 1); 9335 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9336 S->getNextFunctionPrototypeIndex()); 9337 9338 // Add the parameter declaration into this scope. 9339 S->AddDecl(New); 9340 if (II) 9341 IdResolver.AddDecl(New); 9342 9343 ProcessDeclAttributes(S, New, D); 9344 9345 if (D.getDeclSpec().isModulePrivateSpecified()) 9346 Diag(New->getLocation(), diag::err_module_private_local) 9347 << 1 << New->getDeclName() 9348 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9349 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9350 9351 if (New->hasAttr<BlocksAttr>()) { 9352 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9353 } 9354 return New; 9355 } 9356 9357 /// \brief Synthesizes a variable for a parameter arising from a 9358 /// typedef. 9359 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9360 SourceLocation Loc, 9361 QualType T) { 9362 /* FIXME: setting StartLoc == Loc. 9363 Would it be worth to modify callers so as to provide proper source 9364 location for the unnamed parameters, embedding the parameter's type? */ 9365 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9366 T, Context.getTrivialTypeSourceInfo(T, Loc), 9367 SC_None, 0); 9368 Param->setImplicit(); 9369 return Param; 9370 } 9371 9372 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9373 ParmVarDecl * const *ParamEnd) { 9374 // Don't diagnose unused-parameter errors in template instantiations; we 9375 // will already have done so in the template itself. 9376 if (!ActiveTemplateInstantiations.empty()) 9377 return; 9378 9379 for (; Param != ParamEnd; ++Param) { 9380 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9381 !(*Param)->hasAttr<UnusedAttr>()) { 9382 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9383 << (*Param)->getDeclName(); 9384 } 9385 } 9386 } 9387 9388 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9389 ParmVarDecl * const *ParamEnd, 9390 QualType ReturnTy, 9391 NamedDecl *D) { 9392 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9393 return; 9394 9395 // Warn if the return value is pass-by-value and larger than the specified 9396 // threshold. 9397 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9398 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9399 if (Size > LangOpts.NumLargeByValueCopy) 9400 Diag(D->getLocation(), diag::warn_return_value_size) 9401 << D->getDeclName() << Size; 9402 } 9403 9404 // Warn if any parameter is pass-by-value and larger than the specified 9405 // threshold. 9406 for (; Param != ParamEnd; ++Param) { 9407 QualType T = (*Param)->getType(); 9408 if (T->isDependentType() || !T.isPODType(Context)) 9409 continue; 9410 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9411 if (Size > LangOpts.NumLargeByValueCopy) 9412 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9413 << (*Param)->getDeclName() << Size; 9414 } 9415 } 9416 9417 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9418 SourceLocation NameLoc, IdentifierInfo *Name, 9419 QualType T, TypeSourceInfo *TSInfo, 9420 VarDecl::StorageClass StorageClass) { 9421 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9422 if (getLangOpts().ObjCAutoRefCount && 9423 T.getObjCLifetime() == Qualifiers::OCL_None && 9424 T->isObjCLifetimeType()) { 9425 9426 Qualifiers::ObjCLifetime lifetime; 9427 9428 // Special cases for arrays: 9429 // - if it's const, use __unsafe_unretained 9430 // - otherwise, it's an error 9431 if (T->isArrayType()) { 9432 if (!T.isConstQualified()) { 9433 DelayedDiagnostics.add( 9434 sema::DelayedDiagnostic::makeForbiddenType( 9435 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9436 } 9437 lifetime = Qualifiers::OCL_ExplicitNone; 9438 } else { 9439 lifetime = T->getObjCARCImplicitLifetime(); 9440 } 9441 T = Context.getLifetimeQualifiedType(T, lifetime); 9442 } 9443 9444 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9445 Context.getAdjustedParameterType(T), 9446 TSInfo, 9447 StorageClass, 0); 9448 9449 // Parameters can not be abstract class types. 9450 // For record types, this is done by the AbstractClassUsageDiagnoser once 9451 // the class has been completely parsed. 9452 if (!CurContext->isRecord() && 9453 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9454 AbstractParamType)) 9455 New->setInvalidDecl(); 9456 9457 // Parameter declarators cannot be interface types. All ObjC objects are 9458 // passed by reference. 9459 if (T->isObjCObjectType()) { 9460 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9461 Diag(NameLoc, 9462 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9463 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9464 T = Context.getObjCObjectPointerType(T); 9465 New->setType(T); 9466 } 9467 9468 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9469 // duration shall not be qualified by an address-space qualifier." 9470 // Since all parameters have automatic store duration, they can not have 9471 // an address space. 9472 if (T.getAddressSpace() != 0) { 9473 Diag(NameLoc, diag::err_arg_with_address_space); 9474 New->setInvalidDecl(); 9475 } 9476 9477 return New; 9478 } 9479 9480 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9481 SourceLocation LocAfterDecls) { 9482 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9483 9484 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9485 // for a K&R function. 9486 if (!FTI.hasPrototype) { 9487 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 9488 --i; 9489 if (FTI.Params[i].Param == 0) { 9490 SmallString<256> Code; 9491 llvm::raw_svector_ostream(Code) 9492 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 9493 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 9494 << FTI.Params[i].Ident 9495 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9496 9497 // Implicitly declare the argument as type 'int' for lack of a better 9498 // type. 9499 AttributeFactory attrs; 9500 DeclSpec DS(attrs); 9501 const char* PrevSpec; // unused 9502 unsigned DiagID; // unused 9503 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 9504 DiagID, Context.getPrintingPolicy()); 9505 // Use the identifier location for the type source range. 9506 DS.SetRangeStart(FTI.Params[i].IdentLoc); 9507 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 9508 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9509 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 9510 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 9511 } 9512 } 9513 } 9514 } 9515 9516 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9517 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9518 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9519 Scope *ParentScope = FnBodyScope->getParent(); 9520 9521 D.setFunctionDefinitionKind(FDK_Definition); 9522 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9523 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9524 } 9525 9526 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9527 const FunctionDecl*& PossibleZeroParamPrototype) { 9528 // Don't warn about invalid declarations. 9529 if (FD->isInvalidDecl()) 9530 return false; 9531 9532 // Or declarations that aren't global. 9533 if (!FD->isGlobal()) 9534 return false; 9535 9536 // Don't warn about C++ member functions. 9537 if (isa<CXXMethodDecl>(FD)) 9538 return false; 9539 9540 // Don't warn about 'main'. 9541 if (FD->isMain()) 9542 return false; 9543 9544 // Don't warn about inline functions. 9545 if (FD->isInlined()) 9546 return false; 9547 9548 // Don't warn about function templates. 9549 if (FD->getDescribedFunctionTemplate()) 9550 return false; 9551 9552 // Don't warn about function template specializations. 9553 if (FD->isFunctionTemplateSpecialization()) 9554 return false; 9555 9556 // Don't warn for OpenCL kernels. 9557 if (FD->hasAttr<OpenCLKernelAttr>()) 9558 return false; 9559 9560 bool MissingPrototype = true; 9561 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9562 Prev; Prev = Prev->getPreviousDecl()) { 9563 // Ignore any declarations that occur in function or method 9564 // scope, because they aren't visible from the header. 9565 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9566 continue; 9567 9568 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9569 if (FD->getNumParams() == 0) 9570 PossibleZeroParamPrototype = Prev; 9571 break; 9572 } 9573 9574 return MissingPrototype; 9575 } 9576 9577 void 9578 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9579 const FunctionDecl *EffectiveDefinition) { 9580 // Don't complain if we're in GNU89 mode and the previous definition 9581 // was an extern inline function. 9582 const FunctionDecl *Definition = EffectiveDefinition; 9583 if (!Definition) 9584 if (!FD->isDefined(Definition)) 9585 return; 9586 9587 if (canRedefineFunction(Definition, getLangOpts())) 9588 return; 9589 9590 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9591 Definition->getStorageClass() == SC_Extern) 9592 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9593 << FD->getDeclName() << getLangOpts().CPlusPlus; 9594 else 9595 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9596 9597 Diag(Definition->getLocation(), diag::note_previous_definition); 9598 FD->setInvalidDecl(); 9599 } 9600 9601 9602 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9603 Sema &S) { 9604 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9605 9606 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9607 LSI->CallOperator = CallOperator; 9608 LSI->Lambda = LambdaClass; 9609 LSI->ReturnType = CallOperator->getReturnType(); 9610 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9611 9612 if (LCD == LCD_None) 9613 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9614 else if (LCD == LCD_ByCopy) 9615 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9616 else if (LCD == LCD_ByRef) 9617 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9618 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9619 9620 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9621 LSI->Mutable = !CallOperator->isConst(); 9622 9623 // Add the captures to the LSI so they can be noted as already 9624 // captured within tryCaptureVar. 9625 for (const auto &C : LambdaClass->captures()) { 9626 if (C.capturesVariable()) { 9627 VarDecl *VD = C.getCapturedVar(); 9628 if (VD->isInitCapture()) 9629 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9630 QualType CaptureType = VD->getType(); 9631 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 9632 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9633 /*RefersToEnclosingLocal*/true, C.getLocation(), 9634 /*EllipsisLoc*/C.isPackExpansion() 9635 ? C.getEllipsisLoc() : SourceLocation(), 9636 CaptureType, /*Expr*/ 0); 9637 9638 } else if (C.capturesThis()) { 9639 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 9640 S.getCurrentThisType(), /*Expr*/ 0); 9641 } 9642 } 9643 } 9644 9645 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9646 // Clear the last template instantiation error context. 9647 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9648 9649 if (!D) 9650 return D; 9651 FunctionDecl *FD = 0; 9652 9653 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9654 FD = FunTmpl->getTemplatedDecl(); 9655 else 9656 FD = cast<FunctionDecl>(D); 9657 // If we are instantiating a generic lambda call operator, push 9658 // a LambdaScopeInfo onto the function stack. But use the information 9659 // that's already been calculated (ActOnLambdaExpr) to prime the current 9660 // LambdaScopeInfo. 9661 // When the template operator is being specialized, the LambdaScopeInfo, 9662 // has to be properly restored so that tryCaptureVariable doesn't try 9663 // and capture any new variables. In addition when calculating potential 9664 // captures during transformation of nested lambdas, it is necessary to 9665 // have the LSI properly restored. 9666 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9667 assert(ActiveTemplateInstantiations.size() && 9668 "There should be an active template instantiation on the stack " 9669 "when instantiating a generic lambda!"); 9670 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9671 } 9672 else 9673 // Enter a new function scope 9674 PushFunctionScope(); 9675 9676 // See if this is a redefinition. 9677 if (!FD->isLateTemplateParsed()) 9678 CheckForFunctionRedefinition(FD); 9679 9680 // Builtin functions cannot be defined. 9681 if (unsigned BuiltinID = FD->getBuiltinID()) { 9682 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9683 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9684 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9685 FD->setInvalidDecl(); 9686 } 9687 } 9688 9689 // The return type of a function definition must be complete 9690 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9691 QualType ResultType = FD->getReturnType(); 9692 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9693 !FD->isInvalidDecl() && 9694 RequireCompleteType(FD->getLocation(), ResultType, 9695 diag::err_func_def_incomplete_result)) 9696 FD->setInvalidDecl(); 9697 9698 // GNU warning -Wmissing-prototypes: 9699 // Warn if a global function is defined without a previous 9700 // prototype declaration. This warning is issued even if the 9701 // definition itself provides a prototype. The aim is to detect 9702 // global functions that fail to be declared in header files. 9703 const FunctionDecl *PossibleZeroParamPrototype = 0; 9704 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9705 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9706 9707 if (PossibleZeroParamPrototype) { 9708 // We found a declaration that is not a prototype, 9709 // but that could be a zero-parameter prototype 9710 if (TypeSourceInfo *TI = 9711 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9712 TypeLoc TL = TI->getTypeLoc(); 9713 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9714 Diag(PossibleZeroParamPrototype->getLocation(), 9715 diag::note_declaration_not_a_prototype) 9716 << PossibleZeroParamPrototype 9717 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9718 } 9719 } 9720 } 9721 9722 if (FnBodyScope) 9723 PushDeclContext(FnBodyScope, FD); 9724 9725 // Check the validity of our function parameters 9726 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9727 /*CheckParameterNames=*/true); 9728 9729 // Introduce our parameters into the function scope 9730 for (auto Param : FD->params()) { 9731 Param->setOwningFunction(FD); 9732 9733 // If this has an identifier, add it to the scope stack. 9734 if (Param->getIdentifier() && FnBodyScope) { 9735 CheckShadow(FnBodyScope, Param); 9736 9737 PushOnScopeChains(Param, FnBodyScope); 9738 } 9739 } 9740 9741 // If we had any tags defined in the function prototype, 9742 // introduce them into the function scope. 9743 if (FnBodyScope) { 9744 for (ArrayRef<NamedDecl *>::iterator 9745 I = FD->getDeclsInPrototypeScope().begin(), 9746 E = FD->getDeclsInPrototypeScope().end(); 9747 I != E; ++I) { 9748 NamedDecl *D = *I; 9749 9750 // Some of these decls (like enums) may have been pinned to the translation unit 9751 // for lack of a real context earlier. If so, remove from the translation unit 9752 // and reattach to the current context. 9753 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9754 // Is the decl actually in the context? 9755 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 9756 if (DI == D) { 9757 Context.getTranslationUnitDecl()->removeDecl(D); 9758 break; 9759 } 9760 } 9761 // Either way, reassign the lexical decl context to our FunctionDecl. 9762 D->setLexicalDeclContext(CurContext); 9763 } 9764 9765 // If the decl has a non-null name, make accessible in the current scope. 9766 if (!D->getName().empty()) 9767 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9768 9769 // Similarly, dive into enums and fish their constants out, making them 9770 // accessible in this scope. 9771 if (auto *ED = dyn_cast<EnumDecl>(D)) { 9772 for (auto *EI : ED->enumerators()) 9773 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 9774 } 9775 } 9776 } 9777 9778 // Ensure that the function's exception specification is instantiated. 9779 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9780 ResolveExceptionSpec(D->getLocation(), FPT); 9781 9782 // Checking attributes of current function definition 9783 // dllimport attribute. 9784 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9785 if (DA && (!FD->hasAttr<DLLExportAttr>())) { 9786 // dllimport attribute cannot be directly applied to definition. 9787 // Microsoft accepts dllimport for functions defined within class scope. 9788 if (!DA->isInherited() && 9789 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9790 Diag(FD->getLocation(), 9791 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9792 << DA; 9793 FD->setInvalidDecl(); 9794 return D; 9795 } 9796 } 9797 // We want to attach documentation to original Decl (which might be 9798 // a function template). 9799 ActOnDocumentableDecl(D); 9800 return D; 9801 } 9802 9803 /// \brief Given the set of return statements within a function body, 9804 /// compute the variables that are subject to the named return value 9805 /// optimization. 9806 /// 9807 /// Each of the variables that is subject to the named return value 9808 /// optimization will be marked as NRVO variables in the AST, and any 9809 /// return statement that has a marked NRVO variable as its NRVO candidate can 9810 /// use the named return value optimization. 9811 /// 9812 /// This function applies a very simplistic algorithm for NRVO: if every return 9813 /// statement in the function has the same NRVO candidate, that candidate is 9814 /// the NRVO variable. 9815 /// 9816 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9817 /// statements and the lifetimes of the NRVO candidates. We should be able to 9818 /// find a maximal set of NRVO variables. 9819 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9820 ReturnStmt **Returns = Scope->Returns.data(); 9821 9822 const VarDecl *NRVOCandidate = 0; 9823 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9824 if (!Returns[I]->getNRVOCandidate()) 9825 return; 9826 9827 if (!NRVOCandidate) 9828 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9829 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9830 return; 9831 } 9832 9833 if (NRVOCandidate) 9834 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9835 } 9836 9837 bool Sema::canDelayFunctionBody(const Declarator &D) { 9838 // We can't delay parsing the body of a constexpr function template (yet). 9839 if (D.getDeclSpec().isConstexprSpecified()) 9840 return false; 9841 9842 // We can't delay parsing the body of a function template with a deduced 9843 // return type (yet). 9844 if (D.getDeclSpec().containsPlaceholderType()) { 9845 // If the placeholder introduces a non-deduced trailing return type, 9846 // we can still delay parsing it. 9847 if (D.getNumTypeObjects()) { 9848 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 9849 if (Outer.Kind == DeclaratorChunk::Function && 9850 Outer.Fun.hasTrailingReturnType()) { 9851 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 9852 return Ty.isNull() || !Ty->isUndeducedType(); 9853 } 9854 } 9855 return false; 9856 } 9857 9858 return true; 9859 } 9860 9861 bool Sema::canSkipFunctionBody(Decl *D) { 9862 // We cannot skip the body of a function (or function template) which is 9863 // constexpr, since we may need to evaluate its body in order to parse the 9864 // rest of the file. 9865 // We cannot skip the body of a function with an undeduced return type, 9866 // because any callers of that function need to know the type. 9867 if (const FunctionDecl *FD = D->getAsFunction()) 9868 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9869 return false; 9870 return Consumer.shouldSkipFunctionBody(D); 9871 } 9872 9873 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9874 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9875 FD->setHasSkippedBody(); 9876 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9877 MD->setHasSkippedBody(); 9878 return ActOnFinishFunctionBody(Decl, 0); 9879 } 9880 9881 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9882 return ActOnFinishFunctionBody(D, BodyArg, false); 9883 } 9884 9885 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9886 bool IsInstantiation) { 9887 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0; 9888 9889 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9890 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9891 9892 if (FD) { 9893 FD->setBody(Body); 9894 9895 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9896 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 9897 // If the function has a deduced result type but contains no 'return' 9898 // statements, the result type as written must be exactly 'auto', and 9899 // the deduced result type is 'void'. 9900 if (!FD->getReturnType()->getAs<AutoType>()) { 9901 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9902 << FD->getReturnType(); 9903 FD->setInvalidDecl(); 9904 } else { 9905 // Substitute 'void' for the 'auto' in the type. 9906 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9907 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 9908 Context.adjustDeducedFunctionResultType( 9909 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9910 } 9911 } 9912 9913 // The only way to be included in UndefinedButUsed is if there is an 9914 // ODR use before the definition. Avoid the expensive map lookup if this 9915 // is the first declaration. 9916 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9917 if (!FD->isExternallyVisible()) 9918 UndefinedButUsed.erase(FD); 9919 else if (FD->isInlined() && 9920 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9921 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9922 UndefinedButUsed.erase(FD); 9923 } 9924 9925 // If the function implicitly returns zero (like 'main') or is naked, 9926 // don't complain about missing return statements. 9927 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9928 WP.disableCheckFallThrough(); 9929 9930 // MSVC permits the use of pure specifier (=0) on function definition, 9931 // defined at class scope, warn about this non-standard construct. 9932 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9933 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9934 9935 if (!FD->isInvalidDecl()) { 9936 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9937 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9938 FD->getReturnType(), FD); 9939 9940 // If this is a constructor, we need a vtable. 9941 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9942 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9943 9944 // Try to apply the named return value optimization. We have to check 9945 // if we can do this here because lambdas keep return statements around 9946 // to deduce an implicit return type. 9947 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 9948 !FD->isDependentContext()) 9949 computeNRVO(Body, getCurFunction()); 9950 } 9951 9952 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9953 "Function parsing confused"); 9954 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9955 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9956 MD->setBody(Body); 9957 if (!MD->isInvalidDecl()) { 9958 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9959 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9960 MD->getReturnType(), MD); 9961 9962 if (Body) 9963 computeNRVO(Body, getCurFunction()); 9964 } 9965 if (getCurFunction()->ObjCShouldCallSuper) { 9966 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9967 << MD->getSelector().getAsString(); 9968 getCurFunction()->ObjCShouldCallSuper = false; 9969 } 9970 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 9971 const ObjCMethodDecl *InitMethod = 0; 9972 bool isDesignated = 9973 MD->isDesignatedInitializerForTheInterface(&InitMethod); 9974 assert(isDesignated && InitMethod); 9975 (void)isDesignated; 9976 // Don't issue this warning for unavaialable inits. 9977 if (!MD->isUnavailable()) { 9978 Diag(MD->getLocation(), 9979 diag::warn_objc_designated_init_missing_super_call); 9980 Diag(InitMethod->getLocation(), 9981 diag::note_objc_designated_init_marked_here); 9982 } 9983 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 9984 } 9985 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 9986 // Don't issue this warning for unavaialable inits. 9987 if (!MD->isUnavailable()) 9988 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 9989 getCurFunction()->ObjCWarnForNoInitDelegation = false; 9990 } 9991 } else { 9992 return 0; 9993 } 9994 9995 assert(!getCurFunction()->ObjCShouldCallSuper && 9996 "This should only be set for ObjC methods, which should have been " 9997 "handled in the block above."); 9998 9999 // Verify and clean out per-function state. 10000 if (Body) { 10001 // C++ constructors that have function-try-blocks can't have return 10002 // statements in the handlers of that block. (C++ [except.handle]p14) 10003 // Verify this. 10004 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10005 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10006 10007 // Verify that gotos and switch cases don't jump into scopes illegally. 10008 if (getCurFunction()->NeedsScopeChecking() && 10009 !dcl->isInvalidDecl() && 10010 !hasAnyUnrecoverableErrorsInThisFunction() && 10011 !PP.isCodeCompletionEnabled()) 10012 DiagnoseInvalidJumps(Body); 10013 10014 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10015 if (!Destructor->getParent()->isDependentType()) 10016 CheckDestructor(Destructor); 10017 10018 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10019 Destructor->getParent()); 10020 } 10021 10022 // If any errors have occurred, clear out any temporaries that may have 10023 // been leftover. This ensures that these temporaries won't be picked up for 10024 // deletion in some later function. 10025 if (PP.getDiagnostics().hasErrorOccurred() || 10026 PP.getDiagnostics().getSuppressAllDiagnostics()) { 10027 DiscardCleanupsInEvaluationContext(); 10028 } 10029 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 10030 !isa<FunctionTemplateDecl>(dcl)) { 10031 // Since the body is valid, issue any analysis-based warnings that are 10032 // enabled. 10033 ActivePolicy = &WP; 10034 } 10035 10036 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10037 (!CheckConstexprFunctionDecl(FD) || 10038 !CheckConstexprFunctionBody(FD, Body))) 10039 FD->setInvalidDecl(); 10040 10041 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 10042 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10043 assert(MaybeODRUseExprs.empty() && 10044 "Leftover expressions for odr-use checking"); 10045 } 10046 10047 if (!IsInstantiation) 10048 PopDeclContext(); 10049 10050 PopFunctionScopeInfo(ActivePolicy, dcl); 10051 // If any errors have occurred, clear out any temporaries that may have 10052 // been leftover. This ensures that these temporaries won't be picked up for 10053 // deletion in some later function. 10054 if (getDiagnostics().hasErrorOccurred()) { 10055 DiscardCleanupsInEvaluationContext(); 10056 } 10057 10058 return dcl; 10059 } 10060 10061 10062 /// When we finish delayed parsing of an attribute, we must attach it to the 10063 /// relevant Decl. 10064 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10065 ParsedAttributes &Attrs) { 10066 // Always attach attributes to the underlying decl. 10067 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10068 D = TD->getTemplatedDecl(); 10069 ProcessDeclAttributeList(S, D, Attrs.getList()); 10070 10071 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10072 if (Method->isStatic()) 10073 checkThisInStaticMemberFunctionAttributes(Method); 10074 } 10075 10076 10077 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10078 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10079 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10080 IdentifierInfo &II, Scope *S) { 10081 // Before we produce a declaration for an implicitly defined 10082 // function, see whether there was a locally-scoped declaration of 10083 // this name as a function or variable. If so, use that 10084 // (non-visible) declaration, and complain about it. 10085 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10086 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10087 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10088 return ExternCPrev; 10089 } 10090 10091 // Extension in C99. Legal in C90, but warn about it. 10092 unsigned diag_id; 10093 if (II.getName().startswith("__builtin_")) 10094 diag_id = diag::warn_builtin_unknown; 10095 else if (getLangOpts().C99) 10096 diag_id = diag::ext_implicit_function_decl; 10097 else 10098 diag_id = diag::warn_implicit_function_decl; 10099 Diag(Loc, diag_id) << &II; 10100 10101 // Because typo correction is expensive, only do it if the implicit 10102 // function declaration is going to be treated as an error. 10103 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10104 TypoCorrection Corrected; 10105 DeclFilterCCC<FunctionDecl> Validator; 10106 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 10107 LookupOrdinaryName, S, 0, Validator))) 10108 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10109 /*ErrorRecovery*/false); 10110 } 10111 10112 // Set a Declarator for the implicit definition: int foo(); 10113 const char *Dummy; 10114 AttributeFactory attrFactory; 10115 DeclSpec DS(attrFactory); 10116 unsigned DiagID; 10117 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10118 Context.getPrintingPolicy()); 10119 (void)Error; // Silence warning. 10120 assert(!Error && "Error setting up implicit decl!"); 10121 SourceLocation NoLoc; 10122 Declarator D(DS, Declarator::BlockContext); 10123 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10124 /*IsAmbiguous=*/false, 10125 /*LParenLoc=*/NoLoc, 10126 /*Params=*/0, 10127 /*NumParams=*/0, 10128 /*EllipsisLoc=*/NoLoc, 10129 /*RParenLoc=*/NoLoc, 10130 /*TypeQuals=*/0, 10131 /*RefQualifierIsLvalueRef=*/true, 10132 /*RefQualifierLoc=*/NoLoc, 10133 /*ConstQualifierLoc=*/NoLoc, 10134 /*VolatileQualifierLoc=*/NoLoc, 10135 /*MutableLoc=*/NoLoc, 10136 EST_None, 10137 /*ESpecLoc=*/NoLoc, 10138 /*Exceptions=*/0, 10139 /*ExceptionRanges=*/0, 10140 /*NumExceptions=*/0, 10141 /*NoexceptExpr=*/0, 10142 Loc, Loc, D), 10143 DS.getAttributes(), 10144 SourceLocation()); 10145 D.SetIdentifier(&II, Loc); 10146 10147 // Insert this function into translation-unit scope. 10148 10149 DeclContext *PrevDC = CurContext; 10150 CurContext = Context.getTranslationUnitDecl(); 10151 10152 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10153 FD->setImplicit(); 10154 10155 CurContext = PrevDC; 10156 10157 AddKnownFunctionAttributes(FD); 10158 10159 return FD; 10160 } 10161 10162 /// \brief Adds any function attributes that we know a priori based on 10163 /// the declaration of this function. 10164 /// 10165 /// These attributes can apply both to implicitly-declared builtins 10166 /// (like __builtin___printf_chk) or to library-declared functions 10167 /// like NSLog or printf. 10168 /// 10169 /// We need to check for duplicate attributes both here and where user-written 10170 /// attributes are applied to declarations. 10171 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10172 if (FD->isInvalidDecl()) 10173 return; 10174 10175 // If this is a built-in function, map its builtin attributes to 10176 // actual attributes. 10177 if (unsigned BuiltinID = FD->getBuiltinID()) { 10178 // Handle printf-formatting attributes. 10179 unsigned FormatIdx; 10180 bool HasVAListArg; 10181 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10182 if (!FD->hasAttr<FormatAttr>()) { 10183 const char *fmt = "printf"; 10184 unsigned int NumParams = FD->getNumParams(); 10185 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10186 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10187 fmt = "NSString"; 10188 FD->addAttr(FormatAttr::CreateImplicit(Context, 10189 &Context.Idents.get(fmt), 10190 FormatIdx+1, 10191 HasVAListArg ? 0 : FormatIdx+2, 10192 FD->getLocation())); 10193 } 10194 } 10195 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10196 HasVAListArg)) { 10197 if (!FD->hasAttr<FormatAttr>()) 10198 FD->addAttr(FormatAttr::CreateImplicit(Context, 10199 &Context.Idents.get("scanf"), 10200 FormatIdx+1, 10201 HasVAListArg ? 0 : FormatIdx+2, 10202 FD->getLocation())); 10203 } 10204 10205 // Mark const if we don't care about errno and that is the only 10206 // thing preventing the function from being const. This allows 10207 // IRgen to use LLVM intrinsics for such functions. 10208 if (!getLangOpts().MathErrno && 10209 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10210 if (!FD->hasAttr<ConstAttr>()) 10211 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10212 } 10213 10214 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10215 !FD->hasAttr<ReturnsTwiceAttr>()) 10216 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10217 FD->getLocation())); 10218 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10219 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10220 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10221 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10222 } 10223 10224 IdentifierInfo *Name = FD->getIdentifier(); 10225 if (!Name) 10226 return; 10227 if ((!getLangOpts().CPlusPlus && 10228 FD->getDeclContext()->isTranslationUnit()) || 10229 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10230 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10231 LinkageSpecDecl::lang_c)) { 10232 // Okay: this could be a libc/libm/Objective-C function we know 10233 // about. 10234 } else 10235 return; 10236 10237 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10238 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10239 // target-specific builtins, perhaps? 10240 if (!FD->hasAttr<FormatAttr>()) 10241 FD->addAttr(FormatAttr::CreateImplicit(Context, 10242 &Context.Idents.get("printf"), 2, 10243 Name->isStr("vasprintf") ? 0 : 3, 10244 FD->getLocation())); 10245 } 10246 10247 if (Name->isStr("__CFStringMakeConstantString")) { 10248 // We already have a __builtin___CFStringMakeConstantString, 10249 // but builds that use -fno-constant-cfstrings don't go through that. 10250 if (!FD->hasAttr<FormatArgAttr>()) 10251 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10252 FD->getLocation())); 10253 } 10254 } 10255 10256 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10257 TypeSourceInfo *TInfo) { 10258 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10259 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10260 10261 if (!TInfo) { 10262 assert(D.isInvalidType() && "no declarator info for valid type"); 10263 TInfo = Context.getTrivialTypeSourceInfo(T); 10264 } 10265 10266 // Scope manipulation handled by caller. 10267 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10268 D.getLocStart(), 10269 D.getIdentifierLoc(), 10270 D.getIdentifier(), 10271 TInfo); 10272 10273 // Bail out immediately if we have an invalid declaration. 10274 if (D.isInvalidType()) { 10275 NewTD->setInvalidDecl(); 10276 return NewTD; 10277 } 10278 10279 if (D.getDeclSpec().isModulePrivateSpecified()) { 10280 if (CurContext->isFunctionOrMethod()) 10281 Diag(NewTD->getLocation(), diag::err_module_private_local) 10282 << 2 << NewTD->getDeclName() 10283 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10284 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10285 else 10286 NewTD->setModulePrivate(); 10287 } 10288 10289 // C++ [dcl.typedef]p8: 10290 // If the typedef declaration defines an unnamed class (or 10291 // enum), the first typedef-name declared by the declaration 10292 // to be that class type (or enum type) is used to denote the 10293 // class type (or enum type) for linkage purposes only. 10294 // We need to check whether the type was declared in the declaration. 10295 switch (D.getDeclSpec().getTypeSpecType()) { 10296 case TST_enum: 10297 case TST_struct: 10298 case TST_interface: 10299 case TST_union: 10300 case TST_class: { 10301 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10302 10303 // Do nothing if the tag is not anonymous or already has an 10304 // associated typedef (from an earlier typedef in this decl group). 10305 if (tagFromDeclSpec->getIdentifier()) break; 10306 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10307 10308 // A well-formed anonymous tag must always be a TUK_Definition. 10309 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10310 10311 // The type must match the tag exactly; no qualifiers allowed. 10312 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10313 break; 10314 10315 // If we've already computed linkage for the anonymous tag, then 10316 // adding a typedef name for the anonymous decl can change that 10317 // linkage, which might be a serious problem. Diagnose this as 10318 // unsupported and ignore the typedef name. TODO: we should 10319 // pursue this as a language defect and establish a formal rule 10320 // for how to handle it. 10321 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10322 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10323 10324 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10325 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(), 10326 getLangOpts()); 10327 10328 llvm::SmallString<40> textToInsert; 10329 textToInsert += ' '; 10330 textToInsert += D.getIdentifier()->getName(); 10331 Diag(tagLoc, diag::note_typedef_changes_linkage) 10332 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10333 break; 10334 } 10335 10336 // Otherwise, set this is the anon-decl typedef for the tag. 10337 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10338 break; 10339 } 10340 10341 default: 10342 break; 10343 } 10344 10345 return NewTD; 10346 } 10347 10348 10349 /// \brief Check that this is a valid underlying type for an enum declaration. 10350 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10351 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10352 QualType T = TI->getType(); 10353 10354 if (T->isDependentType()) 10355 return false; 10356 10357 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10358 if (BT->isInteger()) 10359 return false; 10360 10361 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10362 return true; 10363 } 10364 10365 /// Check whether this is a valid redeclaration of a previous enumeration. 10366 /// \return true if the redeclaration was invalid. 10367 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10368 QualType EnumUnderlyingTy, 10369 const EnumDecl *Prev) { 10370 bool IsFixed = !EnumUnderlyingTy.isNull(); 10371 10372 if (IsScoped != Prev->isScoped()) { 10373 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10374 << Prev->isScoped(); 10375 Diag(Prev->getLocation(), diag::note_previous_declaration); 10376 return true; 10377 } 10378 10379 if (IsFixed && Prev->isFixed()) { 10380 if (!EnumUnderlyingTy->isDependentType() && 10381 !Prev->getIntegerType()->isDependentType() && 10382 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10383 Prev->getIntegerType())) { 10384 // TODO: Highlight the underlying type of the redeclaration. 10385 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10386 << EnumUnderlyingTy << Prev->getIntegerType(); 10387 Diag(Prev->getLocation(), diag::note_previous_declaration) 10388 << Prev->getIntegerTypeRange(); 10389 return true; 10390 } 10391 } else if (IsFixed != Prev->isFixed()) { 10392 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10393 << Prev->isFixed(); 10394 Diag(Prev->getLocation(), diag::note_previous_declaration); 10395 return true; 10396 } 10397 10398 return false; 10399 } 10400 10401 /// \brief Get diagnostic %select index for tag kind for 10402 /// redeclaration diagnostic message. 10403 /// WARNING: Indexes apply to particular diagnostics only! 10404 /// 10405 /// \returns diagnostic %select index. 10406 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10407 switch (Tag) { 10408 case TTK_Struct: return 0; 10409 case TTK_Interface: return 1; 10410 case TTK_Class: return 2; 10411 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10412 } 10413 } 10414 10415 /// \brief Determine if tag kind is a class-key compatible with 10416 /// class for redeclaration (class, struct, or __interface). 10417 /// 10418 /// \returns true iff the tag kind is compatible. 10419 static bool isClassCompatTagKind(TagTypeKind Tag) 10420 { 10421 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10422 } 10423 10424 /// \brief Determine whether a tag with a given kind is acceptable 10425 /// as a redeclaration of the given tag declaration. 10426 /// 10427 /// \returns true if the new tag kind is acceptable, false otherwise. 10428 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10429 TagTypeKind NewTag, bool isDefinition, 10430 SourceLocation NewTagLoc, 10431 const IdentifierInfo &Name) { 10432 // C++ [dcl.type.elab]p3: 10433 // The class-key or enum keyword present in the 10434 // elaborated-type-specifier shall agree in kind with the 10435 // declaration to which the name in the elaborated-type-specifier 10436 // refers. This rule also applies to the form of 10437 // elaborated-type-specifier that declares a class-name or 10438 // friend class since it can be construed as referring to the 10439 // definition of the class. Thus, in any 10440 // elaborated-type-specifier, the enum keyword shall be used to 10441 // refer to an enumeration (7.2), the union class-key shall be 10442 // used to refer to a union (clause 9), and either the class or 10443 // struct class-key shall be used to refer to a class (clause 9) 10444 // declared using the class or struct class-key. 10445 TagTypeKind OldTag = Previous->getTagKind(); 10446 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10447 if (OldTag == NewTag) 10448 return true; 10449 10450 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10451 // Warn about the struct/class tag mismatch. 10452 bool isTemplate = false; 10453 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10454 isTemplate = Record->getDescribedClassTemplate(); 10455 10456 if (!ActiveTemplateInstantiations.empty()) { 10457 // In a template instantiation, do not offer fix-its for tag mismatches 10458 // since they usually mess up the template instead of fixing the problem. 10459 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10460 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10461 << getRedeclDiagFromTagKind(OldTag); 10462 return true; 10463 } 10464 10465 if (isDefinition) { 10466 // On definitions, check previous tags and issue a fix-it for each 10467 // one that doesn't match the current tag. 10468 if (Previous->getDefinition()) { 10469 // Don't suggest fix-its for redefinitions. 10470 return true; 10471 } 10472 10473 bool previousMismatch = false; 10474 for (auto I : Previous->redecls()) { 10475 if (I->getTagKind() != NewTag) { 10476 if (!previousMismatch) { 10477 previousMismatch = true; 10478 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10479 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10480 << getRedeclDiagFromTagKind(I->getTagKind()); 10481 } 10482 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10483 << getRedeclDiagFromTagKind(NewTag) 10484 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10485 TypeWithKeyword::getTagTypeKindName(NewTag)); 10486 } 10487 } 10488 return true; 10489 } 10490 10491 // Check for a previous definition. If current tag and definition 10492 // are same type, do nothing. If no definition, but disagree with 10493 // with previous tag type, give a warning, but no fix-it. 10494 const TagDecl *Redecl = Previous->getDefinition() ? 10495 Previous->getDefinition() : Previous; 10496 if (Redecl->getTagKind() == NewTag) { 10497 return true; 10498 } 10499 10500 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10501 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10502 << getRedeclDiagFromTagKind(OldTag); 10503 Diag(Redecl->getLocation(), diag::note_previous_use); 10504 10505 // If there is a previous definition, suggest a fix-it. 10506 if (Previous->getDefinition()) { 10507 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10508 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10509 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10510 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10511 } 10512 10513 return true; 10514 } 10515 return false; 10516 } 10517 10518 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10519 /// former case, Name will be non-null. In the later case, Name will be null. 10520 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10521 /// reference/declaration/definition of a tag. 10522 /// 10523 /// IsTypeSpecifier is true if this is a type-specifier (or 10524 /// trailing-type-specifier) other than one in an alias-declaration. 10525 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10526 SourceLocation KWLoc, CXXScopeSpec &SS, 10527 IdentifierInfo *Name, SourceLocation NameLoc, 10528 AttributeList *Attr, AccessSpecifier AS, 10529 SourceLocation ModulePrivateLoc, 10530 MultiTemplateParamsArg TemplateParameterLists, 10531 bool &OwnedDecl, bool &IsDependent, 10532 SourceLocation ScopedEnumKWLoc, 10533 bool ScopedEnumUsesClassTag, 10534 TypeResult UnderlyingType, 10535 bool IsTypeSpecifier) { 10536 // If this is not a definition, it must have a name. 10537 IdentifierInfo *OrigName = Name; 10538 assert((Name != 0 || TUK == TUK_Definition) && 10539 "Nameless record must be a definition!"); 10540 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10541 10542 OwnedDecl = false; 10543 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10544 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10545 10546 // FIXME: Check explicit specializations more carefully. 10547 bool isExplicitSpecialization = false; 10548 bool Invalid = false; 10549 10550 // We only need to do this matching if we have template parameters 10551 // or a scope specifier, which also conveniently avoids this work 10552 // for non-C++ cases. 10553 if (TemplateParameterLists.size() > 0 || 10554 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10555 if (TemplateParameterList *TemplateParams = 10556 MatchTemplateParametersToScopeSpecifier( 10557 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend, 10558 isExplicitSpecialization, Invalid)) { 10559 if (Kind == TTK_Enum) { 10560 Diag(KWLoc, diag::err_enum_template); 10561 return 0; 10562 } 10563 10564 if (TemplateParams->size() > 0) { 10565 // This is a declaration or definition of a class template (which may 10566 // be a member of another template). 10567 10568 if (Invalid) 10569 return 0; 10570 10571 OwnedDecl = false; 10572 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10573 SS, Name, NameLoc, Attr, 10574 TemplateParams, AS, 10575 ModulePrivateLoc, 10576 TemplateParameterLists.size()-1, 10577 TemplateParameterLists.data()); 10578 return Result.get(); 10579 } else { 10580 // The "template<>" header is extraneous. 10581 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10582 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10583 isExplicitSpecialization = true; 10584 } 10585 } 10586 } 10587 10588 // Figure out the underlying type if this a enum declaration. We need to do 10589 // this early, because it's needed to detect if this is an incompatible 10590 // redeclaration. 10591 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10592 10593 if (Kind == TTK_Enum) { 10594 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10595 // No underlying type explicitly specified, or we failed to parse the 10596 // type, default to int. 10597 EnumUnderlying = Context.IntTy.getTypePtr(); 10598 else if (UnderlyingType.get()) { 10599 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10600 // integral type; any cv-qualification is ignored. 10601 TypeSourceInfo *TI = 0; 10602 GetTypeFromParser(UnderlyingType.get(), &TI); 10603 EnumUnderlying = TI; 10604 10605 if (CheckEnumUnderlyingType(TI)) 10606 // Recover by falling back to int. 10607 EnumUnderlying = Context.IntTy.getTypePtr(); 10608 10609 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10610 UPPC_FixedUnderlyingType)) 10611 EnumUnderlying = Context.IntTy.getTypePtr(); 10612 10613 } else if (getLangOpts().MSVCCompat) 10614 // Microsoft enums are always of int type. 10615 EnumUnderlying = Context.IntTy.getTypePtr(); 10616 } 10617 10618 DeclContext *SearchDC = CurContext; 10619 DeclContext *DC = CurContext; 10620 bool isStdBadAlloc = false; 10621 10622 RedeclarationKind Redecl = ForRedeclaration; 10623 if (TUK == TUK_Friend || TUK == TUK_Reference) 10624 Redecl = NotForRedeclaration; 10625 10626 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10627 bool FriendSawTagOutsideEnclosingNamespace = false; 10628 if (Name && SS.isNotEmpty()) { 10629 // We have a nested-name tag ('struct foo::bar'). 10630 10631 // Check for invalid 'foo::'. 10632 if (SS.isInvalid()) { 10633 Name = 0; 10634 goto CreateNewDecl; 10635 } 10636 10637 // If this is a friend or a reference to a class in a dependent 10638 // context, don't try to make a decl for it. 10639 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10640 DC = computeDeclContext(SS, false); 10641 if (!DC) { 10642 IsDependent = true; 10643 return 0; 10644 } 10645 } else { 10646 DC = computeDeclContext(SS, true); 10647 if (!DC) { 10648 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10649 << SS.getRange(); 10650 return 0; 10651 } 10652 } 10653 10654 if (RequireCompleteDeclContext(SS, DC)) 10655 return 0; 10656 10657 SearchDC = DC; 10658 // Look-up name inside 'foo::'. 10659 LookupQualifiedName(Previous, DC); 10660 10661 if (Previous.isAmbiguous()) 10662 return 0; 10663 10664 if (Previous.empty()) { 10665 // Name lookup did not find anything. However, if the 10666 // nested-name-specifier refers to the current instantiation, 10667 // and that current instantiation has any dependent base 10668 // classes, we might find something at instantiation time: treat 10669 // this as a dependent elaborated-type-specifier. 10670 // But this only makes any sense for reference-like lookups. 10671 if (Previous.wasNotFoundInCurrentInstantiation() && 10672 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10673 IsDependent = true; 10674 return 0; 10675 } 10676 10677 // A tag 'foo::bar' must already exist. 10678 Diag(NameLoc, diag::err_not_tag_in_scope) 10679 << Kind << Name << DC << SS.getRange(); 10680 Name = 0; 10681 Invalid = true; 10682 goto CreateNewDecl; 10683 } 10684 } else if (Name) { 10685 // If this is a named struct, check to see if there was a previous forward 10686 // declaration or definition. 10687 // FIXME: We're looking into outer scopes here, even when we 10688 // shouldn't be. Doing so can result in ambiguities that we 10689 // shouldn't be diagnosing. 10690 LookupName(Previous, S); 10691 10692 // When declaring or defining a tag, ignore ambiguities introduced 10693 // by types using'ed into this scope. 10694 if (Previous.isAmbiguous() && 10695 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10696 LookupResult::Filter F = Previous.makeFilter(); 10697 while (F.hasNext()) { 10698 NamedDecl *ND = F.next(); 10699 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10700 F.erase(); 10701 } 10702 F.done(); 10703 } 10704 10705 // C++11 [namespace.memdef]p3: 10706 // If the name in a friend declaration is neither qualified nor 10707 // a template-id and the declaration is a function or an 10708 // elaborated-type-specifier, the lookup to determine whether 10709 // the entity has been previously declared shall not consider 10710 // any scopes outside the innermost enclosing namespace. 10711 // 10712 // Does it matter that this should be by scope instead of by 10713 // semantic context? 10714 if (!Previous.empty() && TUK == TUK_Friend) { 10715 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10716 LookupResult::Filter F = Previous.makeFilter(); 10717 while (F.hasNext()) { 10718 NamedDecl *ND = F.next(); 10719 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10720 if (DC->isFileContext() && 10721 !EnclosingNS->Encloses(ND->getDeclContext())) { 10722 F.erase(); 10723 FriendSawTagOutsideEnclosingNamespace = true; 10724 } 10725 } 10726 F.done(); 10727 } 10728 10729 // Note: there used to be some attempt at recovery here. 10730 if (Previous.isAmbiguous()) 10731 return 0; 10732 10733 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10734 // FIXME: This makes sure that we ignore the contexts associated 10735 // with C structs, unions, and enums when looking for a matching 10736 // tag declaration or definition. See the similar lookup tweak 10737 // in Sema::LookupName; is there a better way to deal with this? 10738 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10739 SearchDC = SearchDC->getParent(); 10740 } 10741 } else if (S->isFunctionPrototypeScope()) { 10742 // If this is an enum declaration in function prototype scope, set its 10743 // initial context to the translation unit. 10744 // FIXME: [citation needed] 10745 SearchDC = Context.getTranslationUnitDecl(); 10746 } 10747 10748 if (Previous.isSingleResult() && 10749 Previous.getFoundDecl()->isTemplateParameter()) { 10750 // Maybe we will complain about the shadowed template parameter. 10751 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10752 // Just pretend that we didn't see the previous declaration. 10753 Previous.clear(); 10754 } 10755 10756 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10757 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10758 // This is a declaration of or a reference to "std::bad_alloc". 10759 isStdBadAlloc = true; 10760 10761 if (Previous.empty() && StdBadAlloc) { 10762 // std::bad_alloc has been implicitly declared (but made invisible to 10763 // name lookup). Fill in this implicit declaration as the previous 10764 // declaration, so that the declarations get chained appropriately. 10765 Previous.addDecl(getStdBadAlloc()); 10766 } 10767 } 10768 10769 // If we didn't find a previous declaration, and this is a reference 10770 // (or friend reference), move to the correct scope. In C++, we 10771 // also need to do a redeclaration lookup there, just in case 10772 // there's a shadow friend decl. 10773 if (Name && Previous.empty() && 10774 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10775 if (Invalid) goto CreateNewDecl; 10776 assert(SS.isEmpty()); 10777 10778 if (TUK == TUK_Reference) { 10779 // C++ [basic.scope.pdecl]p5: 10780 // -- for an elaborated-type-specifier of the form 10781 // 10782 // class-key identifier 10783 // 10784 // if the elaborated-type-specifier is used in the 10785 // decl-specifier-seq or parameter-declaration-clause of a 10786 // function defined in namespace scope, the identifier is 10787 // declared as a class-name in the namespace that contains 10788 // the declaration; otherwise, except as a friend 10789 // declaration, the identifier is declared in the smallest 10790 // non-class, non-function-prototype scope that contains the 10791 // declaration. 10792 // 10793 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10794 // C structs and unions. 10795 // 10796 // It is an error in C++ to declare (rather than define) an enum 10797 // type, including via an elaborated type specifier. We'll 10798 // diagnose that later; for now, declare the enum in the same 10799 // scope as we would have picked for any other tag type. 10800 // 10801 // GNU C also supports this behavior as part of its incomplete 10802 // enum types extension, while GNU C++ does not. 10803 // 10804 // Find the context where we'll be declaring the tag. 10805 // FIXME: We would like to maintain the current DeclContext as the 10806 // lexical context, 10807 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10808 SearchDC = SearchDC->getParent(); 10809 10810 // Find the scope where we'll be declaring the tag. 10811 while (S->isClassScope() || 10812 (getLangOpts().CPlusPlus && 10813 S->isFunctionPrototypeScope()) || 10814 ((S->getFlags() & Scope::DeclScope) == 0) || 10815 (S->getEntity() && S->getEntity()->isTransparentContext())) 10816 S = S->getParent(); 10817 } else { 10818 assert(TUK == TUK_Friend); 10819 // C++ [namespace.memdef]p3: 10820 // If a friend declaration in a non-local class first declares a 10821 // class or function, the friend class or function is a member of 10822 // the innermost enclosing namespace. 10823 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10824 } 10825 10826 // In C++, we need to do a redeclaration lookup to properly 10827 // diagnose some problems. 10828 if (getLangOpts().CPlusPlus) { 10829 Previous.setRedeclarationKind(ForRedeclaration); 10830 LookupQualifiedName(Previous, SearchDC); 10831 } 10832 } 10833 10834 if (!Previous.empty()) { 10835 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10836 NamedDecl *DirectPrevDecl = 10837 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10838 10839 // It's okay to have a tag decl in the same scope as a typedef 10840 // which hides a tag decl in the same scope. Finding this 10841 // insanity with a redeclaration lookup can only actually happen 10842 // in C++. 10843 // 10844 // This is also okay for elaborated-type-specifiers, which is 10845 // technically forbidden by the current standard but which is 10846 // okay according to the likely resolution of an open issue; 10847 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10848 if (getLangOpts().CPlusPlus) { 10849 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10850 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10851 TagDecl *Tag = TT->getDecl(); 10852 if (Tag->getDeclName() == Name && 10853 Tag->getDeclContext()->getRedeclContext() 10854 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10855 PrevDecl = Tag; 10856 Previous.clear(); 10857 Previous.addDecl(Tag); 10858 Previous.resolveKind(); 10859 } 10860 } 10861 } 10862 } 10863 10864 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10865 // If this is a use of a previous tag, or if the tag is already declared 10866 // in the same scope (so that the definition/declaration completes or 10867 // rementions the tag), reuse the decl. 10868 if (TUK == TUK_Reference || TUK == TUK_Friend || 10869 isDeclInScope(DirectPrevDecl, SearchDC, S, 10870 SS.isNotEmpty() || isExplicitSpecialization)) { 10871 // Make sure that this wasn't declared as an enum and now used as a 10872 // struct or something similar. 10873 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10874 TUK == TUK_Definition, KWLoc, 10875 *Name)) { 10876 bool SafeToContinue 10877 = (PrevTagDecl->getTagKind() != TTK_Enum && 10878 Kind != TTK_Enum); 10879 if (SafeToContinue) 10880 Diag(KWLoc, diag::err_use_with_wrong_tag) 10881 << Name 10882 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10883 PrevTagDecl->getKindName()); 10884 else 10885 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10886 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10887 10888 if (SafeToContinue) 10889 Kind = PrevTagDecl->getTagKind(); 10890 else { 10891 // Recover by making this an anonymous redefinition. 10892 Name = 0; 10893 Previous.clear(); 10894 Invalid = true; 10895 } 10896 } 10897 10898 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10899 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10900 10901 // If this is an elaborated-type-specifier for a scoped enumeration, 10902 // the 'class' keyword is not necessary and not permitted. 10903 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10904 if (ScopedEnum) 10905 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10906 << PrevEnum->isScoped() 10907 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10908 return PrevTagDecl; 10909 } 10910 10911 QualType EnumUnderlyingTy; 10912 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10913 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 10914 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10915 EnumUnderlyingTy = QualType(T, 0); 10916 10917 // All conflicts with previous declarations are recovered by 10918 // returning the previous declaration, unless this is a definition, 10919 // in which case we want the caller to bail out. 10920 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10921 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10922 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10923 } 10924 10925 // C++11 [class.mem]p1: 10926 // A member shall not be declared twice in the member-specification, 10927 // except that a nested class or member class template can be declared 10928 // and then later defined. 10929 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10930 S->isDeclScope(PrevDecl)) { 10931 Diag(NameLoc, diag::ext_member_redeclared); 10932 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10933 } 10934 10935 if (!Invalid) { 10936 // If this is a use, just return the declaration we found. 10937 10938 // FIXME: In the future, return a variant or some other clue 10939 // for the consumer of this Decl to know it doesn't own it. 10940 // For our current ASTs this shouldn't be a problem, but will 10941 // need to be changed with DeclGroups. 10942 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10943 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10944 return PrevTagDecl; 10945 10946 // Diagnose attempts to redefine a tag. 10947 if (TUK == TUK_Definition) { 10948 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10949 // If we're defining a specialization and the previous definition 10950 // is from an implicit instantiation, don't emit an error 10951 // here; we'll catch this in the general case below. 10952 bool IsExplicitSpecializationAfterInstantiation = false; 10953 if (isExplicitSpecialization) { 10954 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10955 IsExplicitSpecializationAfterInstantiation = 10956 RD->getTemplateSpecializationKind() != 10957 TSK_ExplicitSpecialization; 10958 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10959 IsExplicitSpecializationAfterInstantiation = 10960 ED->getTemplateSpecializationKind() != 10961 TSK_ExplicitSpecialization; 10962 } 10963 10964 if (!IsExplicitSpecializationAfterInstantiation) { 10965 // A redeclaration in function prototype scope in C isn't 10966 // visible elsewhere, so merely issue a warning. 10967 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10968 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10969 else 10970 Diag(NameLoc, diag::err_redefinition) << Name; 10971 Diag(Def->getLocation(), diag::note_previous_definition); 10972 // If this is a redefinition, recover by making this 10973 // struct be anonymous, which will make any later 10974 // references get the previous definition. 10975 Name = 0; 10976 Previous.clear(); 10977 Invalid = true; 10978 } 10979 } else { 10980 // If the type is currently being defined, complain 10981 // about a nested redefinition. 10982 const TagType *Tag 10983 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10984 if (Tag->isBeingDefined()) { 10985 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10986 Diag(PrevTagDecl->getLocation(), 10987 diag::note_previous_definition); 10988 Name = 0; 10989 Previous.clear(); 10990 Invalid = true; 10991 } 10992 } 10993 10994 // Okay, this is definition of a previously declared or referenced 10995 // tag PrevDecl. We're going to create a new Decl for it. 10996 } 10997 } 10998 // If we get here we have (another) forward declaration or we 10999 // have a definition. Just create a new decl. 11000 11001 } else { 11002 // If we get here, this is a definition of a new tag type in a nested 11003 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11004 // new decl/type. We set PrevDecl to NULL so that the entities 11005 // have distinct types. 11006 Previous.clear(); 11007 } 11008 // If we get here, we're going to create a new Decl. If PrevDecl 11009 // is non-NULL, it's a definition of the tag declared by 11010 // PrevDecl. If it's NULL, we have a new definition. 11011 11012 11013 // Otherwise, PrevDecl is not a tag, but was found with tag 11014 // lookup. This is only actually possible in C++, where a few 11015 // things like templates still live in the tag namespace. 11016 } else { 11017 // Use a better diagnostic if an elaborated-type-specifier 11018 // found the wrong kind of type on the first 11019 // (non-redeclaration) lookup. 11020 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11021 !Previous.isForRedeclaration()) { 11022 unsigned Kind = 0; 11023 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11024 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11025 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11026 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11027 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11028 Invalid = true; 11029 11030 // Otherwise, only diagnose if the declaration is in scope. 11031 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11032 SS.isNotEmpty() || isExplicitSpecialization)) { 11033 // do nothing 11034 11035 // Diagnose implicit declarations introduced by elaborated types. 11036 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11037 unsigned Kind = 0; 11038 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11039 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11040 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11041 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11042 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11043 Invalid = true; 11044 11045 // Otherwise it's a declaration. Call out a particularly common 11046 // case here. 11047 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11048 unsigned Kind = 0; 11049 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11050 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11051 << Name << Kind << TND->getUnderlyingType(); 11052 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11053 Invalid = true; 11054 11055 // Otherwise, diagnose. 11056 } else { 11057 // The tag name clashes with something else in the target scope, 11058 // issue an error and recover by making this tag be anonymous. 11059 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11060 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11061 Name = 0; 11062 Invalid = true; 11063 } 11064 11065 // The existing declaration isn't relevant to us; we're in a 11066 // new scope, so clear out the previous declaration. 11067 Previous.clear(); 11068 } 11069 } 11070 11071 CreateNewDecl: 11072 11073 TagDecl *PrevDecl = 0; 11074 if (Previous.isSingleResult()) 11075 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11076 11077 // If there is an identifier, use the location of the identifier as the 11078 // location of the decl, otherwise use the location of the struct/union 11079 // keyword. 11080 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11081 11082 // Otherwise, create a new declaration. If there is a previous 11083 // declaration of the same entity, the two will be linked via 11084 // PrevDecl. 11085 TagDecl *New; 11086 11087 bool IsForwardReference = false; 11088 if (Kind == TTK_Enum) { 11089 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11090 // enum X { A, B, C } D; D should chain to X. 11091 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11092 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11093 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11094 // If this is an undefined enum, warn. 11095 if (TUK != TUK_Definition && !Invalid) { 11096 TagDecl *Def; 11097 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11098 cast<EnumDecl>(New)->isFixed()) { 11099 // C++0x: 7.2p2: opaque-enum-declaration. 11100 // Conflicts are diagnosed above. Do nothing. 11101 } 11102 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11103 Diag(Loc, diag::ext_forward_ref_enum_def) 11104 << New; 11105 Diag(Def->getLocation(), diag::note_previous_definition); 11106 } else { 11107 unsigned DiagID = diag::ext_forward_ref_enum; 11108 if (getLangOpts().MSVCCompat) 11109 DiagID = diag::ext_ms_forward_ref_enum; 11110 else if (getLangOpts().CPlusPlus) 11111 DiagID = diag::err_forward_ref_enum; 11112 Diag(Loc, DiagID); 11113 11114 // If this is a forward-declared reference to an enumeration, make a 11115 // note of it; we won't actually be introducing the declaration into 11116 // the declaration context. 11117 if (TUK == TUK_Reference) 11118 IsForwardReference = true; 11119 } 11120 } 11121 11122 if (EnumUnderlying) { 11123 EnumDecl *ED = cast<EnumDecl>(New); 11124 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11125 ED->setIntegerTypeSourceInfo(TI); 11126 else 11127 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11128 ED->setPromotionType(ED->getIntegerType()); 11129 } 11130 11131 } else { 11132 // struct/union/class 11133 11134 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11135 // struct X { int A; } D; D should chain to X. 11136 if (getLangOpts().CPlusPlus) { 11137 // FIXME: Look for a way to use RecordDecl for simple structs. 11138 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11139 cast_or_null<CXXRecordDecl>(PrevDecl)); 11140 11141 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11142 StdBadAlloc = cast<CXXRecordDecl>(New); 11143 } else 11144 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11145 cast_or_null<RecordDecl>(PrevDecl)); 11146 } 11147 11148 // C++11 [dcl.type]p3: 11149 // A type-specifier-seq shall not define a class or enumeration [...]. 11150 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11151 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11152 << Context.getTagDeclType(New); 11153 Invalid = true; 11154 } 11155 11156 // Maybe add qualifier info. 11157 if (SS.isNotEmpty()) { 11158 if (SS.isSet()) { 11159 // If this is either a declaration or a definition, check the 11160 // nested-name-specifier against the current context. We don't do this 11161 // for explicit specializations, because they have similar checking 11162 // (with more specific diagnostics) in the call to 11163 // CheckMemberSpecialization, below. 11164 if (!isExplicitSpecialization && 11165 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11166 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11167 Invalid = true; 11168 11169 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11170 if (TemplateParameterLists.size() > 0) { 11171 New->setTemplateParameterListsInfo(Context, 11172 TemplateParameterLists.size(), 11173 TemplateParameterLists.data()); 11174 } 11175 } 11176 else 11177 Invalid = true; 11178 } 11179 11180 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11181 // Add alignment attributes if necessary; these attributes are checked when 11182 // the ASTContext lays out the structure. 11183 // 11184 // It is important for implementing the correct semantics that this 11185 // happen here (in act on tag decl). The #pragma pack stack is 11186 // maintained as a result of parser callbacks which can occur at 11187 // many points during the parsing of a struct declaration (because 11188 // the #pragma tokens are effectively skipped over during the 11189 // parsing of the struct). 11190 if (TUK == TUK_Definition) { 11191 AddAlignmentAttributesForRecord(RD); 11192 AddMsStructLayoutForRecord(RD); 11193 } 11194 } 11195 11196 if (ModulePrivateLoc.isValid()) { 11197 if (isExplicitSpecialization) 11198 Diag(New->getLocation(), diag::err_module_private_specialization) 11199 << 2 11200 << FixItHint::CreateRemoval(ModulePrivateLoc); 11201 // __module_private__ does not apply to local classes. However, we only 11202 // diagnose this as an error when the declaration specifiers are 11203 // freestanding. Here, we just ignore the __module_private__. 11204 else if (!SearchDC->isFunctionOrMethod()) 11205 New->setModulePrivate(); 11206 } 11207 11208 // If this is a specialization of a member class (of a class template), 11209 // check the specialization. 11210 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11211 Invalid = true; 11212 11213 if (Invalid) 11214 New->setInvalidDecl(); 11215 11216 if (Attr) 11217 ProcessDeclAttributeList(S, New, Attr); 11218 11219 // If we're declaring or defining a tag in function prototype scope in C, 11220 // note that this type can only be used within the function and add it to 11221 // the list of decls to inject into the function definition scope. 11222 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) && 11223 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11224 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11225 DeclsInPrototypeScope.push_back(New); 11226 } 11227 11228 // Set the lexical context. If the tag has a C++ scope specifier, the 11229 // lexical context will be different from the semantic context. 11230 New->setLexicalDeclContext(CurContext); 11231 11232 // Mark this as a friend decl if applicable. 11233 // In Microsoft mode, a friend declaration also acts as a forward 11234 // declaration so we always pass true to setObjectOfFriendDecl to make 11235 // the tag name visible. 11236 if (TUK == TUK_Friend) 11237 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11238 getLangOpts().MicrosoftExt); 11239 11240 // Set the access specifier. 11241 if (!Invalid && SearchDC->isRecord()) 11242 SetMemberAccessSpecifier(New, PrevDecl, AS); 11243 11244 if (TUK == TUK_Definition) 11245 New->startDefinition(); 11246 11247 // If this has an identifier, add it to the scope stack. 11248 if (TUK == TUK_Friend) { 11249 // We might be replacing an existing declaration in the lookup tables; 11250 // if so, borrow its access specifier. 11251 if (PrevDecl) 11252 New->setAccess(PrevDecl->getAccess()); 11253 11254 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11255 DC->makeDeclVisibleInContext(New); 11256 if (Name) // can be null along some error paths 11257 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11258 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11259 } else if (Name) { 11260 S = getNonFieldDeclScope(S); 11261 PushOnScopeChains(New, S, !IsForwardReference); 11262 if (IsForwardReference) 11263 SearchDC->makeDeclVisibleInContext(New); 11264 11265 } else { 11266 CurContext->addDecl(New); 11267 } 11268 11269 // If this is the C FILE type, notify the AST context. 11270 if (IdentifierInfo *II = New->getIdentifier()) 11271 if (!New->isInvalidDecl() && 11272 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11273 II->isStr("FILE")) 11274 Context.setFILEDecl(New); 11275 11276 if (PrevDecl) 11277 mergeDeclAttributes(New, PrevDecl); 11278 11279 // If there's a #pragma GCC visibility in scope, set the visibility of this 11280 // record. 11281 AddPushedVisibilityAttribute(New); 11282 11283 OwnedDecl = true; 11284 // In C++, don't return an invalid declaration. We can't recover well from 11285 // the cases where we make the type anonymous. 11286 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11287 } 11288 11289 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11290 AdjustDeclIfTemplate(TagD); 11291 TagDecl *Tag = cast<TagDecl>(TagD); 11292 11293 // Enter the tag context. 11294 PushDeclContext(S, Tag); 11295 11296 ActOnDocumentableDecl(TagD); 11297 11298 // If there's a #pragma GCC visibility in scope, set the visibility of this 11299 // record. 11300 AddPushedVisibilityAttribute(Tag); 11301 } 11302 11303 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11304 assert(isa<ObjCContainerDecl>(IDecl) && 11305 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11306 DeclContext *OCD = cast<DeclContext>(IDecl); 11307 assert(getContainingDC(OCD) == CurContext && 11308 "The next DeclContext should be lexically contained in the current one."); 11309 CurContext = OCD; 11310 return IDecl; 11311 } 11312 11313 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11314 SourceLocation FinalLoc, 11315 bool IsFinalSpelledSealed, 11316 SourceLocation LBraceLoc) { 11317 AdjustDeclIfTemplate(TagD); 11318 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11319 11320 FieldCollector->StartClass(); 11321 11322 if (!Record->getIdentifier()) 11323 return; 11324 11325 if (FinalLoc.isValid()) 11326 Record->addAttr(new (Context) 11327 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11328 11329 // C++ [class]p2: 11330 // [...] The class-name is also inserted into the scope of the 11331 // class itself; this is known as the injected-class-name. For 11332 // purposes of access checking, the injected-class-name is treated 11333 // as if it were a public member name. 11334 CXXRecordDecl *InjectedClassName 11335 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11336 Record->getLocStart(), Record->getLocation(), 11337 Record->getIdentifier(), 11338 /*PrevDecl=*/0, 11339 /*DelayTypeCreation=*/true); 11340 Context.getTypeDeclType(InjectedClassName, Record); 11341 InjectedClassName->setImplicit(); 11342 InjectedClassName->setAccess(AS_public); 11343 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11344 InjectedClassName->setDescribedClassTemplate(Template); 11345 PushOnScopeChains(InjectedClassName, S); 11346 assert(InjectedClassName->isInjectedClassName() && 11347 "Broken injected-class-name"); 11348 } 11349 11350 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11351 SourceLocation RBraceLoc) { 11352 AdjustDeclIfTemplate(TagD); 11353 TagDecl *Tag = cast<TagDecl>(TagD); 11354 Tag->setRBraceLoc(RBraceLoc); 11355 11356 // Make sure we "complete" the definition even it is invalid. 11357 if (Tag->isBeingDefined()) { 11358 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11359 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11360 RD->completeDefinition(); 11361 } 11362 11363 if (isa<CXXRecordDecl>(Tag)) 11364 FieldCollector->FinishClass(); 11365 11366 // Exit this scope of this tag's definition. 11367 PopDeclContext(); 11368 11369 if (getCurLexicalContext()->isObjCContainer() && 11370 Tag->getDeclContext()->isFileContext()) 11371 Tag->setTopLevelDeclInObjCContainer(); 11372 11373 // Notify the consumer that we've defined a tag. 11374 if (!Tag->isInvalidDecl()) 11375 Consumer.HandleTagDeclDefinition(Tag); 11376 } 11377 11378 void Sema::ActOnObjCContainerFinishDefinition() { 11379 // Exit this scope of this interface definition. 11380 PopDeclContext(); 11381 } 11382 11383 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11384 assert(DC == CurContext && "Mismatch of container contexts"); 11385 OriginalLexicalContext = DC; 11386 ActOnObjCContainerFinishDefinition(); 11387 } 11388 11389 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11390 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11391 OriginalLexicalContext = 0; 11392 } 11393 11394 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11395 AdjustDeclIfTemplate(TagD); 11396 TagDecl *Tag = cast<TagDecl>(TagD); 11397 Tag->setInvalidDecl(); 11398 11399 // Make sure we "complete" the definition even it is invalid. 11400 if (Tag->isBeingDefined()) { 11401 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11402 RD->completeDefinition(); 11403 } 11404 11405 // We're undoing ActOnTagStartDefinition here, not 11406 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11407 // the FieldCollector. 11408 11409 PopDeclContext(); 11410 } 11411 11412 // Note that FieldName may be null for anonymous bitfields. 11413 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11414 IdentifierInfo *FieldName, 11415 QualType FieldTy, bool IsMsStruct, 11416 Expr *BitWidth, bool *ZeroWidth) { 11417 // Default to true; that shouldn't confuse checks for emptiness 11418 if (ZeroWidth) 11419 *ZeroWidth = true; 11420 11421 // C99 6.7.2.1p4 - verify the field type. 11422 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11423 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11424 // Handle incomplete types with specific error. 11425 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11426 return ExprError(); 11427 if (FieldName) 11428 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11429 << FieldName << FieldTy << BitWidth->getSourceRange(); 11430 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11431 << FieldTy << BitWidth->getSourceRange(); 11432 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11433 UPPC_BitFieldWidth)) 11434 return ExprError(); 11435 11436 // If the bit-width is type- or value-dependent, don't try to check 11437 // it now. 11438 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11439 return Owned(BitWidth); 11440 11441 llvm::APSInt Value; 11442 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11443 if (ICE.isInvalid()) 11444 return ICE; 11445 BitWidth = ICE.take(); 11446 11447 if (Value != 0 && ZeroWidth) 11448 *ZeroWidth = false; 11449 11450 // Zero-width bitfield is ok for anonymous field. 11451 if (Value == 0 && FieldName) 11452 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11453 11454 if (Value.isSigned() && Value.isNegative()) { 11455 if (FieldName) 11456 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11457 << FieldName << Value.toString(10); 11458 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11459 << Value.toString(10); 11460 } 11461 11462 if (!FieldTy->isDependentType()) { 11463 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11464 if (Value.getZExtValue() > TypeSize) { 11465 if (!getLangOpts().CPlusPlus || IsMsStruct || 11466 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11467 if (FieldName) 11468 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11469 << FieldName << (unsigned)Value.getZExtValue() 11470 << (unsigned)TypeSize; 11471 11472 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11473 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11474 } 11475 11476 if (FieldName) 11477 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11478 << FieldName << (unsigned)Value.getZExtValue() 11479 << (unsigned)TypeSize; 11480 else 11481 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11482 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11483 } 11484 } 11485 11486 return Owned(BitWidth); 11487 } 11488 11489 /// ActOnField - Each field of a C struct/union is passed into this in order 11490 /// to create a FieldDecl object for it. 11491 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11492 Declarator &D, Expr *BitfieldWidth) { 11493 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11494 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11495 /*InitStyle=*/ICIS_NoInit, AS_public); 11496 return Res; 11497 } 11498 11499 /// HandleField - Analyze a field of a C struct or a C++ data member. 11500 /// 11501 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11502 SourceLocation DeclStart, 11503 Declarator &D, Expr *BitWidth, 11504 InClassInitStyle InitStyle, 11505 AccessSpecifier AS) { 11506 IdentifierInfo *II = D.getIdentifier(); 11507 SourceLocation Loc = DeclStart; 11508 if (II) Loc = D.getIdentifierLoc(); 11509 11510 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11511 QualType T = TInfo->getType(); 11512 if (getLangOpts().CPlusPlus) { 11513 CheckExtraCXXDefaultArguments(D); 11514 11515 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11516 UPPC_DataMemberType)) { 11517 D.setInvalidType(); 11518 T = Context.IntTy; 11519 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11520 } 11521 } 11522 11523 // TR 18037 does not allow fields to be declared with address spaces. 11524 if (T.getQualifiers().hasAddressSpace()) { 11525 Diag(Loc, diag::err_field_with_address_space); 11526 D.setInvalidType(); 11527 } 11528 11529 // OpenCL 1.2 spec, s6.9 r: 11530 // The event type cannot be used to declare a structure or union field. 11531 if (LangOpts.OpenCL && T->isEventT()) { 11532 Diag(Loc, diag::err_event_t_struct_field); 11533 D.setInvalidType(); 11534 } 11535 11536 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11537 11538 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11539 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11540 diag::err_invalid_thread) 11541 << DeclSpec::getSpecifierName(TSCS); 11542 11543 // Check to see if this name was declared as a member previously 11544 NamedDecl *PrevDecl = 0; 11545 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11546 LookupName(Previous, S); 11547 switch (Previous.getResultKind()) { 11548 case LookupResult::Found: 11549 case LookupResult::FoundUnresolvedValue: 11550 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11551 break; 11552 11553 case LookupResult::FoundOverloaded: 11554 PrevDecl = Previous.getRepresentativeDecl(); 11555 break; 11556 11557 case LookupResult::NotFound: 11558 case LookupResult::NotFoundInCurrentInstantiation: 11559 case LookupResult::Ambiguous: 11560 break; 11561 } 11562 Previous.suppressDiagnostics(); 11563 11564 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11565 // Maybe we will complain about the shadowed template parameter. 11566 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11567 // Just pretend that we didn't see the previous declaration. 11568 PrevDecl = 0; 11569 } 11570 11571 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11572 PrevDecl = 0; 11573 11574 bool Mutable 11575 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11576 SourceLocation TSSL = D.getLocStart(); 11577 FieldDecl *NewFD 11578 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11579 TSSL, AS, PrevDecl, &D); 11580 11581 if (NewFD->isInvalidDecl()) 11582 Record->setInvalidDecl(); 11583 11584 if (D.getDeclSpec().isModulePrivateSpecified()) 11585 NewFD->setModulePrivate(); 11586 11587 if (NewFD->isInvalidDecl() && PrevDecl) { 11588 // Don't introduce NewFD into scope; there's already something 11589 // with the same name in the same scope. 11590 } else if (II) { 11591 PushOnScopeChains(NewFD, S); 11592 } else 11593 Record->addDecl(NewFD); 11594 11595 return NewFD; 11596 } 11597 11598 /// \brief Build a new FieldDecl and check its well-formedness. 11599 /// 11600 /// This routine builds a new FieldDecl given the fields name, type, 11601 /// record, etc. \p PrevDecl should refer to any previous declaration 11602 /// with the same name and in the same scope as the field to be 11603 /// created. 11604 /// 11605 /// \returns a new FieldDecl. 11606 /// 11607 /// \todo The Declarator argument is a hack. It will be removed once 11608 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11609 TypeSourceInfo *TInfo, 11610 RecordDecl *Record, SourceLocation Loc, 11611 bool Mutable, Expr *BitWidth, 11612 InClassInitStyle InitStyle, 11613 SourceLocation TSSL, 11614 AccessSpecifier AS, NamedDecl *PrevDecl, 11615 Declarator *D) { 11616 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11617 bool InvalidDecl = false; 11618 if (D) InvalidDecl = D->isInvalidType(); 11619 11620 // If we receive a broken type, recover by assuming 'int' and 11621 // marking this declaration as invalid. 11622 if (T.isNull()) { 11623 InvalidDecl = true; 11624 T = Context.IntTy; 11625 } 11626 11627 QualType EltTy = Context.getBaseElementType(T); 11628 if (!EltTy->isDependentType()) { 11629 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11630 // Fields of incomplete type force their record to be invalid. 11631 Record->setInvalidDecl(); 11632 InvalidDecl = true; 11633 } else { 11634 NamedDecl *Def; 11635 EltTy->isIncompleteType(&Def); 11636 if (Def && Def->isInvalidDecl()) { 11637 Record->setInvalidDecl(); 11638 InvalidDecl = true; 11639 } 11640 } 11641 } 11642 11643 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11644 if (BitWidth && getLangOpts().OpenCL) { 11645 Diag(Loc, diag::err_opencl_bitfields); 11646 InvalidDecl = true; 11647 } 11648 11649 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11650 // than a variably modified type. 11651 if (!InvalidDecl && T->isVariablyModifiedType()) { 11652 bool SizeIsNegative; 11653 llvm::APSInt Oversized; 11654 11655 TypeSourceInfo *FixedTInfo = 11656 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11657 SizeIsNegative, 11658 Oversized); 11659 if (FixedTInfo) { 11660 Diag(Loc, diag::warn_illegal_constant_array_size); 11661 TInfo = FixedTInfo; 11662 T = FixedTInfo->getType(); 11663 } else { 11664 if (SizeIsNegative) 11665 Diag(Loc, diag::err_typecheck_negative_array_size); 11666 else if (Oversized.getBoolValue()) 11667 Diag(Loc, diag::err_array_too_large) 11668 << Oversized.toString(10); 11669 else 11670 Diag(Loc, diag::err_typecheck_field_variable_size); 11671 InvalidDecl = true; 11672 } 11673 } 11674 11675 // Fields can not have abstract class types 11676 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11677 diag::err_abstract_type_in_decl, 11678 AbstractFieldType)) 11679 InvalidDecl = true; 11680 11681 bool ZeroWidth = false; 11682 // If this is declared as a bit-field, check the bit-field. 11683 if (!InvalidDecl && BitWidth) { 11684 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11685 &ZeroWidth).take(); 11686 if (!BitWidth) { 11687 InvalidDecl = true; 11688 BitWidth = 0; 11689 ZeroWidth = false; 11690 } 11691 } 11692 11693 // Check that 'mutable' is consistent with the type of the declaration. 11694 if (!InvalidDecl && Mutable) { 11695 unsigned DiagID = 0; 11696 if (T->isReferenceType()) 11697 DiagID = diag::err_mutable_reference; 11698 else if (T.isConstQualified()) 11699 DiagID = diag::err_mutable_const; 11700 11701 if (DiagID) { 11702 SourceLocation ErrLoc = Loc; 11703 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11704 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11705 Diag(ErrLoc, DiagID); 11706 Mutable = false; 11707 InvalidDecl = true; 11708 } 11709 } 11710 11711 // C++11 [class.union]p8 (DR1460): 11712 // At most one variant member of a union may have a 11713 // brace-or-equal-initializer. 11714 if (InitStyle != ICIS_NoInit) 11715 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11716 11717 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11718 BitWidth, Mutable, InitStyle); 11719 if (InvalidDecl) 11720 NewFD->setInvalidDecl(); 11721 11722 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11723 Diag(Loc, diag::err_duplicate_member) << II; 11724 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11725 NewFD->setInvalidDecl(); 11726 } 11727 11728 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11729 if (Record->isUnion()) { 11730 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11731 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11732 if (RDecl->getDefinition()) { 11733 // C++ [class.union]p1: An object of a class with a non-trivial 11734 // constructor, a non-trivial copy constructor, a non-trivial 11735 // destructor, or a non-trivial copy assignment operator 11736 // cannot be a member of a union, nor can an array of such 11737 // objects. 11738 if (CheckNontrivialField(NewFD)) 11739 NewFD->setInvalidDecl(); 11740 } 11741 } 11742 11743 // C++ [class.union]p1: If a union contains a member of reference type, 11744 // the program is ill-formed, except when compiling with MSVC extensions 11745 // enabled. 11746 if (EltTy->isReferenceType()) { 11747 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11748 diag::ext_union_member_of_reference_type : 11749 diag::err_union_member_of_reference_type) 11750 << NewFD->getDeclName() << EltTy; 11751 if (!getLangOpts().MicrosoftExt) 11752 NewFD->setInvalidDecl(); 11753 } 11754 } 11755 } 11756 11757 // FIXME: We need to pass in the attributes given an AST 11758 // representation, not a parser representation. 11759 if (D) { 11760 // FIXME: The current scope is almost... but not entirely... correct here. 11761 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11762 11763 if (NewFD->hasAttrs()) 11764 CheckAlignasUnderalignment(NewFD); 11765 } 11766 11767 // In auto-retain/release, infer strong retension for fields of 11768 // retainable type. 11769 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11770 NewFD->setInvalidDecl(); 11771 11772 if (T.isObjCGCWeak()) 11773 Diag(Loc, diag::warn_attribute_weak_on_field); 11774 11775 NewFD->setAccess(AS); 11776 return NewFD; 11777 } 11778 11779 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11780 assert(FD); 11781 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11782 11783 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11784 return false; 11785 11786 QualType EltTy = Context.getBaseElementType(FD->getType()); 11787 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11788 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11789 if (RDecl->getDefinition()) { 11790 // We check for copy constructors before constructors 11791 // because otherwise we'll never get complaints about 11792 // copy constructors. 11793 11794 CXXSpecialMember member = CXXInvalid; 11795 // We're required to check for any non-trivial constructors. Since the 11796 // implicit default constructor is suppressed if there are any 11797 // user-declared constructors, we just need to check that there is a 11798 // trivial default constructor and a trivial copy constructor. (We don't 11799 // worry about move constructors here, since this is a C++98 check.) 11800 if (RDecl->hasNonTrivialCopyConstructor()) 11801 member = CXXCopyConstructor; 11802 else if (!RDecl->hasTrivialDefaultConstructor()) 11803 member = CXXDefaultConstructor; 11804 else if (RDecl->hasNonTrivialCopyAssignment()) 11805 member = CXXCopyAssignment; 11806 else if (RDecl->hasNonTrivialDestructor()) 11807 member = CXXDestructor; 11808 11809 if (member != CXXInvalid) { 11810 if (!getLangOpts().CPlusPlus11 && 11811 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11812 // Objective-C++ ARC: it is an error to have a non-trivial field of 11813 // a union. However, system headers in Objective-C programs 11814 // occasionally have Objective-C lifetime objects within unions, 11815 // and rather than cause the program to fail, we make those 11816 // members unavailable. 11817 SourceLocation Loc = FD->getLocation(); 11818 if (getSourceManager().isInSystemHeader(Loc)) { 11819 if (!FD->hasAttr<UnavailableAttr>()) 11820 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11821 "this system field has retaining ownership", 11822 Loc)); 11823 return false; 11824 } 11825 } 11826 11827 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11828 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11829 diag::err_illegal_union_or_anon_struct_member) 11830 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11831 DiagnoseNontrivial(RDecl, member); 11832 return !getLangOpts().CPlusPlus11; 11833 } 11834 } 11835 } 11836 11837 return false; 11838 } 11839 11840 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11841 /// AST enum value. 11842 static ObjCIvarDecl::AccessControl 11843 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11844 switch (ivarVisibility) { 11845 default: llvm_unreachable("Unknown visitibility kind"); 11846 case tok::objc_private: return ObjCIvarDecl::Private; 11847 case tok::objc_public: return ObjCIvarDecl::Public; 11848 case tok::objc_protected: return ObjCIvarDecl::Protected; 11849 case tok::objc_package: return ObjCIvarDecl::Package; 11850 } 11851 } 11852 11853 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11854 /// in order to create an IvarDecl object for it. 11855 Decl *Sema::ActOnIvar(Scope *S, 11856 SourceLocation DeclStart, 11857 Declarator &D, Expr *BitfieldWidth, 11858 tok::ObjCKeywordKind Visibility) { 11859 11860 IdentifierInfo *II = D.getIdentifier(); 11861 Expr *BitWidth = (Expr*)BitfieldWidth; 11862 SourceLocation Loc = DeclStart; 11863 if (II) Loc = D.getIdentifierLoc(); 11864 11865 // FIXME: Unnamed fields can be handled in various different ways, for 11866 // example, unnamed unions inject all members into the struct namespace! 11867 11868 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11869 QualType T = TInfo->getType(); 11870 11871 if (BitWidth) { 11872 // 6.7.2.1p3, 6.7.2.1p4 11873 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11874 if (!BitWidth) 11875 D.setInvalidType(); 11876 } else { 11877 // Not a bitfield. 11878 11879 // validate II. 11880 11881 } 11882 if (T->isReferenceType()) { 11883 Diag(Loc, diag::err_ivar_reference_type); 11884 D.setInvalidType(); 11885 } 11886 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11887 // than a variably modified type. 11888 else if (T->isVariablyModifiedType()) { 11889 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11890 D.setInvalidType(); 11891 } 11892 11893 // Get the visibility (access control) for this ivar. 11894 ObjCIvarDecl::AccessControl ac = 11895 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11896 : ObjCIvarDecl::None; 11897 // Must set ivar's DeclContext to its enclosing interface. 11898 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11899 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11900 return 0; 11901 ObjCContainerDecl *EnclosingContext; 11902 if (ObjCImplementationDecl *IMPDecl = 11903 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11904 if (LangOpts.ObjCRuntime.isFragile()) { 11905 // Case of ivar declared in an implementation. Context is that of its class. 11906 EnclosingContext = IMPDecl->getClassInterface(); 11907 assert(EnclosingContext && "Implementation has no class interface!"); 11908 } 11909 else 11910 EnclosingContext = EnclosingDecl; 11911 } else { 11912 if (ObjCCategoryDecl *CDecl = 11913 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11914 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11915 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11916 return 0; 11917 } 11918 } 11919 EnclosingContext = EnclosingDecl; 11920 } 11921 11922 // Construct the decl. 11923 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11924 DeclStart, Loc, II, T, 11925 TInfo, ac, (Expr *)BitfieldWidth); 11926 11927 if (II) { 11928 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11929 ForRedeclaration); 11930 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11931 && !isa<TagDecl>(PrevDecl)) { 11932 Diag(Loc, diag::err_duplicate_member) << II; 11933 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11934 NewID->setInvalidDecl(); 11935 } 11936 } 11937 11938 // Process attributes attached to the ivar. 11939 ProcessDeclAttributes(S, NewID, D); 11940 11941 if (D.isInvalidType()) 11942 NewID->setInvalidDecl(); 11943 11944 // In ARC, infer 'retaining' for ivars of retainable type. 11945 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11946 NewID->setInvalidDecl(); 11947 11948 if (D.getDeclSpec().isModulePrivateSpecified()) 11949 NewID->setModulePrivate(); 11950 11951 if (II) { 11952 // FIXME: When interfaces are DeclContexts, we'll need to add 11953 // these to the interface. 11954 S->AddDecl(NewID); 11955 IdResolver.AddDecl(NewID); 11956 } 11957 11958 if (LangOpts.ObjCRuntime.isNonFragile() && 11959 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11960 Diag(Loc, diag::warn_ivars_in_interface); 11961 11962 return NewID; 11963 } 11964 11965 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11966 /// class and class extensions. For every class \@interface and class 11967 /// extension \@interface, if the last ivar is a bitfield of any type, 11968 /// then add an implicit `char :0` ivar to the end of that interface. 11969 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11970 SmallVectorImpl<Decl *> &AllIvarDecls) { 11971 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11972 return; 11973 11974 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11975 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11976 11977 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11978 return; 11979 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11980 if (!ID) { 11981 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11982 if (!CD->IsClassExtension()) 11983 return; 11984 } 11985 // No need to add this to end of @implementation. 11986 else 11987 return; 11988 } 11989 // All conditions are met. Add a new bitfield to the tail end of ivars. 11990 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11991 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11992 11993 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11994 DeclLoc, DeclLoc, 0, 11995 Context.CharTy, 11996 Context.getTrivialTypeSourceInfo(Context.CharTy, 11997 DeclLoc), 11998 ObjCIvarDecl::Private, BW, 11999 true); 12000 AllIvarDecls.push_back(Ivar); 12001 } 12002 12003 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12004 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12005 SourceLocation RBrac, AttributeList *Attr) { 12006 assert(EnclosingDecl && "missing record or interface decl"); 12007 12008 // If this is an Objective-C @implementation or category and we have 12009 // new fields here we should reset the layout of the interface since 12010 // it will now change. 12011 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12012 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12013 switch (DC->getKind()) { 12014 default: break; 12015 case Decl::ObjCCategory: 12016 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12017 break; 12018 case Decl::ObjCImplementation: 12019 Context. 12020 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12021 break; 12022 } 12023 } 12024 12025 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12026 12027 // Start counting up the number of named members; make sure to include 12028 // members of anonymous structs and unions in the total. 12029 unsigned NumNamedMembers = 0; 12030 if (Record) { 12031 for (const auto *I : Record->decls()) { 12032 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12033 if (IFD->getDeclName()) 12034 ++NumNamedMembers; 12035 } 12036 } 12037 12038 // Verify that all the fields are okay. 12039 SmallVector<FieldDecl*, 32> RecFields; 12040 12041 bool ARCErrReported = false; 12042 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12043 i != end; ++i) { 12044 FieldDecl *FD = cast<FieldDecl>(*i); 12045 12046 // Get the type for the field. 12047 const Type *FDTy = FD->getType().getTypePtr(); 12048 12049 if (!FD->isAnonymousStructOrUnion()) { 12050 // Remember all fields written by the user. 12051 RecFields.push_back(FD); 12052 } 12053 12054 // If the field is already invalid for some reason, don't emit more 12055 // diagnostics about it. 12056 if (FD->isInvalidDecl()) { 12057 EnclosingDecl->setInvalidDecl(); 12058 continue; 12059 } 12060 12061 // C99 6.7.2.1p2: 12062 // A structure or union shall not contain a member with 12063 // incomplete or function type (hence, a structure shall not 12064 // contain an instance of itself, but may contain a pointer to 12065 // an instance of itself), except that the last member of a 12066 // structure with more than one named member may have incomplete 12067 // array type; such a structure (and any union containing, 12068 // possibly recursively, a member that is such a structure) 12069 // shall not be a member of a structure or an element of an 12070 // array. 12071 if (FDTy->isFunctionType()) { 12072 // Field declared as a function. 12073 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12074 << FD->getDeclName(); 12075 FD->setInvalidDecl(); 12076 EnclosingDecl->setInvalidDecl(); 12077 continue; 12078 } else if (FDTy->isIncompleteArrayType() && Record && 12079 ((i + 1 == Fields.end() && !Record->isUnion()) || 12080 ((getLangOpts().MicrosoftExt || 12081 getLangOpts().CPlusPlus) && 12082 (i + 1 == Fields.end() || Record->isUnion())))) { 12083 // Flexible array member. 12084 // Microsoft and g++ is more permissive regarding flexible array. 12085 // It will accept flexible array in union and also 12086 // as the sole element of a struct/class. 12087 unsigned DiagID = 0; 12088 if (Record->isUnion()) 12089 DiagID = getLangOpts().MicrosoftExt 12090 ? diag::ext_flexible_array_union_ms 12091 : getLangOpts().CPlusPlus 12092 ? diag::ext_flexible_array_union_gnu 12093 : diag::err_flexible_array_union; 12094 else if (Fields.size() == 1) 12095 DiagID = getLangOpts().MicrosoftExt 12096 ? diag::ext_flexible_array_empty_aggregate_ms 12097 : getLangOpts().CPlusPlus 12098 ? diag::ext_flexible_array_empty_aggregate_gnu 12099 : NumNamedMembers < 1 12100 ? diag::err_flexible_array_empty_aggregate 12101 : 0; 12102 12103 if (DiagID) 12104 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12105 << Record->getTagKind(); 12106 // While the layout of types that contain virtual bases is not specified 12107 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12108 // virtual bases after the derived members. This would make a flexible 12109 // array member declared at the end of an object not adjacent to the end 12110 // of the type. 12111 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12112 if (RD->getNumVBases() != 0) 12113 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12114 << FD->getDeclName() << Record->getTagKind(); 12115 if (!getLangOpts().C99) 12116 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12117 << FD->getDeclName() << Record->getTagKind(); 12118 12119 // If the element type has a non-trivial destructor, we would not 12120 // implicitly destroy the elements, so disallow it for now. 12121 // 12122 // FIXME: GCC allows this. We should probably either implicitly delete 12123 // the destructor of the containing class, or just allow this. 12124 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12125 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12126 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12127 << FD->getDeclName() << FD->getType(); 12128 FD->setInvalidDecl(); 12129 EnclosingDecl->setInvalidDecl(); 12130 continue; 12131 } 12132 // Okay, we have a legal flexible array member at the end of the struct. 12133 if (Record) 12134 Record->setHasFlexibleArrayMember(true); 12135 } else if (!FDTy->isDependentType() && 12136 RequireCompleteType(FD->getLocation(), FD->getType(), 12137 diag::err_field_incomplete)) { 12138 // Incomplete type 12139 FD->setInvalidDecl(); 12140 EnclosingDecl->setInvalidDecl(); 12141 continue; 12142 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12143 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 12144 // If this is a member of a union, then entire union becomes "flexible". 12145 if (Record && Record->isUnion()) { 12146 Record->setHasFlexibleArrayMember(true); 12147 } else { 12148 // If this is a struct/class and this is not the last element, reject 12149 // it. Note that GCC supports variable sized arrays in the middle of 12150 // structures. 12151 if (i + 1 != Fields.end()) 12152 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12153 << FD->getDeclName() << FD->getType(); 12154 else { 12155 // We support flexible arrays at the end of structs in 12156 // other structs as an extension. 12157 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12158 << FD->getDeclName(); 12159 if (Record) 12160 Record->setHasFlexibleArrayMember(true); 12161 } 12162 } 12163 } 12164 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12165 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12166 diag::err_abstract_type_in_decl, 12167 AbstractIvarType)) { 12168 // Ivars can not have abstract class types 12169 FD->setInvalidDecl(); 12170 } 12171 if (Record && FDTTy->getDecl()->hasObjectMember()) 12172 Record->setHasObjectMember(true); 12173 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12174 Record->setHasVolatileMember(true); 12175 } else if (FDTy->isObjCObjectType()) { 12176 /// A field cannot be an Objective-c object 12177 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12178 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12179 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12180 FD->setType(T); 12181 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12182 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12183 // It's an error in ARC if a field has lifetime. 12184 // We don't want to report this in a system header, though, 12185 // so we just make the field unavailable. 12186 // FIXME: that's really not sufficient; we need to make the type 12187 // itself invalid to, say, initialize or copy. 12188 QualType T = FD->getType(); 12189 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12190 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12191 SourceLocation loc = FD->getLocation(); 12192 if (getSourceManager().isInSystemHeader(loc)) { 12193 if (!FD->hasAttr<UnavailableAttr>()) { 12194 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12195 "this system field has retaining ownership", 12196 loc)); 12197 } 12198 } else { 12199 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12200 << T->isBlockPointerType() << Record->getTagKind(); 12201 } 12202 ARCErrReported = true; 12203 } 12204 } else if (getLangOpts().ObjC1 && 12205 getLangOpts().getGC() != LangOptions::NonGC && 12206 Record && !Record->hasObjectMember()) { 12207 if (FD->getType()->isObjCObjectPointerType() || 12208 FD->getType().isObjCGCStrong()) 12209 Record->setHasObjectMember(true); 12210 else if (Context.getAsArrayType(FD->getType())) { 12211 QualType BaseType = Context.getBaseElementType(FD->getType()); 12212 if (BaseType->isRecordType() && 12213 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12214 Record->setHasObjectMember(true); 12215 else if (BaseType->isObjCObjectPointerType() || 12216 BaseType.isObjCGCStrong()) 12217 Record->setHasObjectMember(true); 12218 } 12219 } 12220 if (Record && FD->getType().isVolatileQualified()) 12221 Record->setHasVolatileMember(true); 12222 // Keep track of the number of named members. 12223 if (FD->getIdentifier()) 12224 ++NumNamedMembers; 12225 } 12226 12227 // Okay, we successfully defined 'Record'. 12228 if (Record) { 12229 bool Completed = false; 12230 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12231 if (!CXXRecord->isInvalidDecl()) { 12232 // Set access bits correctly on the directly-declared conversions. 12233 for (CXXRecordDecl::conversion_iterator 12234 I = CXXRecord->conversion_begin(), 12235 E = CXXRecord->conversion_end(); I != E; ++I) 12236 I.setAccess((*I)->getAccess()); 12237 12238 if (!CXXRecord->isDependentType()) { 12239 if (CXXRecord->hasUserDeclaredDestructor()) { 12240 // Adjust user-defined destructor exception spec. 12241 if (getLangOpts().CPlusPlus11) 12242 AdjustDestructorExceptionSpec(CXXRecord, 12243 CXXRecord->getDestructor()); 12244 } 12245 12246 // Add any implicitly-declared members to this class. 12247 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12248 12249 // If we have virtual base classes, we may end up finding multiple 12250 // final overriders for a given virtual function. Check for this 12251 // problem now. 12252 if (CXXRecord->getNumVBases()) { 12253 CXXFinalOverriderMap FinalOverriders; 12254 CXXRecord->getFinalOverriders(FinalOverriders); 12255 12256 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12257 MEnd = FinalOverriders.end(); 12258 M != MEnd; ++M) { 12259 for (OverridingMethods::iterator SO = M->second.begin(), 12260 SOEnd = M->second.end(); 12261 SO != SOEnd; ++SO) { 12262 assert(SO->second.size() > 0 && 12263 "Virtual function without overridding functions?"); 12264 if (SO->second.size() == 1) 12265 continue; 12266 12267 // C++ [class.virtual]p2: 12268 // In a derived class, if a virtual member function of a base 12269 // class subobject has more than one final overrider the 12270 // program is ill-formed. 12271 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12272 << (const NamedDecl *)M->first << Record; 12273 Diag(M->first->getLocation(), 12274 diag::note_overridden_virtual_function); 12275 for (OverridingMethods::overriding_iterator 12276 OM = SO->second.begin(), 12277 OMEnd = SO->second.end(); 12278 OM != OMEnd; ++OM) 12279 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12280 << (const NamedDecl *)M->first << OM->Method->getParent(); 12281 12282 Record->setInvalidDecl(); 12283 } 12284 } 12285 CXXRecord->completeDefinition(&FinalOverriders); 12286 Completed = true; 12287 } 12288 } 12289 } 12290 } 12291 12292 if (!Completed) 12293 Record->completeDefinition(); 12294 12295 if (Record->hasAttrs()) { 12296 CheckAlignasUnderalignment(Record); 12297 12298 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12299 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12300 IA->getRange(), IA->getBestCase(), 12301 IA->getSemanticSpelling()); 12302 } 12303 12304 // Check if the structure/union declaration is a type that can have zero 12305 // size in C. For C this is a language extension, for C++ it may cause 12306 // compatibility problems. 12307 bool CheckForZeroSize; 12308 if (!getLangOpts().CPlusPlus) { 12309 CheckForZeroSize = true; 12310 } else { 12311 // For C++ filter out types that cannot be referenced in C code. 12312 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12313 CheckForZeroSize = 12314 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12315 !CXXRecord->isDependentType() && 12316 CXXRecord->isCLike(); 12317 } 12318 if (CheckForZeroSize) { 12319 bool ZeroSize = true; 12320 bool IsEmpty = true; 12321 unsigned NonBitFields = 0; 12322 for (RecordDecl::field_iterator I = Record->field_begin(), 12323 E = Record->field_end(); 12324 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12325 IsEmpty = false; 12326 if (I->isUnnamedBitfield()) { 12327 if (I->getBitWidthValue(Context) > 0) 12328 ZeroSize = false; 12329 } else { 12330 ++NonBitFields; 12331 QualType FieldType = I->getType(); 12332 if (FieldType->isIncompleteType() || 12333 !Context.getTypeSizeInChars(FieldType).isZero()) 12334 ZeroSize = false; 12335 } 12336 } 12337 12338 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12339 // allowed in C++, but warn if its declaration is inside 12340 // extern "C" block. 12341 if (ZeroSize) { 12342 Diag(RecLoc, getLangOpts().CPlusPlus ? 12343 diag::warn_zero_size_struct_union_in_extern_c : 12344 diag::warn_zero_size_struct_union_compat) 12345 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12346 } 12347 12348 // Structs without named members are extension in C (C99 6.7.2.1p7), 12349 // but are accepted by GCC. 12350 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12351 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12352 diag::ext_no_named_members_in_struct_union) 12353 << Record->isUnion(); 12354 } 12355 } 12356 } else { 12357 ObjCIvarDecl **ClsFields = 12358 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12359 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12360 ID->setEndOfDefinitionLoc(RBrac); 12361 // Add ivar's to class's DeclContext. 12362 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12363 ClsFields[i]->setLexicalDeclContext(ID); 12364 ID->addDecl(ClsFields[i]); 12365 } 12366 // Must enforce the rule that ivars in the base classes may not be 12367 // duplicates. 12368 if (ID->getSuperClass()) 12369 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12370 } else if (ObjCImplementationDecl *IMPDecl = 12371 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12372 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12373 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12374 // Ivar declared in @implementation never belongs to the implementation. 12375 // Only it is in implementation's lexical context. 12376 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12377 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12378 IMPDecl->setIvarLBraceLoc(LBrac); 12379 IMPDecl->setIvarRBraceLoc(RBrac); 12380 } else if (ObjCCategoryDecl *CDecl = 12381 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12382 // case of ivars in class extension; all other cases have been 12383 // reported as errors elsewhere. 12384 // FIXME. Class extension does not have a LocEnd field. 12385 // CDecl->setLocEnd(RBrac); 12386 // Add ivar's to class extension's DeclContext. 12387 // Diagnose redeclaration of private ivars. 12388 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12389 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12390 if (IDecl) { 12391 if (const ObjCIvarDecl *ClsIvar = 12392 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12393 Diag(ClsFields[i]->getLocation(), 12394 diag::err_duplicate_ivar_declaration); 12395 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12396 continue; 12397 } 12398 for (const auto *Ext : IDecl->known_extensions()) { 12399 if (const ObjCIvarDecl *ClsExtIvar 12400 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12401 Diag(ClsFields[i]->getLocation(), 12402 diag::err_duplicate_ivar_declaration); 12403 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12404 continue; 12405 } 12406 } 12407 } 12408 ClsFields[i]->setLexicalDeclContext(CDecl); 12409 CDecl->addDecl(ClsFields[i]); 12410 } 12411 CDecl->setIvarLBraceLoc(LBrac); 12412 CDecl->setIvarRBraceLoc(RBrac); 12413 } 12414 } 12415 12416 if (Attr) 12417 ProcessDeclAttributeList(S, Record, Attr); 12418 } 12419 12420 /// \brief Determine whether the given integral value is representable within 12421 /// the given type T. 12422 static bool isRepresentableIntegerValue(ASTContext &Context, 12423 llvm::APSInt &Value, 12424 QualType T) { 12425 assert(T->isIntegralType(Context) && "Integral type required!"); 12426 unsigned BitWidth = Context.getIntWidth(T); 12427 12428 if (Value.isUnsigned() || Value.isNonNegative()) { 12429 if (T->isSignedIntegerOrEnumerationType()) 12430 --BitWidth; 12431 return Value.getActiveBits() <= BitWidth; 12432 } 12433 return Value.getMinSignedBits() <= BitWidth; 12434 } 12435 12436 // \brief Given an integral type, return the next larger integral type 12437 // (or a NULL type of no such type exists). 12438 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12439 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12440 // enum checking below. 12441 assert(T->isIntegralType(Context) && "Integral type required!"); 12442 const unsigned NumTypes = 4; 12443 QualType SignedIntegralTypes[NumTypes] = { 12444 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12445 }; 12446 QualType UnsignedIntegralTypes[NumTypes] = { 12447 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12448 Context.UnsignedLongLongTy 12449 }; 12450 12451 unsigned BitWidth = Context.getTypeSize(T); 12452 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12453 : UnsignedIntegralTypes; 12454 for (unsigned I = 0; I != NumTypes; ++I) 12455 if (Context.getTypeSize(Types[I]) > BitWidth) 12456 return Types[I]; 12457 12458 return QualType(); 12459 } 12460 12461 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12462 EnumConstantDecl *LastEnumConst, 12463 SourceLocation IdLoc, 12464 IdentifierInfo *Id, 12465 Expr *Val) { 12466 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12467 llvm::APSInt EnumVal(IntWidth); 12468 QualType EltTy; 12469 12470 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12471 Val = 0; 12472 12473 if (Val) 12474 Val = DefaultLvalueConversion(Val).take(); 12475 12476 if (Val) { 12477 if (Enum->isDependentType() || Val->isTypeDependent()) 12478 EltTy = Context.DependentTy; 12479 else { 12480 SourceLocation ExpLoc; 12481 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12482 !getLangOpts().MSVCCompat) { 12483 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12484 // constant-expression in the enumerator-definition shall be a converted 12485 // constant expression of the underlying type. 12486 EltTy = Enum->getIntegerType(); 12487 ExprResult Converted = 12488 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12489 CCEK_Enumerator); 12490 if (Converted.isInvalid()) 12491 Val = 0; 12492 else 12493 Val = Converted.take(); 12494 } else if (!Val->isValueDependent() && 12495 !(Val = VerifyIntegerConstantExpression(Val, 12496 &EnumVal).take())) { 12497 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12498 } else { 12499 if (Enum->isFixed()) { 12500 EltTy = Enum->getIntegerType(); 12501 12502 // In Obj-C and Microsoft mode, require the enumeration value to be 12503 // representable in the underlying type of the enumeration. In C++11, 12504 // we perform a non-narrowing conversion as part of converted constant 12505 // expression checking. 12506 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12507 if (getLangOpts().MSVCCompat) { 12508 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12509 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12510 } else 12511 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12512 } else 12513 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12514 } else if (getLangOpts().CPlusPlus) { 12515 // C++11 [dcl.enum]p5: 12516 // If the underlying type is not fixed, the type of each enumerator 12517 // is the type of its initializing value: 12518 // - If an initializer is specified for an enumerator, the 12519 // initializing value has the same type as the expression. 12520 EltTy = Val->getType(); 12521 } else { 12522 // C99 6.7.2.2p2: 12523 // The expression that defines the value of an enumeration constant 12524 // shall be an integer constant expression that has a value 12525 // representable as an int. 12526 12527 // Complain if the value is not representable in an int. 12528 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12529 Diag(IdLoc, diag::ext_enum_value_not_int) 12530 << EnumVal.toString(10) << Val->getSourceRange() 12531 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12532 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12533 // Force the type of the expression to 'int'. 12534 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12535 } 12536 EltTy = Val->getType(); 12537 } 12538 } 12539 } 12540 } 12541 12542 if (!Val) { 12543 if (Enum->isDependentType()) 12544 EltTy = Context.DependentTy; 12545 else if (!LastEnumConst) { 12546 // C++0x [dcl.enum]p5: 12547 // If the underlying type is not fixed, the type of each enumerator 12548 // is the type of its initializing value: 12549 // - If no initializer is specified for the first enumerator, the 12550 // initializing value has an unspecified integral type. 12551 // 12552 // GCC uses 'int' for its unspecified integral type, as does 12553 // C99 6.7.2.2p3. 12554 if (Enum->isFixed()) { 12555 EltTy = Enum->getIntegerType(); 12556 } 12557 else { 12558 EltTy = Context.IntTy; 12559 } 12560 } else { 12561 // Assign the last value + 1. 12562 EnumVal = LastEnumConst->getInitVal(); 12563 ++EnumVal; 12564 EltTy = LastEnumConst->getType(); 12565 12566 // Check for overflow on increment. 12567 if (EnumVal < LastEnumConst->getInitVal()) { 12568 // C++0x [dcl.enum]p5: 12569 // If the underlying type is not fixed, the type of each enumerator 12570 // is the type of its initializing value: 12571 // 12572 // - Otherwise the type of the initializing value is the same as 12573 // the type of the initializing value of the preceding enumerator 12574 // unless the incremented value is not representable in that type, 12575 // in which case the type is an unspecified integral type 12576 // sufficient to contain the incremented value. If no such type 12577 // exists, the program is ill-formed. 12578 QualType T = getNextLargerIntegralType(Context, EltTy); 12579 if (T.isNull() || Enum->isFixed()) { 12580 // There is no integral type larger enough to represent this 12581 // value. Complain, then allow the value to wrap around. 12582 EnumVal = LastEnumConst->getInitVal(); 12583 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12584 ++EnumVal; 12585 if (Enum->isFixed()) 12586 // When the underlying type is fixed, this is ill-formed. 12587 Diag(IdLoc, diag::err_enumerator_wrapped) 12588 << EnumVal.toString(10) 12589 << EltTy; 12590 else 12591 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 12592 << EnumVal.toString(10); 12593 } else { 12594 EltTy = T; 12595 } 12596 12597 // Retrieve the last enumerator's value, extent that type to the 12598 // type that is supposed to be large enough to represent the incremented 12599 // value, then increment. 12600 EnumVal = LastEnumConst->getInitVal(); 12601 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12602 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12603 ++EnumVal; 12604 12605 // If we're not in C++, diagnose the overflow of enumerator values, 12606 // which in C99 means that the enumerator value is not representable in 12607 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12608 // permits enumerator values that are representable in some larger 12609 // integral type. 12610 if (!getLangOpts().CPlusPlus && !T.isNull()) 12611 Diag(IdLoc, diag::warn_enum_value_overflow); 12612 } else if (!getLangOpts().CPlusPlus && 12613 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12614 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12615 Diag(IdLoc, diag::ext_enum_value_not_int) 12616 << EnumVal.toString(10) << 1; 12617 } 12618 } 12619 } 12620 12621 if (!EltTy->isDependentType()) { 12622 // Make the enumerator value match the signedness and size of the 12623 // enumerator's type. 12624 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12625 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12626 } 12627 12628 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12629 Val, EnumVal); 12630 } 12631 12632 12633 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12634 SourceLocation IdLoc, IdentifierInfo *Id, 12635 AttributeList *Attr, 12636 SourceLocation EqualLoc, Expr *Val) { 12637 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12638 EnumConstantDecl *LastEnumConst = 12639 cast_or_null<EnumConstantDecl>(lastEnumConst); 12640 12641 // The scope passed in may not be a decl scope. Zip up the scope tree until 12642 // we find one that is. 12643 S = getNonFieldDeclScope(S); 12644 12645 // Verify that there isn't already something declared with this name in this 12646 // scope. 12647 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12648 ForRedeclaration); 12649 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12650 // Maybe we will complain about the shadowed template parameter. 12651 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12652 // Just pretend that we didn't see the previous declaration. 12653 PrevDecl = 0; 12654 } 12655 12656 if (PrevDecl) { 12657 // When in C++, we may get a TagDecl with the same name; in this case the 12658 // enum constant will 'hide' the tag. 12659 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12660 "Received TagDecl when not in C++!"); 12661 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12662 if (isa<EnumConstantDecl>(PrevDecl)) 12663 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12664 else 12665 Diag(IdLoc, diag::err_redefinition) << Id; 12666 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12667 return 0; 12668 } 12669 } 12670 12671 // C++ [class.mem]p15: 12672 // If T is the name of a class, then each of the following shall have a name 12673 // different from T: 12674 // - every enumerator of every member of class T that is an unscoped 12675 // enumerated type 12676 if (CXXRecordDecl *Record 12677 = dyn_cast<CXXRecordDecl>( 12678 TheEnumDecl->getDeclContext()->getRedeclContext())) 12679 if (!TheEnumDecl->isScoped() && 12680 Record->getIdentifier() && Record->getIdentifier() == Id) 12681 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12682 12683 EnumConstantDecl *New = 12684 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12685 12686 if (New) { 12687 // Process attributes. 12688 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12689 12690 // Register this decl in the current scope stack. 12691 New->setAccess(TheEnumDecl->getAccess()); 12692 PushOnScopeChains(New, S); 12693 } 12694 12695 ActOnDocumentableDecl(New); 12696 12697 return New; 12698 } 12699 12700 // Returns true when the enum initial expression does not trigger the 12701 // duplicate enum warning. A few common cases are exempted as follows: 12702 // Element2 = Element1 12703 // Element2 = Element1 + 1 12704 // Element2 = Element1 - 1 12705 // Where Element2 and Element1 are from the same enum. 12706 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12707 Expr *InitExpr = ECD->getInitExpr(); 12708 if (!InitExpr) 12709 return true; 12710 InitExpr = InitExpr->IgnoreImpCasts(); 12711 12712 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12713 if (!BO->isAdditiveOp()) 12714 return true; 12715 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12716 if (!IL) 12717 return true; 12718 if (IL->getValue() != 1) 12719 return true; 12720 12721 InitExpr = BO->getLHS(); 12722 } 12723 12724 // This checks if the elements are from the same enum. 12725 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12726 if (!DRE) 12727 return true; 12728 12729 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12730 if (!EnumConstant) 12731 return true; 12732 12733 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12734 Enum) 12735 return true; 12736 12737 return false; 12738 } 12739 12740 struct DupKey { 12741 int64_t val; 12742 bool isTombstoneOrEmptyKey; 12743 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12744 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12745 }; 12746 12747 static DupKey GetDupKey(const llvm::APSInt& Val) { 12748 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12749 false); 12750 } 12751 12752 struct DenseMapInfoDupKey { 12753 static DupKey getEmptyKey() { return DupKey(0, true); } 12754 static DupKey getTombstoneKey() { return DupKey(1, true); } 12755 static unsigned getHashValue(const DupKey Key) { 12756 return (unsigned)(Key.val * 37); 12757 } 12758 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12759 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12760 LHS.val == RHS.val; 12761 } 12762 }; 12763 12764 // Emits a warning when an element is implicitly set a value that 12765 // a previous element has already been set to. 12766 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12767 EnumDecl *Enum, 12768 QualType EnumType) { 12769 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12770 Enum->getLocation()) == 12771 DiagnosticsEngine::Ignored) 12772 return; 12773 // Avoid anonymous enums 12774 if (!Enum->getIdentifier()) 12775 return; 12776 12777 // Only check for small enums. 12778 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12779 return; 12780 12781 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12782 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12783 12784 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12785 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12786 ValueToVectorMap; 12787 12788 DuplicatesVector DupVector; 12789 ValueToVectorMap EnumMap; 12790 12791 // Populate the EnumMap with all values represented by enum constants without 12792 // an initialier. 12793 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12794 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12795 12796 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12797 // this constant. Skip this enum since it may be ill-formed. 12798 if (!ECD) { 12799 return; 12800 } 12801 12802 if (ECD->getInitExpr()) 12803 continue; 12804 12805 DupKey Key = GetDupKey(ECD->getInitVal()); 12806 DeclOrVector &Entry = EnumMap[Key]; 12807 12808 // First time encountering this value. 12809 if (Entry.isNull()) 12810 Entry = ECD; 12811 } 12812 12813 // Create vectors for any values that has duplicates. 12814 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12815 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12816 if (!ValidDuplicateEnum(ECD, Enum)) 12817 continue; 12818 12819 DupKey Key = GetDupKey(ECD->getInitVal()); 12820 12821 DeclOrVector& Entry = EnumMap[Key]; 12822 if (Entry.isNull()) 12823 continue; 12824 12825 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12826 // Ensure constants are different. 12827 if (D == ECD) 12828 continue; 12829 12830 // Create new vector and push values onto it. 12831 ECDVector *Vec = new ECDVector(); 12832 Vec->push_back(D); 12833 Vec->push_back(ECD); 12834 12835 // Update entry to point to the duplicates vector. 12836 Entry = Vec; 12837 12838 // Store the vector somewhere we can consult later for quick emission of 12839 // diagnostics. 12840 DupVector.push_back(Vec); 12841 continue; 12842 } 12843 12844 ECDVector *Vec = Entry.get<ECDVector*>(); 12845 // Make sure constants are not added more than once. 12846 if (*Vec->begin() == ECD) 12847 continue; 12848 12849 Vec->push_back(ECD); 12850 } 12851 12852 // Emit diagnostics. 12853 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12854 DupVectorEnd = DupVector.end(); 12855 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12856 ECDVector *Vec = *DupVectorIter; 12857 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12858 12859 // Emit warning for one enum constant. 12860 ECDVector::iterator I = Vec->begin(); 12861 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12862 << (*I)->getName() << (*I)->getInitVal().toString(10) 12863 << (*I)->getSourceRange(); 12864 ++I; 12865 12866 // Emit one note for each of the remaining enum constants with 12867 // the same value. 12868 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12869 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12870 << (*I)->getName() << (*I)->getInitVal().toString(10) 12871 << (*I)->getSourceRange(); 12872 delete Vec; 12873 } 12874 } 12875 12876 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12877 SourceLocation RBraceLoc, Decl *EnumDeclX, 12878 ArrayRef<Decl *> Elements, 12879 Scope *S, AttributeList *Attr) { 12880 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12881 QualType EnumType = Context.getTypeDeclType(Enum); 12882 12883 if (Attr) 12884 ProcessDeclAttributeList(S, Enum, Attr); 12885 12886 if (Enum->isDependentType()) { 12887 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12888 EnumConstantDecl *ECD = 12889 cast_or_null<EnumConstantDecl>(Elements[i]); 12890 if (!ECD) continue; 12891 12892 ECD->setType(EnumType); 12893 } 12894 12895 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12896 return; 12897 } 12898 12899 // TODO: If the result value doesn't fit in an int, it must be a long or long 12900 // long value. ISO C does not support this, but GCC does as an extension, 12901 // emit a warning. 12902 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12903 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12904 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12905 12906 // Verify that all the values are okay, compute the size of the values, and 12907 // reverse the list. 12908 unsigned NumNegativeBits = 0; 12909 unsigned NumPositiveBits = 0; 12910 12911 // Keep track of whether all elements have type int. 12912 bool AllElementsInt = true; 12913 12914 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12915 EnumConstantDecl *ECD = 12916 cast_or_null<EnumConstantDecl>(Elements[i]); 12917 if (!ECD) continue; // Already issued a diagnostic. 12918 12919 const llvm::APSInt &InitVal = ECD->getInitVal(); 12920 12921 // Keep track of the size of positive and negative values. 12922 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12923 NumPositiveBits = std::max(NumPositiveBits, 12924 (unsigned)InitVal.getActiveBits()); 12925 else 12926 NumNegativeBits = std::max(NumNegativeBits, 12927 (unsigned)InitVal.getMinSignedBits()); 12928 12929 // Keep track of whether every enum element has type int (very commmon). 12930 if (AllElementsInt) 12931 AllElementsInt = ECD->getType() == Context.IntTy; 12932 } 12933 12934 // Figure out the type that should be used for this enum. 12935 QualType BestType; 12936 unsigned BestWidth; 12937 12938 // C++0x N3000 [conv.prom]p3: 12939 // An rvalue of an unscoped enumeration type whose underlying 12940 // type is not fixed can be converted to an rvalue of the first 12941 // of the following types that can represent all the values of 12942 // the enumeration: int, unsigned int, long int, unsigned long 12943 // int, long long int, or unsigned long long int. 12944 // C99 6.4.4.3p2: 12945 // An identifier declared as an enumeration constant has type int. 12946 // The C99 rule is modified by a gcc extension 12947 QualType BestPromotionType; 12948 12949 bool Packed = Enum->hasAttr<PackedAttr>(); 12950 // -fshort-enums is the equivalent to specifying the packed attribute on all 12951 // enum definitions. 12952 if (LangOpts.ShortEnums) 12953 Packed = true; 12954 12955 if (Enum->isFixed()) { 12956 BestType = Enum->getIntegerType(); 12957 if (BestType->isPromotableIntegerType()) 12958 BestPromotionType = Context.getPromotedIntegerType(BestType); 12959 else 12960 BestPromotionType = BestType; 12961 // We don't need to set BestWidth, because BestType is going to be the type 12962 // of the enumerators, but we do anyway because otherwise some compilers 12963 // warn that it might be used uninitialized. 12964 BestWidth = CharWidth; 12965 } 12966 else if (NumNegativeBits) { 12967 // If there is a negative value, figure out the smallest integer type (of 12968 // int/long/longlong) that fits. 12969 // If it's packed, check also if it fits a char or a short. 12970 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12971 BestType = Context.SignedCharTy; 12972 BestWidth = CharWidth; 12973 } else if (Packed && NumNegativeBits <= ShortWidth && 12974 NumPositiveBits < ShortWidth) { 12975 BestType = Context.ShortTy; 12976 BestWidth = ShortWidth; 12977 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12978 BestType = Context.IntTy; 12979 BestWidth = IntWidth; 12980 } else { 12981 BestWidth = Context.getTargetInfo().getLongWidth(); 12982 12983 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12984 BestType = Context.LongTy; 12985 } else { 12986 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12987 12988 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12989 Diag(Enum->getLocation(), diag::ext_enum_too_large); 12990 BestType = Context.LongLongTy; 12991 } 12992 } 12993 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12994 } else { 12995 // If there is no negative value, figure out the smallest type that fits 12996 // all of the enumerator values. 12997 // If it's packed, check also if it fits a char or a short. 12998 if (Packed && NumPositiveBits <= CharWidth) { 12999 BestType = Context.UnsignedCharTy; 13000 BestPromotionType = Context.IntTy; 13001 BestWidth = CharWidth; 13002 } else if (Packed && NumPositiveBits <= ShortWidth) { 13003 BestType = Context.UnsignedShortTy; 13004 BestPromotionType = Context.IntTy; 13005 BestWidth = ShortWidth; 13006 } else if (NumPositiveBits <= IntWidth) { 13007 BestType = Context.UnsignedIntTy; 13008 BestWidth = IntWidth; 13009 BestPromotionType 13010 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13011 ? Context.UnsignedIntTy : Context.IntTy; 13012 } else if (NumPositiveBits <= 13013 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13014 BestType = Context.UnsignedLongTy; 13015 BestPromotionType 13016 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13017 ? Context.UnsignedLongTy : Context.LongTy; 13018 } else { 13019 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13020 assert(NumPositiveBits <= BestWidth && 13021 "How could an initializer get larger than ULL?"); 13022 BestType = Context.UnsignedLongLongTy; 13023 BestPromotionType 13024 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13025 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13026 } 13027 } 13028 13029 // Loop over all of the enumerator constants, changing their types to match 13030 // the type of the enum if needed. 13031 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13032 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13033 if (!ECD) continue; // Already issued a diagnostic. 13034 13035 // Standard C says the enumerators have int type, but we allow, as an 13036 // extension, the enumerators to be larger than int size. If each 13037 // enumerator value fits in an int, type it as an int, otherwise type it the 13038 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13039 // that X has type 'int', not 'unsigned'. 13040 13041 // Determine whether the value fits into an int. 13042 llvm::APSInt InitVal = ECD->getInitVal(); 13043 13044 // If it fits into an integer type, force it. Otherwise force it to match 13045 // the enum decl type. 13046 QualType NewTy; 13047 unsigned NewWidth; 13048 bool NewSign; 13049 if (!getLangOpts().CPlusPlus && 13050 !Enum->isFixed() && 13051 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13052 NewTy = Context.IntTy; 13053 NewWidth = IntWidth; 13054 NewSign = true; 13055 } else if (ECD->getType() == BestType) { 13056 // Already the right type! 13057 if (getLangOpts().CPlusPlus) 13058 // C++ [dcl.enum]p4: Following the closing brace of an 13059 // enum-specifier, each enumerator has the type of its 13060 // enumeration. 13061 ECD->setType(EnumType); 13062 continue; 13063 } else { 13064 NewTy = BestType; 13065 NewWidth = BestWidth; 13066 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13067 } 13068 13069 // Adjust the APSInt value. 13070 InitVal = InitVal.extOrTrunc(NewWidth); 13071 InitVal.setIsSigned(NewSign); 13072 ECD->setInitVal(InitVal); 13073 13074 // Adjust the Expr initializer and type. 13075 if (ECD->getInitExpr() && 13076 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13077 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13078 CK_IntegralCast, 13079 ECD->getInitExpr(), 13080 /*base paths*/ 0, 13081 VK_RValue)); 13082 if (getLangOpts().CPlusPlus) 13083 // C++ [dcl.enum]p4: Following the closing brace of an 13084 // enum-specifier, each enumerator has the type of its 13085 // enumeration. 13086 ECD->setType(EnumType); 13087 else 13088 ECD->setType(NewTy); 13089 } 13090 13091 Enum->completeDefinition(BestType, BestPromotionType, 13092 NumPositiveBits, NumNegativeBits); 13093 13094 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13095 13096 // Now that the enum type is defined, ensure it's not been underaligned. 13097 if (Enum->hasAttrs()) 13098 CheckAlignasUnderalignment(Enum); 13099 } 13100 13101 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13102 SourceLocation StartLoc, 13103 SourceLocation EndLoc) { 13104 StringLiteral *AsmString = cast<StringLiteral>(expr); 13105 13106 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13107 AsmString, StartLoc, 13108 EndLoc); 13109 CurContext->addDecl(New); 13110 return New; 13111 } 13112 13113 static void checkModuleImportContext(Sema &S, Module *M, 13114 SourceLocation ImportLoc, 13115 DeclContext *DC) { 13116 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13117 switch (LSD->getLanguage()) { 13118 case LinkageSpecDecl::lang_c: 13119 if (!M->IsExternC) { 13120 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13121 << M->getFullModuleName(); 13122 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13123 return; 13124 } 13125 break; 13126 case LinkageSpecDecl::lang_cxx: 13127 break; 13128 } 13129 DC = LSD->getParent(); 13130 } 13131 13132 while (isa<LinkageSpecDecl>(DC)) 13133 DC = DC->getParent(); 13134 if (!isa<TranslationUnitDecl>(DC)) { 13135 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13136 << M->getFullModuleName() << DC; 13137 S.Diag(cast<Decl>(DC)->getLocStart(), 13138 diag::note_module_import_not_at_top_level) 13139 << DC; 13140 } 13141 } 13142 13143 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13144 SourceLocation ImportLoc, 13145 ModuleIdPath Path) { 13146 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 13147 Module::AllVisible, 13148 /*IsIncludeDirective=*/false); 13149 if (!Mod) 13150 return true; 13151 13152 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13153 13154 SmallVector<SourceLocation, 2> IdentifierLocs; 13155 Module *ModCheck = Mod; 13156 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13157 // If we've run out of module parents, just drop the remaining identifiers. 13158 // We need the length to be consistent. 13159 if (!ModCheck) 13160 break; 13161 ModCheck = ModCheck->Parent; 13162 13163 IdentifierLocs.push_back(Path[I].second); 13164 } 13165 13166 ImportDecl *Import = ImportDecl::Create(Context, 13167 Context.getTranslationUnitDecl(), 13168 AtLoc.isValid()? AtLoc : ImportLoc, 13169 Mod, IdentifierLocs); 13170 Context.getTranslationUnitDecl()->addDecl(Import); 13171 return Import; 13172 } 13173 13174 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13175 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13176 13177 // FIXME: Should we synthesize an ImportDecl here? 13178 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13179 /*Complain=*/true); 13180 } 13181 13182 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 13183 // Create the implicit import declaration. 13184 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13185 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13186 Loc, Mod, Loc); 13187 TU->addDecl(ImportD); 13188 Consumer.HandleImplicitImportDecl(ImportD); 13189 13190 // Make the module visible. 13191 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13192 /*Complain=*/false); 13193 } 13194 13195 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13196 IdentifierInfo* AliasName, 13197 SourceLocation PragmaLoc, 13198 SourceLocation NameLoc, 13199 SourceLocation AliasNameLoc) { 13200 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13201 LookupOrdinaryName); 13202 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13203 AliasName->getName(), 0); 13204 13205 if (PrevDecl) 13206 PrevDecl->addAttr(Attr); 13207 else 13208 (void)ExtnameUndeclaredIdentifiers.insert( 13209 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13210 } 13211 13212 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13213 SourceLocation PragmaLoc, 13214 SourceLocation NameLoc) { 13215 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13216 13217 if (PrevDecl) { 13218 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13219 } else { 13220 (void)WeakUndeclaredIdentifiers.insert( 13221 std::pair<IdentifierInfo*,WeakInfo> 13222 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 13223 } 13224 } 13225 13226 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13227 IdentifierInfo* AliasName, 13228 SourceLocation PragmaLoc, 13229 SourceLocation NameLoc, 13230 SourceLocation AliasNameLoc) { 13231 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13232 LookupOrdinaryName); 13233 WeakInfo W = WeakInfo(Name, NameLoc); 13234 13235 if (PrevDecl) { 13236 if (!PrevDecl->hasAttr<AliasAttr>()) 13237 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13238 DeclApplyPragmaWeak(TUScope, ND, W); 13239 } else { 13240 (void)WeakUndeclaredIdentifiers.insert( 13241 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13242 } 13243 } 13244 13245 Decl *Sema::getObjCDeclContext() const { 13246 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13247 } 13248 13249 AvailabilityResult Sema::getCurContextAvailability() const { 13250 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13251 // If we are within an Objective-C method, we should consult 13252 // both the availability of the method as well as the 13253 // enclosing class. If the class is (say) deprecated, 13254 // the entire method is considered deprecated from the 13255 // purpose of checking if the current context is deprecated. 13256 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13257 AvailabilityResult R = MD->getAvailability(); 13258 if (R != AR_Available) 13259 return R; 13260 D = MD->getClassInterface(); 13261 } 13262 // If we are within an Objective-c @implementation, it 13263 // gets the same availability context as the @interface. 13264 else if (const ObjCImplementationDecl *ID = 13265 dyn_cast<ObjCImplementationDecl>(D)) { 13266 D = ID->getClassInterface(); 13267 } 13268 return D->getAvailability(); 13269 } 13270