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 CTK_ErrorRecovery); 223 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 224 TemplateTy Template; 225 bool MemberOfUnknownSpecialization; 226 UnqualifiedId TemplateName; 227 TemplateName.setIdentifier(NewII, NameLoc); 228 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 229 CXXScopeSpec NewSS, *NewSSPtr = SS; 230 if (SS && NNS) { 231 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 232 NewSSPtr = &NewSS; 233 } 234 if (Correction && (NNS || NewII != &II) && 235 // Ignore a correction to a template type as the to-be-corrected 236 // identifier is not a template (typo correction for template names 237 // is handled elsewhere). 238 !(getLangOpts().CPlusPlus && NewSSPtr && 239 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 240 false, Template, MemberOfUnknownSpecialization))) { 241 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 242 isClassName, HasTrailingDot, ObjectTypePtr, 243 IsCtorOrDtorName, 244 WantNontrivialTypeSourceInfo); 245 if (Ty) { 246 diagnoseTypo(Correction, 247 PDiag(diag::err_unknown_type_or_class_name_suggest) 248 << Result.getLookupName() << isClassName); 249 if (SS && NNS) 250 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 251 *CorrectedII = NewII; 252 return Ty; 253 } 254 } 255 } 256 // If typo correction failed or was not performed, fall through 257 case LookupResult::FoundOverloaded: 258 case LookupResult::FoundUnresolvedValue: 259 Result.suppressDiagnostics(); 260 return ParsedType(); 261 262 case LookupResult::Ambiguous: 263 // Recover from type-hiding ambiguities by hiding the type. We'll 264 // do the lookup again when looking for an object, and we can 265 // diagnose the error then. If we don't do this, then the error 266 // about hiding the type will be immediately followed by an error 267 // that only makes sense if the identifier was treated like a type. 268 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 269 Result.suppressDiagnostics(); 270 return ParsedType(); 271 } 272 273 // Look to see if we have a type anywhere in the list of results. 274 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 275 Res != ResEnd; ++Res) { 276 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 277 if (!IIDecl || 278 (*Res)->getLocation().getRawEncoding() < 279 IIDecl->getLocation().getRawEncoding()) 280 IIDecl = *Res; 281 } 282 } 283 284 if (!IIDecl) { 285 // None of the entities we found is a type, so there is no way 286 // to even assume that the result is a type. In this case, don't 287 // complain about the ambiguity. The parser will either try to 288 // perform this lookup again (e.g., as an object name), which 289 // will produce the ambiguity, or will complain that it expected 290 // a type name. 291 Result.suppressDiagnostics(); 292 return ParsedType(); 293 } 294 295 // We found a type within the ambiguous lookup; diagnose the 296 // ambiguity and then return that type. This might be the right 297 // answer, or it might not be, but it suppresses any attempt to 298 // perform the name lookup again. 299 break; 300 301 case LookupResult::Found: 302 IIDecl = Result.getFoundDecl(); 303 break; 304 } 305 306 assert(IIDecl && "Didn't find decl"); 307 308 QualType T; 309 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 310 DiagnoseUseOfDecl(IIDecl, NameLoc); 311 312 if (T.isNull()) 313 T = Context.getTypeDeclType(TD); 314 315 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 316 // constructor or destructor name (in such a case, the scope specifier 317 // will be attached to the enclosing Expr or Decl node). 318 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 319 if (WantNontrivialTypeSourceInfo) { 320 // Construct a type with type-source information. 321 TypeLocBuilder Builder; 322 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 323 324 T = getElaboratedType(ETK_None, *SS, T); 325 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 326 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 327 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 328 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 329 } else { 330 T = getElaboratedType(ETK_None, *SS, T); 331 } 332 } 333 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 334 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 335 if (!HasTrailingDot) 336 T = Context.getObjCInterfaceType(IDecl); 337 } 338 339 if (T.isNull()) { 340 // If it's not plausibly a type, suppress diagnostics. 341 Result.suppressDiagnostics(); 342 return ParsedType(); 343 } 344 return ParsedType::make(T); 345 } 346 347 /// isTagName() - This method is called *for error recovery purposes only* 348 /// to determine if the specified name is a valid tag name ("struct foo"). If 349 /// so, this returns the TST for the tag corresponding to it (TST_enum, 350 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 351 /// cases in C where the user forgot to specify the tag. 352 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 353 // Do a tag name lookup in this scope. 354 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 355 LookupName(R, S, false); 356 R.suppressDiagnostics(); 357 if (R.getResultKind() == LookupResult::Found) 358 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 359 switch (TD->getTagKind()) { 360 case TTK_Struct: return DeclSpec::TST_struct; 361 case TTK_Interface: return DeclSpec::TST_interface; 362 case TTK_Union: return DeclSpec::TST_union; 363 case TTK_Class: return DeclSpec::TST_class; 364 case TTK_Enum: return DeclSpec::TST_enum; 365 } 366 } 367 368 return DeclSpec::TST_unspecified; 369 } 370 371 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 372 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 373 /// then downgrade the missing typename error to a warning. 374 /// This is needed for MSVC compatibility; Example: 375 /// @code 376 /// template<class T> class A { 377 /// public: 378 /// typedef int TYPE; 379 /// }; 380 /// template<class T> class B : public A<T> { 381 /// public: 382 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 383 /// }; 384 /// @endcode 385 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 386 if (CurContext->isRecord()) { 387 const Type *Ty = SS->getScopeRep()->getAsType(); 388 389 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 390 for (const auto &Base : RD->bases()) 391 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 392 return true; 393 return S->isFunctionPrototypeScope(); 394 } 395 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 396 } 397 398 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 399 SourceLocation IILoc, 400 Scope *S, 401 CXXScopeSpec *SS, 402 ParsedType &SuggestedType, 403 bool AllowClassTemplates) { 404 // We don't have anything to suggest (yet). 405 SuggestedType = ParsedType(); 406 407 // There may have been a typo in the name of the type. Look up typo 408 // results, in case we have something that we can suggest. 409 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 410 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 411 LookupOrdinaryName, S, SS, 412 Validator, CTK_ErrorRecovery)) { 413 if (Corrected.isKeyword()) { 414 // We corrected to a keyword. 415 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 416 II = Corrected.getCorrectionAsIdentifierInfo(); 417 } else { 418 // We found a similarly-named type or interface; suggest that. 419 if (!SS || !SS->isSet()) { 420 diagnoseTypo(Corrected, 421 PDiag(diag::err_unknown_typename_suggest) << II); 422 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 423 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 424 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 425 II->getName().equals(CorrectedStr); 426 diagnoseTypo(Corrected, 427 PDiag(diag::err_unknown_nested_typename_suggest) 428 << II << DC << DroppedSpecifier << SS->getRange()); 429 } else { 430 llvm_unreachable("could not have corrected a typo here"); 431 } 432 433 CXXScopeSpec tmpSS; 434 if (Corrected.getCorrectionSpecifier()) 435 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 436 SourceRange(IILoc)); 437 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 438 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 439 false, ParsedType(), 440 /*IsCtorOrDtorName=*/false, 441 /*NonTrivialTypeSourceInfo=*/true); 442 } 443 return true; 444 } 445 446 if (getLangOpts().CPlusPlus) { 447 // See if II is a class template that the user forgot to pass arguments to. 448 UnqualifiedId Name; 449 Name.setIdentifier(II, IILoc); 450 CXXScopeSpec EmptySS; 451 TemplateTy TemplateResult; 452 bool MemberOfUnknownSpecialization; 453 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 454 Name, ParsedType(), true, TemplateResult, 455 MemberOfUnknownSpecialization) == TNK_Type_template) { 456 TemplateName TplName = TemplateResult.get(); 457 Diag(IILoc, diag::err_template_missing_args) << TplName; 458 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 459 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 460 << TplDecl->getTemplateParameters()->getSourceRange(); 461 } 462 return true; 463 } 464 } 465 466 // FIXME: Should we move the logic that tries to recover from a missing tag 467 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 468 469 if (!SS || (!SS->isSet() && !SS->isInvalid())) 470 Diag(IILoc, diag::err_unknown_typename) << II; 471 else if (DeclContext *DC = computeDeclContext(*SS, false)) 472 Diag(IILoc, diag::err_typename_nested_not_found) 473 << II << DC << SS->getRange(); 474 else if (isDependentScopeSpecifier(*SS)) { 475 unsigned DiagID = diag::err_typename_missing; 476 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 477 DiagID = diag::warn_typename_missing; 478 479 Diag(SS->getRange().getBegin(), DiagID) 480 << SS->getScopeRep() << II->getName() 481 << SourceRange(SS->getRange().getBegin(), IILoc) 482 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 483 SuggestedType = ActOnTypenameType(S, SourceLocation(), 484 *SS, *II, IILoc).get(); 485 } else { 486 assert(SS && SS->isInvalid() && 487 "Invalid scope specifier has already been diagnosed"); 488 } 489 490 return true; 491 } 492 493 /// \brief Determine whether the given result set contains either a type name 494 /// or 495 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 496 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 497 NextToken.is(tok::less); 498 499 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 500 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 501 return true; 502 503 if (CheckTemplate && isa<TemplateDecl>(*I)) 504 return true; 505 } 506 507 return false; 508 } 509 510 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 511 Scope *S, CXXScopeSpec &SS, 512 IdentifierInfo *&Name, 513 SourceLocation NameLoc) { 514 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 515 SemaRef.LookupParsedName(R, S, &SS); 516 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 517 const char *TagName = 0; 518 const char *FixItTagName = 0; 519 switch (Tag->getTagKind()) { 520 case TTK_Class: 521 TagName = "class"; 522 FixItTagName = "class "; 523 break; 524 525 case TTK_Enum: 526 TagName = "enum"; 527 FixItTagName = "enum "; 528 break; 529 530 case TTK_Struct: 531 TagName = "struct"; 532 FixItTagName = "struct "; 533 break; 534 535 case TTK_Interface: 536 TagName = "__interface"; 537 FixItTagName = "__interface "; 538 break; 539 540 case TTK_Union: 541 TagName = "union"; 542 FixItTagName = "union "; 543 break; 544 } 545 546 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 547 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 548 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 549 550 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 551 I != IEnd; ++I) 552 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 553 << Name << TagName; 554 555 // Replace lookup results with just the tag decl. 556 Result.clear(Sema::LookupTagName); 557 SemaRef.LookupParsedName(Result, S, &SS); 558 return true; 559 } 560 561 return false; 562 } 563 564 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 565 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 566 QualType T, SourceLocation NameLoc) { 567 ASTContext &Context = S.Context; 568 569 TypeLocBuilder Builder; 570 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 571 572 T = S.getElaboratedType(ETK_None, SS, T); 573 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 574 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 575 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 576 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 577 } 578 579 Sema::NameClassification Sema::ClassifyName(Scope *S, 580 CXXScopeSpec &SS, 581 IdentifierInfo *&Name, 582 SourceLocation NameLoc, 583 const Token &NextToken, 584 bool IsAddressOfOperand, 585 CorrectionCandidateCallback *CCC) { 586 DeclarationNameInfo NameInfo(Name, NameLoc); 587 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 588 589 if (NextToken.is(tok::coloncolon)) { 590 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 591 QualType(), false, SS, 0, false); 592 } 593 594 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 CTK_ErrorRecovery)) { 656 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 657 unsigned QualifiedDiag = diag::err_no_member_suggest; 658 659 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 660 NamedDecl *UnderlyingFirstDecl 661 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 662 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 663 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 664 UnqualifiedDiag = diag::err_no_template_suggest; 665 QualifiedDiag = diag::err_no_member_template_suggest; 666 } else if (UnderlyingFirstDecl && 667 (isa<TypeDecl>(UnderlyingFirstDecl) || 668 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 669 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 670 UnqualifiedDiag = diag::err_unknown_typename_suggest; 671 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 672 } 673 674 if (SS.isEmpty()) { 675 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 676 } else {// FIXME: is this even reachable? Test it. 677 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 678 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 679 Name->getName().equals(CorrectedStr); 680 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 681 << Name << computeDeclContext(SS, false) 682 << DroppedSpecifier << SS.getRange()); 683 } 684 685 // Update the name, so that the caller has the new name. 686 Name = Corrected.getCorrectionAsIdentifierInfo(); 687 688 // Typo correction corrected to a keyword. 689 if (Corrected.isKeyword()) 690 return Name; 691 692 // Also update the LookupResult... 693 // FIXME: This should probably go away at some point 694 Result.clear(); 695 Result.setLookupName(Corrected.getCorrection()); 696 if (FirstDecl) 697 Result.addDecl(FirstDecl); 698 699 // If we found an Objective-C instance variable, let 700 // LookupInObjCMethod build the appropriate expression to 701 // reference the ivar. 702 // FIXME: This is a gross hack. 703 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 704 Result.clear(); 705 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 706 return E; 707 } 708 709 goto Corrected; 710 } 711 } 712 713 // We failed to correct; just fall through and let the parser deal with it. 714 Result.suppressDiagnostics(); 715 return NameClassification::Unknown(); 716 717 case LookupResult::NotFoundInCurrentInstantiation: { 718 // We performed name lookup into the current instantiation, and there were 719 // dependent bases, so we treat this result the same way as any other 720 // dependent nested-name-specifier. 721 722 // C++ [temp.res]p2: 723 // A name used in a template declaration or definition and that is 724 // dependent on a template-parameter is assumed not to name a type 725 // unless the applicable name lookup finds a type name or the name is 726 // qualified by the keyword typename. 727 // 728 // FIXME: If the next token is '<', we might want to ask the parser to 729 // perform some heroics to see if we actually have a 730 // template-argument-list, which would indicate a missing 'template' 731 // keyword here. 732 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 733 NameInfo, IsAddressOfOperand, 734 /*TemplateArgs=*/0); 735 } 736 737 case LookupResult::Found: 738 case LookupResult::FoundOverloaded: 739 case LookupResult::FoundUnresolvedValue: 740 break; 741 742 case LookupResult::Ambiguous: 743 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 744 hasAnyAcceptableTemplateNames(Result)) { 745 // C++ [temp.local]p3: 746 // A lookup that finds an injected-class-name (10.2) can result in an 747 // ambiguity in certain cases (for example, if it is found in more than 748 // one base class). If all of the injected-class-names that are found 749 // refer to specializations of the same class template, and if the name 750 // is followed by a template-argument-list, the reference refers to the 751 // class template itself and not a specialization thereof, and is not 752 // ambiguous. 753 // 754 // This filtering can make an ambiguous result into an unambiguous one, 755 // so try again after filtering out template names. 756 FilterAcceptableTemplateNames(Result); 757 if (!Result.isAmbiguous()) { 758 IsFilteredTemplateName = true; 759 break; 760 } 761 } 762 763 // Diagnose the ambiguity and return an error. 764 return NameClassification::Error(); 765 } 766 767 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 768 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 769 // C++ [temp.names]p3: 770 // After name lookup (3.4) finds that a name is a template-name or that 771 // an operator-function-id or a literal- operator-id refers to a set of 772 // overloaded functions any member of which is a function template if 773 // this is followed by a <, the < is always taken as the delimiter of a 774 // template-argument-list and never as the less-than operator. 775 if (!IsFilteredTemplateName) 776 FilterAcceptableTemplateNames(Result); 777 778 if (!Result.empty()) { 779 bool IsFunctionTemplate; 780 bool IsVarTemplate; 781 TemplateName Template; 782 if (Result.end() - Result.begin() > 1) { 783 IsFunctionTemplate = true; 784 Template = Context.getOverloadedTemplateName(Result.begin(), 785 Result.end()); 786 } else { 787 TemplateDecl *TD 788 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 789 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 790 IsVarTemplate = isa<VarTemplateDecl>(TD); 791 792 if (SS.isSet() && !SS.isInvalid()) 793 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 794 /*TemplateKeyword=*/false, 795 TD); 796 else 797 Template = TemplateName(TD); 798 } 799 800 if (IsFunctionTemplate) { 801 // Function templates always go through overload resolution, at which 802 // point we'll perform the various checks (e.g., accessibility) we need 803 // to based on which function we selected. 804 Result.suppressDiagnostics(); 805 806 return NameClassification::FunctionTemplate(Template); 807 } 808 809 return IsVarTemplate ? NameClassification::VarTemplate(Template) 810 : NameClassification::TypeTemplate(Template); 811 } 812 } 813 814 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 815 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 816 DiagnoseUseOfDecl(Type, NameLoc); 817 QualType T = Context.getTypeDeclType(Type); 818 if (SS.isNotEmpty()) 819 return buildNestedType(*this, SS, T, NameLoc); 820 return ParsedType::make(T); 821 } 822 823 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 824 if (!Class) { 825 // FIXME: It's unfortunate that we don't have a Type node for handling this. 826 if (ObjCCompatibleAliasDecl *Alias 827 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 828 Class = Alias->getClassInterface(); 829 } 830 831 if (Class) { 832 DiagnoseUseOfDecl(Class, NameLoc); 833 834 if (NextToken.is(tok::period)) { 835 // Interface. <something> is parsed as a property reference expression. 836 // Just return "unknown" as a fall-through for now. 837 Result.suppressDiagnostics(); 838 return NameClassification::Unknown(); 839 } 840 841 QualType T = Context.getObjCInterfaceType(Class); 842 return ParsedType::make(T); 843 } 844 845 // We can have a type template here if we're classifying a template argument. 846 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 847 return NameClassification::TypeTemplate( 848 TemplateName(cast<TemplateDecl>(FirstDecl))); 849 850 // Check for a tag type hidden by a non-type decl in a few cases where it 851 // seems likely a type is wanted instead of the non-type that was found. 852 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 853 if ((NextToken.is(tok::identifier) || 854 (NextIsOp && 855 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 856 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 857 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 858 DiagnoseUseOfDecl(Type, NameLoc); 859 QualType T = Context.getTypeDeclType(Type); 860 if (SS.isNotEmpty()) 861 return buildNestedType(*this, SS, T, NameLoc); 862 return ParsedType::make(T); 863 } 864 865 if (FirstDecl->isCXXClassMember()) 866 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 867 868 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 869 return BuildDeclarationNameExpr(SS, Result, ADL); 870 } 871 872 // Determines the context to return to after temporarily entering a 873 // context. This depends in an unnecessarily complicated way on the 874 // exact ordering of callbacks from the parser. 875 DeclContext *Sema::getContainingDC(DeclContext *DC) { 876 877 // Functions defined inline within classes aren't parsed until we've 878 // finished parsing the top-level class, so the top-level class is 879 // the context we'll need to return to. 880 // A Lambda call operator whose parent is a class must not be treated 881 // as an inline member function. A Lambda can be used legally 882 // either as an in-class member initializer or a default argument. These 883 // are parsed once the class has been marked complete and so the containing 884 // context would be the nested class (when the lambda is defined in one); 885 // If the class is not complete, then the lambda is being used in an 886 // ill-formed fashion (such as to specify the width of a bit-field, or 887 // in an array-bound) - in which case we still want to return the 888 // lexically containing DC (which could be a nested class). 889 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 890 DC = DC->getLexicalParent(); 891 892 // A function not defined within a class will always return to its 893 // lexical context. 894 if (!isa<CXXRecordDecl>(DC)) 895 return DC; 896 897 // A C++ inline method/friend is parsed *after* the topmost class 898 // it was declared in is fully parsed ("complete"); the topmost 899 // class is the context we need to return to. 900 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 901 DC = RD; 902 903 // Return the declaration context of the topmost class the inline method is 904 // declared in. 905 return DC; 906 } 907 908 return DC->getLexicalParent(); 909 } 910 911 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 912 assert(getContainingDC(DC) == CurContext && 913 "The next DeclContext should be lexically contained in the current one."); 914 CurContext = DC; 915 S->setEntity(DC); 916 } 917 918 void Sema::PopDeclContext() { 919 assert(CurContext && "DeclContext imbalance!"); 920 921 CurContext = getContainingDC(CurContext); 922 assert(CurContext && "Popped translation unit!"); 923 } 924 925 /// EnterDeclaratorContext - Used when we must lookup names in the context 926 /// of a declarator's nested name specifier. 927 /// 928 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 929 // C++0x [basic.lookup.unqual]p13: 930 // A name used in the definition of a static data member of class 931 // X (after the qualified-id of the static member) is looked up as 932 // if the name was used in a member function of X. 933 // C++0x [basic.lookup.unqual]p14: 934 // If a variable member of a namespace is defined outside of the 935 // scope of its namespace then any name used in the definition of 936 // the variable member (after the declarator-id) is looked up as 937 // if the definition of the variable member occurred in its 938 // namespace. 939 // Both of these imply that we should push a scope whose context 940 // is the semantic context of the declaration. We can't use 941 // PushDeclContext here because that context is not necessarily 942 // lexically contained in the current context. Fortunately, 943 // the containing scope should have the appropriate information. 944 945 assert(!S->getEntity() && "scope already has entity"); 946 947 #ifndef NDEBUG 948 Scope *Ancestor = S->getParent(); 949 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 950 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 951 #endif 952 953 CurContext = DC; 954 S->setEntity(DC); 955 } 956 957 void Sema::ExitDeclaratorContext(Scope *S) { 958 assert(S->getEntity() == CurContext && "Context imbalance!"); 959 960 // Switch back to the lexical context. The safety of this is 961 // enforced by an assert in EnterDeclaratorContext. 962 Scope *Ancestor = S->getParent(); 963 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 964 CurContext = Ancestor->getEntity(); 965 966 // We don't need to do anything with the scope, which is going to 967 // disappear. 968 } 969 970 971 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 972 // We assume that the caller has already called 973 // ActOnReenterTemplateScope so getTemplatedDecl() works. 974 FunctionDecl *FD = D->getAsFunction(); 975 if (!FD) 976 return; 977 978 // Same implementation as PushDeclContext, but enters the context 979 // from the lexical parent, rather than the top-level class. 980 assert(CurContext == FD->getLexicalParent() && 981 "The next DeclContext should be lexically contained in the current one."); 982 CurContext = FD; 983 S->setEntity(CurContext); 984 985 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 986 ParmVarDecl *Param = FD->getParamDecl(P); 987 // If the parameter has an identifier, then add it to the scope 988 if (Param->getIdentifier()) { 989 S->AddDecl(Param); 990 IdResolver.AddDecl(Param); 991 } 992 } 993 } 994 995 996 void Sema::ActOnExitFunctionContext() { 997 // Same implementation as PopDeclContext, but returns to the lexical parent, 998 // rather than the top-level class. 999 assert(CurContext && "DeclContext imbalance!"); 1000 CurContext = CurContext->getLexicalParent(); 1001 assert(CurContext && "Popped translation unit!"); 1002 } 1003 1004 1005 /// \brief Determine whether we allow overloading of the function 1006 /// PrevDecl with another declaration. 1007 /// 1008 /// This routine determines whether overloading is possible, not 1009 /// whether some new function is actually an overload. It will return 1010 /// true in C++ (where we can always provide overloads) or, as an 1011 /// extension, in C when the previous function is already an 1012 /// overloaded function declaration or has the "overloadable" 1013 /// attribute. 1014 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1015 ASTContext &Context) { 1016 if (Context.getLangOpts().CPlusPlus) 1017 return true; 1018 1019 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1020 return true; 1021 1022 return (Previous.getResultKind() == LookupResult::Found 1023 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1024 } 1025 1026 /// Add this decl to the scope shadowed decl chains. 1027 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1028 // Move up the scope chain until we find the nearest enclosing 1029 // non-transparent context. The declaration will be introduced into this 1030 // scope. 1031 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1032 S = S->getParent(); 1033 1034 // Add scoped declarations into their context, so that they can be 1035 // found later. Declarations without a context won't be inserted 1036 // into any context. 1037 if (AddToContext) 1038 CurContext->addDecl(D); 1039 1040 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1041 // are function-local declarations. 1042 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1043 !D->getDeclContext()->getRedeclContext()->Equals( 1044 D->getLexicalDeclContext()->getRedeclContext()) && 1045 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1046 return; 1047 1048 // Template instantiations should also not be pushed into scope. 1049 if (isa<FunctionDecl>(D) && 1050 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1051 return; 1052 1053 // If this replaces anything in the current scope, 1054 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1055 IEnd = IdResolver.end(); 1056 for (; I != IEnd; ++I) { 1057 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1058 S->RemoveDecl(*I); 1059 IdResolver.RemoveDecl(*I); 1060 1061 // Should only need to replace one decl. 1062 break; 1063 } 1064 } 1065 1066 S->AddDecl(D); 1067 1068 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1069 // Implicitly-generated labels may end up getting generated in an order that 1070 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1071 // the label at the appropriate place in the identifier chain. 1072 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1073 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1074 if (IDC == CurContext) { 1075 if (!S->isDeclScope(*I)) 1076 continue; 1077 } else if (IDC->Encloses(CurContext)) 1078 break; 1079 } 1080 1081 IdResolver.InsertDeclAfter(I, D); 1082 } else { 1083 IdResolver.AddDecl(D); 1084 } 1085 } 1086 1087 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1088 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1089 TUScope->AddDecl(D); 1090 } 1091 1092 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1093 bool AllowInlineNamespace) { 1094 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1095 } 1096 1097 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1098 DeclContext *TargetDC = DC->getPrimaryContext(); 1099 do { 1100 if (DeclContext *ScopeDC = S->getEntity()) 1101 if (ScopeDC->getPrimaryContext() == TargetDC) 1102 return S; 1103 } while ((S = S->getParent())); 1104 1105 return 0; 1106 } 1107 1108 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1109 DeclContext*, 1110 ASTContext&); 1111 1112 /// Filters out lookup results that don't fall within the given scope 1113 /// as determined by isDeclInScope. 1114 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1115 bool ConsiderLinkage, 1116 bool AllowInlineNamespace) { 1117 LookupResult::Filter F = R.makeFilter(); 1118 while (F.hasNext()) { 1119 NamedDecl *D = F.next(); 1120 1121 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1122 continue; 1123 1124 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1125 continue; 1126 1127 F.erase(); 1128 } 1129 1130 F.done(); 1131 } 1132 1133 static bool isUsingDecl(NamedDecl *D) { 1134 return isa<UsingShadowDecl>(D) || 1135 isa<UnresolvedUsingTypenameDecl>(D) || 1136 isa<UnresolvedUsingValueDecl>(D); 1137 } 1138 1139 /// Removes using shadow declarations from the lookup results. 1140 static void RemoveUsingDecls(LookupResult &R) { 1141 LookupResult::Filter F = R.makeFilter(); 1142 while (F.hasNext()) 1143 if (isUsingDecl(F.next())) 1144 F.erase(); 1145 1146 F.done(); 1147 } 1148 1149 /// \brief Check for this common pattern: 1150 /// @code 1151 /// class S { 1152 /// S(const S&); // DO NOT IMPLEMENT 1153 /// void operator=(const S&); // DO NOT IMPLEMENT 1154 /// }; 1155 /// @endcode 1156 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1157 // FIXME: Should check for private access too but access is set after we get 1158 // the decl here. 1159 if (D->doesThisDeclarationHaveABody()) 1160 return false; 1161 1162 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1163 return CD->isCopyConstructor(); 1164 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1165 return Method->isCopyAssignmentOperator(); 1166 return false; 1167 } 1168 1169 // We need this to handle 1170 // 1171 // typedef struct { 1172 // void *foo() { return 0; } 1173 // } A; 1174 // 1175 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1176 // for example. If 'A', foo will have external linkage. If we have '*A', 1177 // foo will have no linkage. Since we can't know until we get to the end 1178 // of the typedef, this function finds out if D might have non-external linkage. 1179 // Callers should verify at the end of the TU if it D has external linkage or 1180 // not. 1181 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1182 const DeclContext *DC = D->getDeclContext(); 1183 while (!DC->isTranslationUnit()) { 1184 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1185 if (!RD->hasNameForLinkage()) 1186 return true; 1187 } 1188 DC = DC->getParent(); 1189 } 1190 1191 return !D->isExternallyVisible(); 1192 } 1193 1194 // FIXME: This needs to be refactored; some other isInMainFile users want 1195 // these semantics. 1196 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1197 if (S.TUKind != TU_Complete) 1198 return false; 1199 return S.SourceMgr.isInMainFile(Loc); 1200 } 1201 1202 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1203 assert(D); 1204 1205 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1206 return false; 1207 1208 // Ignore all entities declared within templates, and out-of-line definitions 1209 // of members of class templates. 1210 if (D->getDeclContext()->isDependentContext() || 1211 D->getLexicalDeclContext()->isDependentContext()) 1212 return false; 1213 1214 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1215 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1216 return false; 1217 1218 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1219 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1220 return false; 1221 } else { 1222 // 'static inline' functions are defined in headers; don't warn. 1223 if (FD->isInlineSpecified() && 1224 !isMainFileLoc(*this, FD->getLocation())) 1225 return false; 1226 } 1227 1228 if (FD->doesThisDeclarationHaveABody() && 1229 Context.DeclMustBeEmitted(FD)) 1230 return false; 1231 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1232 // Constants and utility variables are defined in headers with internal 1233 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1234 // like "inline".) 1235 if (!isMainFileLoc(*this, VD->getLocation())) 1236 return false; 1237 1238 if (Context.DeclMustBeEmitted(VD)) 1239 return false; 1240 1241 if (VD->isStaticDataMember() && 1242 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1243 return false; 1244 } else { 1245 return false; 1246 } 1247 1248 // Only warn for unused decls internal to the translation unit. 1249 return mightHaveNonExternalLinkage(D); 1250 } 1251 1252 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1253 if (!D) 1254 return; 1255 1256 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1257 const FunctionDecl *First = FD->getFirstDecl(); 1258 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1259 return; // First should already be in the vector. 1260 } 1261 1262 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1263 const VarDecl *First = VD->getFirstDecl(); 1264 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1265 return; // First should already be in the vector. 1266 } 1267 1268 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1269 UnusedFileScopedDecls.push_back(D); 1270 } 1271 1272 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1273 if (D->isInvalidDecl()) 1274 return false; 1275 1276 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1277 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1278 return false; 1279 1280 if (isa<LabelDecl>(D)) 1281 return true; 1282 1283 // White-list anything that isn't a local variable. 1284 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1285 !D->getDeclContext()->isFunctionOrMethod()) 1286 return false; 1287 1288 // Types of valid local variables should be complete, so this should succeed. 1289 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1290 1291 // White-list anything with an __attribute__((unused)) type. 1292 QualType Ty = VD->getType(); 1293 1294 // Only look at the outermost level of typedef. 1295 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1296 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1297 return false; 1298 } 1299 1300 // If we failed to complete the type for some reason, or if the type is 1301 // dependent, don't diagnose the variable. 1302 if (Ty->isIncompleteType() || Ty->isDependentType()) 1303 return false; 1304 1305 if (const TagType *TT = Ty->getAs<TagType>()) { 1306 const TagDecl *Tag = TT->getDecl(); 1307 if (Tag->hasAttr<UnusedAttr>()) 1308 return false; 1309 1310 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1311 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1312 return false; 1313 1314 if (const Expr *Init = VD->getInit()) { 1315 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1316 Init = Cleanups->getSubExpr(); 1317 const CXXConstructExpr *Construct = 1318 dyn_cast<CXXConstructExpr>(Init); 1319 if (Construct && !Construct->isElidable()) { 1320 CXXConstructorDecl *CD = Construct->getConstructor(); 1321 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1322 return false; 1323 } 1324 } 1325 } 1326 } 1327 1328 // TODO: __attribute__((unused)) templates? 1329 } 1330 1331 return true; 1332 } 1333 1334 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1335 FixItHint &Hint) { 1336 if (isa<LabelDecl>(D)) { 1337 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1338 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1339 if (AfterColon.isInvalid()) 1340 return; 1341 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1342 getCharRange(D->getLocStart(), AfterColon)); 1343 } 1344 return; 1345 } 1346 1347 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1348 /// unless they are marked attr(unused). 1349 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1350 FixItHint Hint; 1351 if (!ShouldDiagnoseUnusedDecl(D)) 1352 return; 1353 1354 GenerateFixForUnusedDecl(D, Context, Hint); 1355 1356 unsigned DiagID; 1357 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1358 DiagID = diag::warn_unused_exception_param; 1359 else if (isa<LabelDecl>(D)) 1360 DiagID = diag::warn_unused_label; 1361 else 1362 DiagID = diag::warn_unused_variable; 1363 1364 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1365 } 1366 1367 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1368 // Verify that we have no forward references left. If so, there was a goto 1369 // or address of a label taken, but no definition of it. Label fwd 1370 // definitions are indicated with a null substmt. 1371 if (L->getStmt() == 0) 1372 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1373 } 1374 1375 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1376 if (S->decl_empty()) return; 1377 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1378 "Scope shouldn't contain decls!"); 1379 1380 for (auto *TmpD : S->decls()) { 1381 assert(TmpD && "This decl didn't get pushed??"); 1382 1383 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1384 NamedDecl *D = cast<NamedDecl>(TmpD); 1385 1386 if (!D->getDeclName()) continue; 1387 1388 // Diagnose unused variables in this scope. 1389 if (!S->hasUnrecoverableErrorOccurred()) 1390 DiagnoseUnusedDecl(D); 1391 1392 // If this was a forward reference to a label, verify it was defined. 1393 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1394 CheckPoppedLabel(LD, *this); 1395 1396 // Remove this name from our lexical scope. 1397 IdResolver.RemoveDecl(D); 1398 } 1399 } 1400 1401 /// \brief Look for an Objective-C class in the translation unit. 1402 /// 1403 /// \param Id The name of the Objective-C class we're looking for. If 1404 /// typo-correction fixes this name, the Id will be updated 1405 /// to the fixed name. 1406 /// 1407 /// \param IdLoc The location of the name in the translation unit. 1408 /// 1409 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1410 /// if there is no class with the given name. 1411 /// 1412 /// \returns The declaration of the named Objective-C class, or NULL if the 1413 /// class could not be found. 1414 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1415 SourceLocation IdLoc, 1416 bool DoTypoCorrection) { 1417 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1418 // creation from this context. 1419 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1420 1421 if (!IDecl && DoTypoCorrection) { 1422 // Perform typo correction at the given location, but only if we 1423 // find an Objective-C class name. 1424 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1425 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1426 LookupOrdinaryName, TUScope, NULL, 1427 Validator, CTK_ErrorRecovery)) { 1428 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1429 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1430 Id = IDecl->getIdentifier(); 1431 } 1432 } 1433 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1434 // This routine must always return a class definition, if any. 1435 if (Def && Def->getDefinition()) 1436 Def = Def->getDefinition(); 1437 return Def; 1438 } 1439 1440 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1441 /// from S, where a non-field would be declared. This routine copes 1442 /// with the difference between C and C++ scoping rules in structs and 1443 /// unions. For example, the following code is well-formed in C but 1444 /// ill-formed in C++: 1445 /// @code 1446 /// struct S6 { 1447 /// enum { BAR } e; 1448 /// }; 1449 /// 1450 /// void test_S6() { 1451 /// struct S6 a; 1452 /// a.e = BAR; 1453 /// } 1454 /// @endcode 1455 /// For the declaration of BAR, this routine will return a different 1456 /// scope. The scope S will be the scope of the unnamed enumeration 1457 /// within S6. In C++, this routine will return the scope associated 1458 /// with S6, because the enumeration's scope is a transparent 1459 /// context but structures can contain non-field names. In C, this 1460 /// routine will return the translation unit scope, since the 1461 /// enumeration's scope is a transparent context and structures cannot 1462 /// contain non-field names. 1463 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1464 while (((S->getFlags() & Scope::DeclScope) == 0) || 1465 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1466 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1467 S = S->getParent(); 1468 return S; 1469 } 1470 1471 /// \brief Looks up the declaration of "struct objc_super" and 1472 /// saves it for later use in building builtin declaration of 1473 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1474 /// pre-existing declaration exists no action takes place. 1475 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1476 IdentifierInfo *II) { 1477 if (!II->isStr("objc_msgSendSuper")) 1478 return; 1479 ASTContext &Context = ThisSema.Context; 1480 1481 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1482 SourceLocation(), Sema::LookupTagName); 1483 ThisSema.LookupName(Result, S); 1484 if (Result.getResultKind() == LookupResult::Found) 1485 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1486 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1487 } 1488 1489 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1490 /// file scope. lazily create a decl for it. ForRedeclaration is true 1491 /// if we're creating this built-in in anticipation of redeclaring the 1492 /// built-in. 1493 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1494 Scope *S, bool ForRedeclaration, 1495 SourceLocation Loc) { 1496 LookupPredefedObjCSuperType(*this, S, II); 1497 1498 Builtin::ID BID = (Builtin::ID)bid; 1499 1500 ASTContext::GetBuiltinTypeError Error; 1501 QualType R = Context.GetBuiltinType(BID, Error); 1502 switch (Error) { 1503 case ASTContext::GE_None: 1504 // Okay 1505 break; 1506 1507 case ASTContext::GE_Missing_stdio: 1508 if (ForRedeclaration) 1509 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1510 << Context.BuiltinInfo.GetName(BID); 1511 return 0; 1512 1513 case ASTContext::GE_Missing_setjmp: 1514 if (ForRedeclaration) 1515 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1516 << Context.BuiltinInfo.GetName(BID); 1517 return 0; 1518 1519 case ASTContext::GE_Missing_ucontext: 1520 if (ForRedeclaration) 1521 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1522 << Context.BuiltinInfo.GetName(BID); 1523 return 0; 1524 } 1525 1526 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1527 Diag(Loc, diag::ext_implicit_lib_function_decl) 1528 << Context.BuiltinInfo.GetName(BID) 1529 << R; 1530 if (Context.BuiltinInfo.getHeaderName(BID) && 1531 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1532 != DiagnosticsEngine::Ignored) 1533 Diag(Loc, diag::note_please_include_header) 1534 << Context.BuiltinInfo.getHeaderName(BID) 1535 << Context.BuiltinInfo.GetName(BID); 1536 } 1537 1538 DeclContext *Parent = Context.getTranslationUnitDecl(); 1539 if (getLangOpts().CPlusPlus) { 1540 LinkageSpecDecl *CLinkageDecl = 1541 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1542 LinkageSpecDecl::lang_c, false); 1543 CLinkageDecl->setImplicit(); 1544 Parent->addDecl(CLinkageDecl); 1545 Parent = CLinkageDecl; 1546 } 1547 1548 FunctionDecl *New = FunctionDecl::Create(Context, 1549 Parent, 1550 Loc, Loc, II, R, /*TInfo=*/0, 1551 SC_Extern, 1552 false, 1553 /*hasPrototype=*/true); 1554 New->setImplicit(); 1555 1556 // Create Decl objects for each parameter, adding them to the 1557 // FunctionDecl. 1558 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1559 SmallVector<ParmVarDecl*, 16> Params; 1560 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1561 ParmVarDecl *parm = 1562 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1563 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0); 1564 parm->setScopeInfo(0, i); 1565 Params.push_back(parm); 1566 } 1567 New->setParams(Params); 1568 } 1569 1570 AddKnownFunctionAttributes(New); 1571 RegisterLocallyScopedExternCDecl(New, S); 1572 1573 // TUScope is the translation-unit scope to insert this function into. 1574 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1575 // relate Scopes to DeclContexts, and probably eliminate CurContext 1576 // entirely, but we're not there yet. 1577 DeclContext *SavedContext = CurContext; 1578 CurContext = Parent; 1579 PushOnScopeChains(New, TUScope); 1580 CurContext = SavedContext; 1581 return New; 1582 } 1583 1584 /// \brief Filter out any previous declarations that the given declaration 1585 /// should not consider because they are not permitted to conflict, e.g., 1586 /// because they come from hidden sub-modules and do not refer to the same 1587 /// entity. 1588 static void filterNonConflictingPreviousDecls(ASTContext &context, 1589 NamedDecl *decl, 1590 LookupResult &previous){ 1591 // This is only interesting when modules are enabled. 1592 if (!context.getLangOpts().Modules) 1593 return; 1594 1595 // Empty sets are uninteresting. 1596 if (previous.empty()) 1597 return; 1598 1599 LookupResult::Filter filter = previous.makeFilter(); 1600 while (filter.hasNext()) { 1601 NamedDecl *old = filter.next(); 1602 1603 // Non-hidden declarations are never ignored. 1604 if (!old->isHidden()) 1605 continue; 1606 1607 if (!old->isExternallyVisible()) 1608 filter.erase(); 1609 } 1610 1611 filter.done(); 1612 } 1613 1614 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1615 QualType OldType; 1616 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1617 OldType = OldTypedef->getUnderlyingType(); 1618 else 1619 OldType = Context.getTypeDeclType(Old); 1620 QualType NewType = New->getUnderlyingType(); 1621 1622 if (NewType->isVariablyModifiedType()) { 1623 // Must not redefine a typedef with a variably-modified type. 1624 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1625 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1626 << Kind << NewType; 1627 if (Old->getLocation().isValid()) 1628 Diag(Old->getLocation(), diag::note_previous_definition); 1629 New->setInvalidDecl(); 1630 return true; 1631 } 1632 1633 if (OldType != NewType && 1634 !OldType->isDependentType() && 1635 !NewType->isDependentType() && 1636 !Context.hasSameType(OldType, NewType)) { 1637 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1638 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1639 << Kind << NewType << OldType; 1640 if (Old->getLocation().isValid()) 1641 Diag(Old->getLocation(), diag::note_previous_definition); 1642 New->setInvalidDecl(); 1643 return true; 1644 } 1645 return false; 1646 } 1647 1648 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1649 /// same name and scope as a previous declaration 'Old'. Figure out 1650 /// how to resolve this situation, merging decls or emitting 1651 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1652 /// 1653 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1654 // If the new decl is known invalid already, don't bother doing any 1655 // merging checks. 1656 if (New->isInvalidDecl()) return; 1657 1658 // Allow multiple definitions for ObjC built-in typedefs. 1659 // FIXME: Verify the underlying types are equivalent! 1660 if (getLangOpts().ObjC1) { 1661 const IdentifierInfo *TypeID = New->getIdentifier(); 1662 switch (TypeID->getLength()) { 1663 default: break; 1664 case 2: 1665 { 1666 if (!TypeID->isStr("id")) 1667 break; 1668 QualType T = New->getUnderlyingType(); 1669 if (!T->isPointerType()) 1670 break; 1671 if (!T->isVoidPointerType()) { 1672 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1673 if (!PT->isStructureType()) 1674 break; 1675 } 1676 Context.setObjCIdRedefinitionType(T); 1677 // Install the built-in type for 'id', ignoring the current definition. 1678 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1679 return; 1680 } 1681 case 5: 1682 if (!TypeID->isStr("Class")) 1683 break; 1684 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1685 // Install the built-in type for 'Class', ignoring the current definition. 1686 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1687 return; 1688 case 3: 1689 if (!TypeID->isStr("SEL")) 1690 break; 1691 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1692 // Install the built-in type for 'SEL', ignoring the current definition. 1693 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1694 return; 1695 } 1696 // Fall through - the typedef name was not a builtin type. 1697 } 1698 1699 // Verify the old decl was also a type. 1700 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1701 if (!Old) { 1702 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1703 << New->getDeclName(); 1704 1705 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1706 if (OldD->getLocation().isValid()) 1707 Diag(OldD->getLocation(), diag::note_previous_definition); 1708 1709 return New->setInvalidDecl(); 1710 } 1711 1712 // If the old declaration is invalid, just give up here. 1713 if (Old->isInvalidDecl()) 1714 return New->setInvalidDecl(); 1715 1716 // If the typedef types are not identical, reject them in all languages and 1717 // with any extensions enabled. 1718 if (isIncompatibleTypedef(Old, New)) 1719 return; 1720 1721 // The types match. Link up the redeclaration chain and merge attributes if 1722 // the old declaration was a typedef. 1723 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1724 New->setPreviousDecl(Typedef); 1725 mergeDeclAttributes(New, Old); 1726 } 1727 1728 if (getLangOpts().MicrosoftExt) 1729 return; 1730 1731 if (getLangOpts().CPlusPlus) { 1732 // C++ [dcl.typedef]p2: 1733 // In a given non-class scope, a typedef specifier can be used to 1734 // redefine the name of any type declared in that scope to refer 1735 // to the type to which it already refers. 1736 if (!isa<CXXRecordDecl>(CurContext)) 1737 return; 1738 1739 // C++0x [dcl.typedef]p4: 1740 // In a given class scope, a typedef specifier can be used to redefine 1741 // any class-name declared in that scope that is not also a typedef-name 1742 // to refer to the type to which it already refers. 1743 // 1744 // This wording came in via DR424, which was a correction to the 1745 // wording in DR56, which accidentally banned code like: 1746 // 1747 // struct S { 1748 // typedef struct A { } A; 1749 // }; 1750 // 1751 // in the C++03 standard. We implement the C++0x semantics, which 1752 // allow the above but disallow 1753 // 1754 // struct S { 1755 // typedef int I; 1756 // typedef int I; 1757 // }; 1758 // 1759 // since that was the intent of DR56. 1760 if (!isa<TypedefNameDecl>(Old)) 1761 return; 1762 1763 Diag(New->getLocation(), diag::err_redefinition) 1764 << New->getDeclName(); 1765 Diag(Old->getLocation(), diag::note_previous_definition); 1766 return New->setInvalidDecl(); 1767 } 1768 1769 // Modules always permit redefinition of typedefs, as does C11. 1770 if (getLangOpts().Modules || getLangOpts().C11) 1771 return; 1772 1773 // If we have a redefinition of a typedef in C, emit a warning. This warning 1774 // is normally mapped to an error, but can be controlled with 1775 // -Wtypedef-redefinition. If either the original or the redefinition is 1776 // in a system header, don't emit this for compatibility with GCC. 1777 if (getDiagnostics().getSuppressSystemWarnings() && 1778 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1779 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1780 return; 1781 1782 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1783 << New->getDeclName(); 1784 Diag(Old->getLocation(), diag::note_previous_definition); 1785 return; 1786 } 1787 1788 /// DeclhasAttr - returns true if decl Declaration already has the target 1789 /// attribute. 1790 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1791 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1792 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1793 for (const auto *i : D->attrs()) 1794 if (i->getKind() == A->getKind()) { 1795 if (Ann) { 1796 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1797 return true; 1798 continue; 1799 } 1800 // FIXME: Don't hardcode this check 1801 if (OA && isa<OwnershipAttr>(i)) 1802 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 1803 return true; 1804 } 1805 1806 return false; 1807 } 1808 1809 static bool isAttributeTargetADefinition(Decl *D) { 1810 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1811 return VD->isThisDeclarationADefinition(); 1812 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1813 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1814 return true; 1815 } 1816 1817 /// Merge alignment attributes from \p Old to \p New, taking into account the 1818 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1819 /// 1820 /// \return \c true if any attributes were added to \p New. 1821 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1822 // Look for alignas attributes on Old, and pick out whichever attribute 1823 // specifies the strictest alignment requirement. 1824 AlignedAttr *OldAlignasAttr = 0; 1825 AlignedAttr *OldStrictestAlignAttr = 0; 1826 unsigned OldAlign = 0; 1827 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 1828 // FIXME: We have no way of representing inherited dependent alignments 1829 // in a case like: 1830 // template<int A, int B> struct alignas(A) X; 1831 // template<int A, int B> struct alignas(B) X {}; 1832 // For now, we just ignore any alignas attributes which are not on the 1833 // definition in such a case. 1834 if (I->isAlignmentDependent()) 1835 return false; 1836 1837 if (I->isAlignas()) 1838 OldAlignasAttr = I; 1839 1840 unsigned Align = I->getAlignment(S.Context); 1841 if (Align > OldAlign) { 1842 OldAlign = Align; 1843 OldStrictestAlignAttr = I; 1844 } 1845 } 1846 1847 // Look for alignas attributes on New. 1848 AlignedAttr *NewAlignasAttr = 0; 1849 unsigned NewAlign = 0; 1850 for (auto *I : New->specific_attrs<AlignedAttr>()) { 1851 if (I->isAlignmentDependent()) 1852 return false; 1853 1854 if (I->isAlignas()) 1855 NewAlignasAttr = I; 1856 1857 unsigned Align = I->getAlignment(S.Context); 1858 if (Align > NewAlign) 1859 NewAlign = Align; 1860 } 1861 1862 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1863 // Both declarations have 'alignas' attributes. We require them to match. 1864 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1865 // fall short. (If two declarations both have alignas, they must both match 1866 // every definition, and so must match each other if there is a definition.) 1867 1868 // If either declaration only contains 'alignas(0)' specifiers, then it 1869 // specifies the natural alignment for the type. 1870 if (OldAlign == 0 || NewAlign == 0) { 1871 QualType Ty; 1872 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1873 Ty = VD->getType(); 1874 else 1875 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1876 1877 if (OldAlign == 0) 1878 OldAlign = S.Context.getTypeAlign(Ty); 1879 if (NewAlign == 0) 1880 NewAlign = S.Context.getTypeAlign(Ty); 1881 } 1882 1883 if (OldAlign != NewAlign) { 1884 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1885 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1886 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1887 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1888 } 1889 } 1890 1891 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1892 // C++11 [dcl.align]p6: 1893 // if any declaration of an entity has an alignment-specifier, 1894 // every defining declaration of that entity shall specify an 1895 // equivalent alignment. 1896 // C11 6.7.5/7: 1897 // If the definition of an object does not have an alignment 1898 // specifier, any other declaration of that object shall also 1899 // have no alignment specifier. 1900 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1901 << OldAlignasAttr; 1902 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1903 << OldAlignasAttr; 1904 } 1905 1906 bool AnyAdded = false; 1907 1908 // Ensure we have an attribute representing the strictest alignment. 1909 if (OldAlign > NewAlign) { 1910 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1911 Clone->setInherited(true); 1912 New->addAttr(Clone); 1913 AnyAdded = true; 1914 } 1915 1916 // Ensure we have an alignas attribute if the old declaration had one. 1917 if (OldAlignasAttr && !NewAlignasAttr && 1918 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1919 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1920 Clone->setInherited(true); 1921 New->addAttr(Clone); 1922 AnyAdded = true; 1923 } 1924 1925 return AnyAdded; 1926 } 1927 1928 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 1929 const InheritableAttr *Attr, bool Override) { 1930 InheritableAttr *NewAttr = nullptr; 1931 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1932 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 1933 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1934 AA->getIntroduced(), AA->getDeprecated(), 1935 AA->getObsoleted(), AA->getUnavailable(), 1936 AA->getMessage(), Override, 1937 AttrSpellingListIndex); 1938 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 1939 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1940 AttrSpellingListIndex); 1941 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1942 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1943 AttrSpellingListIndex); 1944 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1945 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1946 AttrSpellingListIndex); 1947 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1948 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1949 AttrSpellingListIndex); 1950 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 1951 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1952 FA->getFormatIdx(), FA->getFirstArg(), 1953 AttrSpellingListIndex); 1954 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 1955 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1956 AttrSpellingListIndex); 1957 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 1958 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 1959 AttrSpellingListIndex, 1960 IA->getSemanticSpelling()); 1961 else if (isa<AlignedAttr>(Attr)) 1962 // AlignedAttrs are handled separately, because we need to handle all 1963 // such attributes on a declaration at the same time. 1964 NewAttr = nullptr; 1965 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 1966 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1967 1968 if (NewAttr) { 1969 NewAttr->setInherited(true); 1970 D->addAttr(NewAttr); 1971 return true; 1972 } 1973 1974 return false; 1975 } 1976 1977 static const Decl *getDefinition(const Decl *D) { 1978 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1979 return TD->getDefinition(); 1980 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1981 const VarDecl *Def = VD->getDefinition(); 1982 if (Def) 1983 return Def; 1984 return VD->getActingDefinition(); 1985 } 1986 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1987 const FunctionDecl* Def; 1988 if (FD->isDefined(Def)) 1989 return Def; 1990 } 1991 return NULL; 1992 } 1993 1994 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 1995 for (const auto *Attribute : D->attrs()) 1996 if (Attribute->getKind() == Kind) 1997 return true; 1998 return false; 1999 } 2000 2001 /// checkNewAttributesAfterDef - If we already have a definition, check that 2002 /// there are no new attributes in this declaration. 2003 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2004 if (!New->hasAttrs()) 2005 return; 2006 2007 const Decl *Def = getDefinition(Old); 2008 if (!Def || Def == New) 2009 return; 2010 2011 AttrVec &NewAttributes = New->getAttrs(); 2012 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2013 const Attr *NewAttribute = NewAttributes[I]; 2014 2015 if (isa<AliasAttr>(NewAttribute)) { 2016 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2017 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2018 else { 2019 VarDecl *VD = cast<VarDecl>(New); 2020 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2021 VarDecl::TentativeDefinition 2022 ? diag::err_alias_after_tentative 2023 : diag::err_redefinition; 2024 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2025 S.Diag(Def->getLocation(), diag::note_previous_definition); 2026 VD->setInvalidDecl(); 2027 } 2028 ++I; 2029 continue; 2030 } 2031 2032 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2033 // Tentative definitions are only interesting for the alias check above. 2034 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2035 ++I; 2036 continue; 2037 } 2038 } 2039 2040 if (hasAttribute(Def, NewAttribute->getKind())) { 2041 ++I; 2042 continue; // regular attr merging will take care of validating this. 2043 } 2044 2045 if (isa<C11NoReturnAttr>(NewAttribute)) { 2046 // C's _Noreturn is allowed to be added to a function after it is defined. 2047 ++I; 2048 continue; 2049 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2050 if (AA->isAlignas()) { 2051 // C++11 [dcl.align]p6: 2052 // if any declaration of an entity has an alignment-specifier, 2053 // every defining declaration of that entity shall specify an 2054 // equivalent alignment. 2055 // C11 6.7.5/7: 2056 // If the definition of an object does not have an alignment 2057 // specifier, any other declaration of that object shall also 2058 // have no alignment specifier. 2059 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2060 << AA; 2061 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2062 << AA; 2063 NewAttributes.erase(NewAttributes.begin() + I); 2064 --E; 2065 continue; 2066 } 2067 } 2068 2069 S.Diag(NewAttribute->getLocation(), 2070 diag::warn_attribute_precede_definition); 2071 S.Diag(Def->getLocation(), diag::note_previous_definition); 2072 NewAttributes.erase(NewAttributes.begin() + I); 2073 --E; 2074 } 2075 } 2076 2077 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2078 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2079 AvailabilityMergeKind AMK) { 2080 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2081 UsedAttr *NewAttr = OldAttr->clone(Context); 2082 NewAttr->setInherited(true); 2083 New->addAttr(NewAttr); 2084 } 2085 2086 if (!Old->hasAttrs() && !New->hasAttrs()) 2087 return; 2088 2089 // attributes declared post-definition are currently ignored 2090 checkNewAttributesAfterDef(*this, New, Old); 2091 2092 if (!Old->hasAttrs()) 2093 return; 2094 2095 bool foundAny = New->hasAttrs(); 2096 2097 // Ensure that any moving of objects within the allocated map is done before 2098 // we process them. 2099 if (!foundAny) New->setAttrs(AttrVec()); 2100 2101 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2102 bool Override = false; 2103 // Ignore deprecated/unavailable/availability attributes if requested. 2104 if (isa<DeprecatedAttr>(I) || 2105 isa<UnavailableAttr>(I) || 2106 isa<AvailabilityAttr>(I)) { 2107 switch (AMK) { 2108 case AMK_None: 2109 continue; 2110 2111 case AMK_Redeclaration: 2112 break; 2113 2114 case AMK_Override: 2115 Override = true; 2116 break; 2117 } 2118 } 2119 2120 // Already handled. 2121 if (isa<UsedAttr>(I)) 2122 continue; 2123 2124 if (mergeDeclAttribute(*this, New, I, Override)) 2125 foundAny = true; 2126 } 2127 2128 if (mergeAlignedAttrs(*this, New, Old)) 2129 foundAny = true; 2130 2131 if (!foundAny) New->dropAttrs(); 2132 } 2133 2134 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2135 /// to the new one. 2136 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2137 const ParmVarDecl *oldDecl, 2138 Sema &S) { 2139 // C++11 [dcl.attr.depend]p2: 2140 // The first declaration of a function shall specify the 2141 // carries_dependency attribute for its declarator-id if any declaration 2142 // of the function specifies the carries_dependency attribute. 2143 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2144 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2145 S.Diag(CDA->getLocation(), 2146 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2147 // Find the first declaration of the parameter. 2148 // FIXME: Should we build redeclaration chains for function parameters? 2149 const FunctionDecl *FirstFD = 2150 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2151 const ParmVarDecl *FirstVD = 2152 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2153 S.Diag(FirstVD->getLocation(), 2154 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2155 } 2156 2157 if (!oldDecl->hasAttrs()) 2158 return; 2159 2160 bool foundAny = newDecl->hasAttrs(); 2161 2162 // Ensure that any moving of objects within the allocated map is 2163 // done before we process them. 2164 if (!foundAny) newDecl->setAttrs(AttrVec()); 2165 2166 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2167 if (!DeclHasAttr(newDecl, I)) { 2168 InheritableAttr *newAttr = 2169 cast<InheritableParamAttr>(I->clone(S.Context)); 2170 newAttr->setInherited(true); 2171 newDecl->addAttr(newAttr); 2172 foundAny = true; 2173 } 2174 } 2175 2176 if (!foundAny) newDecl->dropAttrs(); 2177 } 2178 2179 namespace { 2180 2181 /// Used in MergeFunctionDecl to keep track of function parameters in 2182 /// C. 2183 struct GNUCompatibleParamWarning { 2184 ParmVarDecl *OldParm; 2185 ParmVarDecl *NewParm; 2186 QualType PromotedType; 2187 }; 2188 2189 } 2190 2191 /// getSpecialMember - get the special member enum for a method. 2192 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2193 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2194 if (Ctor->isDefaultConstructor()) 2195 return Sema::CXXDefaultConstructor; 2196 2197 if (Ctor->isCopyConstructor()) 2198 return Sema::CXXCopyConstructor; 2199 2200 if (Ctor->isMoveConstructor()) 2201 return Sema::CXXMoveConstructor; 2202 } else if (isa<CXXDestructorDecl>(MD)) { 2203 return Sema::CXXDestructor; 2204 } else if (MD->isCopyAssignmentOperator()) { 2205 return Sema::CXXCopyAssignment; 2206 } else if (MD->isMoveAssignmentOperator()) { 2207 return Sema::CXXMoveAssignment; 2208 } 2209 2210 return Sema::CXXInvalid; 2211 } 2212 2213 /// canRedefineFunction - checks if a function can be redefined. Currently, 2214 /// only extern inline functions can be redefined, and even then only in 2215 /// GNU89 mode. 2216 static bool canRedefineFunction(const FunctionDecl *FD, 2217 const LangOptions& LangOpts) { 2218 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2219 !LangOpts.CPlusPlus && 2220 FD->isInlineSpecified() && 2221 FD->getStorageClass() == SC_Extern); 2222 } 2223 2224 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2225 const AttributedType *AT = T->getAs<AttributedType>(); 2226 while (AT && !AT->isCallingConv()) 2227 AT = AT->getModifiedType()->getAs<AttributedType>(); 2228 return AT; 2229 } 2230 2231 template <typename T> 2232 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2233 const DeclContext *DC = Old->getDeclContext(); 2234 if (DC->isRecord()) 2235 return false; 2236 2237 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2238 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2239 return true; 2240 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2241 return true; 2242 return false; 2243 } 2244 2245 /// MergeFunctionDecl - We just parsed a function 'New' from 2246 /// declarator D which has the same name and scope as a previous 2247 /// declaration 'Old'. Figure out how to resolve this situation, 2248 /// merging decls or emitting diagnostics as appropriate. 2249 /// 2250 /// In C++, New and Old must be declarations that are not 2251 /// overloaded. Use IsOverload to determine whether New and Old are 2252 /// overloaded, and to select the Old declaration that New should be 2253 /// merged with. 2254 /// 2255 /// Returns true if there was an error, false otherwise. 2256 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2257 Scope *S, bool MergeTypeWithOld) { 2258 // Verify the old decl was also a function. 2259 FunctionDecl *Old = OldD->getAsFunction(); 2260 if (!Old) { 2261 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2262 if (New->getFriendObjectKind()) { 2263 Diag(New->getLocation(), diag::err_using_decl_friend); 2264 Diag(Shadow->getTargetDecl()->getLocation(), 2265 diag::note_using_decl_target); 2266 Diag(Shadow->getUsingDecl()->getLocation(), 2267 diag::note_using_decl) << 0; 2268 return true; 2269 } 2270 2271 // C++11 [namespace.udecl]p14: 2272 // If a function declaration in namespace scope or block scope has the 2273 // same name and the same parameter-type-list as a function introduced 2274 // by a using-declaration, and the declarations do not declare the same 2275 // function, the program is ill-formed. 2276 2277 // Check whether the two declarations might declare the same function. 2278 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2279 if (Old && 2280 !Old->getDeclContext()->getRedeclContext()->Equals( 2281 New->getDeclContext()->getRedeclContext()) && 2282 !(Old->isExternC() && New->isExternC())) 2283 Old = 0; 2284 2285 if (!Old) { 2286 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2287 Diag(Shadow->getTargetDecl()->getLocation(), 2288 diag::note_using_decl_target); 2289 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2290 return true; 2291 } 2292 OldD = Old; 2293 } else { 2294 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2295 << New->getDeclName(); 2296 Diag(OldD->getLocation(), diag::note_previous_definition); 2297 return true; 2298 } 2299 } 2300 2301 // If the old declaration is invalid, just give up here. 2302 if (Old->isInvalidDecl()) 2303 return true; 2304 2305 // Determine whether the previous declaration was a definition, 2306 // implicit declaration, or a declaration. 2307 diag::kind PrevDiag; 2308 SourceLocation OldLocation = Old->getLocation(); 2309 if (Old->isThisDeclarationADefinition()) 2310 PrevDiag = diag::note_previous_definition; 2311 else if (Old->isImplicit()) { 2312 PrevDiag = diag::note_previous_implicit_declaration; 2313 if (OldLocation.isInvalid()) 2314 OldLocation = New->getLocation(); 2315 } else 2316 PrevDiag = diag::note_previous_declaration; 2317 2318 // Don't complain about this if we're in GNU89 mode and the old function 2319 // is an extern inline function. 2320 // Don't complain about specializations. They are not supposed to have 2321 // storage classes. 2322 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2323 New->getStorageClass() == SC_Static && 2324 Old->hasExternalFormalLinkage() && 2325 !New->getTemplateSpecializationInfo() && 2326 !canRedefineFunction(Old, getLangOpts())) { 2327 if (getLangOpts().MicrosoftExt) { 2328 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2329 Diag(OldLocation, PrevDiag); 2330 } else { 2331 Diag(New->getLocation(), diag::err_static_non_static) << New; 2332 Diag(OldLocation, PrevDiag); 2333 return true; 2334 } 2335 } 2336 2337 2338 // If a function is first declared with a calling convention, but is later 2339 // declared or defined without one, all following decls assume the calling 2340 // convention of the first. 2341 // 2342 // It's OK if a function is first declared without a calling convention, 2343 // but is later declared or defined with the default calling convention. 2344 // 2345 // To test if either decl has an explicit calling convention, we look for 2346 // AttributedType sugar nodes on the type as written. If they are missing or 2347 // were canonicalized away, we assume the calling convention was implicit. 2348 // 2349 // Note also that we DO NOT return at this point, because we still have 2350 // other tests to run. 2351 QualType OldQType = Context.getCanonicalType(Old->getType()); 2352 QualType NewQType = Context.getCanonicalType(New->getType()); 2353 const FunctionType *OldType = cast<FunctionType>(OldQType); 2354 const FunctionType *NewType = cast<FunctionType>(NewQType); 2355 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2356 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2357 bool RequiresAdjustment = false; 2358 2359 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2360 FunctionDecl *First = Old->getFirstDecl(); 2361 const FunctionType *FT = 2362 First->getType().getCanonicalType()->castAs<FunctionType>(); 2363 FunctionType::ExtInfo FI = FT->getExtInfo(); 2364 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2365 if (!NewCCExplicit) { 2366 // Inherit the CC from the previous declaration if it was specified 2367 // there but not here. 2368 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2369 RequiresAdjustment = true; 2370 } else { 2371 // Calling conventions aren't compatible, so complain. 2372 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2373 Diag(New->getLocation(), diag::err_cconv_change) 2374 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2375 << !FirstCCExplicit 2376 << (!FirstCCExplicit ? "" : 2377 FunctionType::getNameForCallConv(FI.getCC())); 2378 2379 // Put the note on the first decl, since it is the one that matters. 2380 Diag(First->getLocation(), diag::note_previous_declaration); 2381 return true; 2382 } 2383 } 2384 2385 // FIXME: diagnose the other way around? 2386 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2387 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2388 RequiresAdjustment = true; 2389 } 2390 2391 // Merge regparm attribute. 2392 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2393 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2394 if (NewTypeInfo.getHasRegParm()) { 2395 Diag(New->getLocation(), diag::err_regparm_mismatch) 2396 << NewType->getRegParmType() 2397 << OldType->getRegParmType(); 2398 Diag(OldLocation, diag::note_previous_declaration); 2399 return true; 2400 } 2401 2402 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2403 RequiresAdjustment = true; 2404 } 2405 2406 // Merge ns_returns_retained attribute. 2407 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2408 if (NewTypeInfo.getProducesResult()) { 2409 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2410 Diag(OldLocation, diag::note_previous_declaration); 2411 return true; 2412 } 2413 2414 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2415 RequiresAdjustment = true; 2416 } 2417 2418 if (RequiresAdjustment) { 2419 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2420 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2421 New->setType(QualType(AdjustedType, 0)); 2422 NewQType = Context.getCanonicalType(New->getType()); 2423 NewType = cast<FunctionType>(NewQType); 2424 } 2425 2426 // If this redeclaration makes the function inline, we may need to add it to 2427 // UndefinedButUsed. 2428 if (!Old->isInlined() && New->isInlined() && 2429 !New->hasAttr<GNUInlineAttr>() && 2430 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2431 Old->isUsed(false) && 2432 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2433 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2434 SourceLocation())); 2435 2436 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2437 // about it. 2438 if (New->hasAttr<GNUInlineAttr>() && 2439 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2440 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2441 } 2442 2443 if (getLangOpts().CPlusPlus) { 2444 // (C++98 13.1p2): 2445 // Certain function declarations cannot be overloaded: 2446 // -- Function declarations that differ only in the return type 2447 // cannot be overloaded. 2448 2449 // Go back to the type source info to compare the declared return types, 2450 // per C++1y [dcl.type.auto]p13: 2451 // Redeclarations or specializations of a function or function template 2452 // with a declared return type that uses a placeholder type shall also 2453 // use that placeholder, not a deduced type. 2454 QualType OldDeclaredReturnType = 2455 (Old->getTypeSourceInfo() 2456 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2457 : OldType)->getReturnType(); 2458 QualType NewDeclaredReturnType = 2459 (New->getTypeSourceInfo() 2460 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2461 : NewType)->getReturnType(); 2462 QualType ResQT; 2463 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2464 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2465 New->isLocalExternDecl())) { 2466 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2467 OldDeclaredReturnType->isObjCObjectPointerType()) 2468 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2469 if (ResQT.isNull()) { 2470 if (New->isCXXClassMember() && New->isOutOfLine()) 2471 Diag(New->getLocation(), 2472 diag::err_member_def_does_not_match_ret_type) << New; 2473 else 2474 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2475 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2476 return true; 2477 } 2478 else 2479 NewQType = ResQT; 2480 } 2481 2482 QualType OldReturnType = OldType->getReturnType(); 2483 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2484 if (OldReturnType != NewReturnType) { 2485 // If this function has a deduced return type and has already been 2486 // defined, copy the deduced value from the old declaration. 2487 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2488 if (OldAT && OldAT->isDeduced()) { 2489 New->setType( 2490 SubstAutoType(New->getType(), 2491 OldAT->isDependentType() ? Context.DependentTy 2492 : OldAT->getDeducedType())); 2493 NewQType = Context.getCanonicalType( 2494 SubstAutoType(NewQType, 2495 OldAT->isDependentType() ? Context.DependentTy 2496 : OldAT->getDeducedType())); 2497 } 2498 } 2499 2500 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2501 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2502 if (OldMethod && NewMethod) { 2503 // Preserve triviality. 2504 NewMethod->setTrivial(OldMethod->isTrivial()); 2505 2506 // MSVC allows explicit template specialization at class scope: 2507 // 2 CXXMethodDecls referring to the same function will be injected. 2508 // We don't want a redeclaration error. 2509 bool IsClassScopeExplicitSpecialization = 2510 OldMethod->isFunctionTemplateSpecialization() && 2511 NewMethod->isFunctionTemplateSpecialization(); 2512 bool isFriend = NewMethod->getFriendObjectKind(); 2513 2514 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2515 !IsClassScopeExplicitSpecialization) { 2516 // -- Member function declarations with the same name and the 2517 // same parameter types cannot be overloaded if any of them 2518 // is a static member function declaration. 2519 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2520 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2521 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2522 return true; 2523 } 2524 2525 // C++ [class.mem]p1: 2526 // [...] A member shall not be declared twice in the 2527 // member-specification, except that a nested class or member 2528 // class template can be declared and then later defined. 2529 if (ActiveTemplateInstantiations.empty()) { 2530 unsigned NewDiag; 2531 if (isa<CXXConstructorDecl>(OldMethod)) 2532 NewDiag = diag::err_constructor_redeclared; 2533 else if (isa<CXXDestructorDecl>(NewMethod)) 2534 NewDiag = diag::err_destructor_redeclared; 2535 else if (isa<CXXConversionDecl>(NewMethod)) 2536 NewDiag = diag::err_conv_function_redeclared; 2537 else 2538 NewDiag = diag::err_member_redeclared; 2539 2540 Diag(New->getLocation(), NewDiag); 2541 } else { 2542 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2543 << New << New->getType(); 2544 } 2545 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2546 2547 // Complain if this is an explicit declaration of a special 2548 // member that was initially declared implicitly. 2549 // 2550 // As an exception, it's okay to befriend such methods in order 2551 // to permit the implicit constructor/destructor/operator calls. 2552 } else if (OldMethod->isImplicit()) { 2553 if (isFriend) { 2554 NewMethod->setImplicit(); 2555 } else { 2556 Diag(NewMethod->getLocation(), 2557 diag::err_definition_of_implicitly_declared_member) 2558 << New << getSpecialMember(OldMethod); 2559 return true; 2560 } 2561 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2562 Diag(NewMethod->getLocation(), 2563 diag::err_definition_of_explicitly_defaulted_member) 2564 << getSpecialMember(OldMethod); 2565 return true; 2566 } 2567 } 2568 2569 // C++11 [dcl.attr.noreturn]p1: 2570 // The first declaration of a function shall specify the noreturn 2571 // attribute if any declaration of that function specifies the noreturn 2572 // attribute. 2573 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2574 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2575 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2576 Diag(Old->getFirstDecl()->getLocation(), 2577 diag::note_noreturn_missing_first_decl); 2578 } 2579 2580 // C++11 [dcl.attr.depend]p2: 2581 // The first declaration of a function shall specify the 2582 // carries_dependency attribute for its declarator-id if any declaration 2583 // of the function specifies the carries_dependency attribute. 2584 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2585 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2586 Diag(CDA->getLocation(), 2587 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2588 Diag(Old->getFirstDecl()->getLocation(), 2589 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2590 } 2591 2592 // (C++98 8.3.5p3): 2593 // All declarations for a function shall agree exactly in both the 2594 // return type and the parameter-type-list. 2595 // We also want to respect all the extended bits except noreturn. 2596 2597 // noreturn should now match unless the old type info didn't have it. 2598 QualType OldQTypeForComparison = OldQType; 2599 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2600 assert(OldQType == QualType(OldType, 0)); 2601 const FunctionType *OldTypeForComparison 2602 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2603 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2604 assert(OldQTypeForComparison.isCanonical()); 2605 } 2606 2607 if (haveIncompatibleLanguageLinkages(Old, New)) { 2608 // As a special case, retain the language linkage from previous 2609 // declarations of a friend function as an extension. 2610 // 2611 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2612 // and is useful because there's otherwise no way to specify language 2613 // linkage within class scope. 2614 // 2615 // Check cautiously as the friend object kind isn't yet complete. 2616 if (New->getFriendObjectKind() != Decl::FOK_None) { 2617 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2618 Diag(OldLocation, PrevDiag); 2619 } else { 2620 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2621 Diag(OldLocation, PrevDiag); 2622 return true; 2623 } 2624 } 2625 2626 if (OldQTypeForComparison == NewQType) 2627 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2628 2629 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2630 New->isLocalExternDecl()) { 2631 // It's OK if we couldn't merge types for a local function declaraton 2632 // if either the old or new type is dependent. We'll merge the types 2633 // when we instantiate the function. 2634 return false; 2635 } 2636 2637 // Fall through for conflicting redeclarations and redefinitions. 2638 } 2639 2640 // C: Function types need to be compatible, not identical. This handles 2641 // duplicate function decls like "void f(int); void f(enum X);" properly. 2642 if (!getLangOpts().CPlusPlus && 2643 Context.typesAreCompatible(OldQType, NewQType)) { 2644 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2645 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2646 const FunctionProtoType *OldProto = 0; 2647 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2648 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2649 // The old declaration provided a function prototype, but the 2650 // new declaration does not. Merge in the prototype. 2651 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2652 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2653 NewQType = 2654 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2655 OldProto->getExtProtoInfo()); 2656 New->setType(NewQType); 2657 New->setHasInheritedPrototype(); 2658 2659 // Synthesize a parameter for each argument type. 2660 SmallVector<ParmVarDecl*, 16> Params; 2661 for (const auto &ParamType : OldProto->param_types()) { 2662 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2663 SourceLocation(), 0, ParamType, 2664 /*TInfo=*/0, SC_None, 0); 2665 Param->setScopeInfo(0, Params.size()); 2666 Param->setImplicit(); 2667 Params.push_back(Param); 2668 } 2669 2670 New->setParams(Params); 2671 } 2672 2673 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2674 } 2675 2676 // GNU C permits a K&R definition to follow a prototype declaration 2677 // if the declared types of the parameters in the K&R definition 2678 // match the types in the prototype declaration, even when the 2679 // promoted types of the parameters from the K&R definition differ 2680 // from the types in the prototype. GCC then keeps the types from 2681 // the prototype. 2682 // 2683 // If a variadic prototype is followed by a non-variadic K&R definition, 2684 // the K&R definition becomes variadic. This is sort of an edge case, but 2685 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2686 // C99 6.9.1p8. 2687 if (!getLangOpts().CPlusPlus && 2688 Old->hasPrototype() && !New->hasPrototype() && 2689 New->getType()->getAs<FunctionProtoType>() && 2690 Old->getNumParams() == New->getNumParams()) { 2691 SmallVector<QualType, 16> ArgTypes; 2692 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2693 const FunctionProtoType *OldProto 2694 = Old->getType()->getAs<FunctionProtoType>(); 2695 const FunctionProtoType *NewProto 2696 = New->getType()->getAs<FunctionProtoType>(); 2697 2698 // Determine whether this is the GNU C extension. 2699 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2700 NewProto->getReturnType()); 2701 bool LooseCompatible = !MergedReturn.isNull(); 2702 for (unsigned Idx = 0, End = Old->getNumParams(); 2703 LooseCompatible && Idx != End; ++Idx) { 2704 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2705 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2706 if (Context.typesAreCompatible(OldParm->getType(), 2707 NewProto->getParamType(Idx))) { 2708 ArgTypes.push_back(NewParm->getType()); 2709 } else if (Context.typesAreCompatible(OldParm->getType(), 2710 NewParm->getType(), 2711 /*CompareUnqualified=*/true)) { 2712 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2713 NewProto->getParamType(Idx) }; 2714 Warnings.push_back(Warn); 2715 ArgTypes.push_back(NewParm->getType()); 2716 } else 2717 LooseCompatible = false; 2718 } 2719 2720 if (LooseCompatible) { 2721 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2722 Diag(Warnings[Warn].NewParm->getLocation(), 2723 diag::ext_param_promoted_not_compatible_with_prototype) 2724 << Warnings[Warn].PromotedType 2725 << Warnings[Warn].OldParm->getType(); 2726 if (Warnings[Warn].OldParm->getLocation().isValid()) 2727 Diag(Warnings[Warn].OldParm->getLocation(), 2728 diag::note_previous_declaration); 2729 } 2730 2731 if (MergeTypeWithOld) 2732 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2733 OldProto->getExtProtoInfo())); 2734 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2735 } 2736 2737 // Fall through to diagnose conflicting types. 2738 } 2739 2740 // A function that has already been declared has been redeclared or 2741 // defined with a different type; show an appropriate diagnostic. 2742 2743 // If the previous declaration was an implicitly-generated builtin 2744 // declaration, then at the very least we should use a specialized note. 2745 unsigned BuiltinID; 2746 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2747 // If it's actually a library-defined builtin function like 'malloc' 2748 // or 'printf', just warn about the incompatible redeclaration. 2749 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2750 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2751 Diag(OldLocation, diag::note_previous_builtin_declaration) 2752 << Old << Old->getType(); 2753 2754 // If this is a global redeclaration, just forget hereafter 2755 // about the "builtin-ness" of the function. 2756 // 2757 // Doing this for local extern declarations is problematic. If 2758 // the builtin declaration remains visible, a second invalid 2759 // local declaration will produce a hard error; if it doesn't 2760 // remain visible, a single bogus local redeclaration (which is 2761 // actually only a warning) could break all the downstream code. 2762 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2763 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2764 2765 return false; 2766 } 2767 2768 PrevDiag = diag::note_previous_builtin_declaration; 2769 } 2770 2771 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2772 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2773 return true; 2774 } 2775 2776 /// \brief Completes the merge of two function declarations that are 2777 /// known to be compatible. 2778 /// 2779 /// This routine handles the merging of attributes and other 2780 /// properties of function declarations from the old declaration to 2781 /// the new declaration, once we know that New is in fact a 2782 /// redeclaration of Old. 2783 /// 2784 /// \returns false 2785 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2786 Scope *S, bool MergeTypeWithOld) { 2787 // Merge the attributes 2788 mergeDeclAttributes(New, Old); 2789 2790 // Merge "pure" flag. 2791 if (Old->isPure()) 2792 New->setPure(); 2793 2794 // Merge "used" flag. 2795 if (Old->getMostRecentDecl()->isUsed(false)) 2796 New->setIsUsed(); 2797 2798 // Merge attributes from the parameters. These can mismatch with K&R 2799 // declarations. 2800 if (New->getNumParams() == Old->getNumParams()) 2801 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2802 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2803 *this); 2804 2805 if (getLangOpts().CPlusPlus) 2806 return MergeCXXFunctionDecl(New, Old, S); 2807 2808 // Merge the function types so the we get the composite types for the return 2809 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2810 // was visible. 2811 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2812 if (!Merged.isNull() && MergeTypeWithOld) 2813 New->setType(Merged); 2814 2815 return false; 2816 } 2817 2818 2819 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2820 ObjCMethodDecl *oldMethod) { 2821 2822 // Merge the attributes, including deprecated/unavailable 2823 AvailabilityMergeKind MergeKind = 2824 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2825 : AMK_Override; 2826 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2827 2828 // Merge attributes from the parameters. 2829 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2830 oe = oldMethod->param_end(); 2831 for (ObjCMethodDecl::param_iterator 2832 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2833 ni != ne && oi != oe; ++ni, ++oi) 2834 mergeParamDeclAttributes(*ni, *oi, *this); 2835 2836 CheckObjCMethodOverride(newMethod, oldMethod); 2837 } 2838 2839 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2840 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2841 /// emitting diagnostics as appropriate. 2842 /// 2843 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2844 /// to here in AddInitializerToDecl. We can't check them before the initializer 2845 /// is attached. 2846 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2847 bool MergeTypeWithOld) { 2848 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2849 return; 2850 2851 QualType MergedT; 2852 if (getLangOpts().CPlusPlus) { 2853 if (New->getType()->isUndeducedType()) { 2854 // We don't know what the new type is until the initializer is attached. 2855 return; 2856 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2857 // These could still be something that needs exception specs checked. 2858 return MergeVarDeclExceptionSpecs(New, Old); 2859 } 2860 // C++ [basic.link]p10: 2861 // [...] the types specified by all declarations referring to a given 2862 // object or function shall be identical, except that declarations for an 2863 // array object can specify array types that differ by the presence or 2864 // absence of a major array bound (8.3.4). 2865 else if (Old->getType()->isIncompleteArrayType() && 2866 New->getType()->isArrayType()) { 2867 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2868 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2869 if (Context.hasSameType(OldArray->getElementType(), 2870 NewArray->getElementType())) 2871 MergedT = New->getType(); 2872 } else if (Old->getType()->isArrayType() && 2873 New->getType()->isIncompleteArrayType()) { 2874 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2875 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2876 if (Context.hasSameType(OldArray->getElementType(), 2877 NewArray->getElementType())) 2878 MergedT = Old->getType(); 2879 } else if (New->getType()->isObjCObjectPointerType() && 2880 Old->getType()->isObjCObjectPointerType()) { 2881 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2882 Old->getType()); 2883 } 2884 } else { 2885 // C 6.2.7p2: 2886 // All declarations that refer to the same object or function shall have 2887 // compatible type. 2888 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2889 } 2890 if (MergedT.isNull()) { 2891 // It's OK if we couldn't merge types if either type is dependent, for a 2892 // block-scope variable. In other cases (static data members of class 2893 // templates, variable templates, ...), we require the types to be 2894 // equivalent. 2895 // FIXME: The C++ standard doesn't say anything about this. 2896 if ((New->getType()->isDependentType() || 2897 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2898 // If the old type was dependent, we can't merge with it, so the new type 2899 // becomes dependent for now. We'll reproduce the original type when we 2900 // instantiate the TypeSourceInfo for the variable. 2901 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2902 New->setType(Context.DependentTy); 2903 return; 2904 } 2905 2906 // FIXME: Even if this merging succeeds, some other non-visible declaration 2907 // of this variable might have an incompatible type. For instance: 2908 // 2909 // extern int arr[]; 2910 // void f() { extern int arr[2]; } 2911 // void g() { extern int arr[3]; } 2912 // 2913 // Neither C nor C++ requires a diagnostic for this, but we should still try 2914 // to diagnose it. 2915 Diag(New->getLocation(), diag::err_redefinition_different_type) 2916 << New->getDeclName() << New->getType() << Old->getType(); 2917 Diag(Old->getLocation(), diag::note_previous_definition); 2918 return New->setInvalidDecl(); 2919 } 2920 2921 // Don't actually update the type on the new declaration if the old 2922 // declaration was an extern declaration in a different scope. 2923 if (MergeTypeWithOld) 2924 New->setType(MergedT); 2925 } 2926 2927 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2928 LookupResult &Previous) { 2929 // C11 6.2.7p4: 2930 // For an identifier with internal or external linkage declared 2931 // in a scope in which a prior declaration of that identifier is 2932 // visible, if the prior declaration specifies internal or 2933 // external linkage, the type of the identifier at the later 2934 // declaration becomes the composite type. 2935 // 2936 // If the variable isn't visible, we do not merge with its type. 2937 if (Previous.isShadowed()) 2938 return false; 2939 2940 if (S.getLangOpts().CPlusPlus) { 2941 // C++11 [dcl.array]p3: 2942 // If there is a preceding declaration of the entity in the same 2943 // scope in which the bound was specified, an omitted array bound 2944 // is taken to be the same as in that earlier declaration. 2945 return NewVD->isPreviousDeclInSameBlockScope() || 2946 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2947 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2948 } else { 2949 // If the old declaration was function-local, don't merge with its 2950 // type unless we're in the same function. 2951 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2952 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2953 } 2954 } 2955 2956 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2957 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2958 /// situation, merging decls or emitting diagnostics as appropriate. 2959 /// 2960 /// Tentative definition rules (C99 6.9.2p2) are checked by 2961 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2962 /// definitions here, since the initializer hasn't been attached. 2963 /// 2964 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2965 // If the new decl is already invalid, don't do any other checking. 2966 if (New->isInvalidDecl()) 2967 return; 2968 2969 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 2970 2971 // Verify the old decl was also a variable or variable template. 2972 VarDecl *Old = 0; 2973 VarTemplateDecl *OldTemplate = 0; 2974 if (Previous.isSingleResult()) { 2975 if (NewTemplate) { 2976 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 2977 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0; 2978 } else 2979 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2980 } 2981 if (!Old) { 2982 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2983 << New->getDeclName(); 2984 Diag(Previous.getRepresentativeDecl()->getLocation(), 2985 diag::note_previous_definition); 2986 return New->setInvalidDecl(); 2987 } 2988 2989 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 2990 return; 2991 2992 // Ensure the template parameters are compatible. 2993 if (NewTemplate && 2994 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 2995 OldTemplate->getTemplateParameters(), 2996 /*Complain=*/true, TPL_TemplateMatch)) 2997 return; 2998 2999 // C++ [class.mem]p1: 3000 // A member shall not be declared twice in the member-specification [...] 3001 // 3002 // Here, we need only consider static data members. 3003 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3004 Diag(New->getLocation(), diag::err_duplicate_member) 3005 << New->getIdentifier(); 3006 Diag(Old->getLocation(), diag::note_previous_declaration); 3007 New->setInvalidDecl(); 3008 } 3009 3010 mergeDeclAttributes(New, Old); 3011 // Warn if an already-declared variable is made a weak_import in a subsequent 3012 // declaration 3013 if (New->hasAttr<WeakImportAttr>() && 3014 Old->getStorageClass() == SC_None && 3015 !Old->hasAttr<WeakImportAttr>()) { 3016 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3017 Diag(Old->getLocation(), diag::note_previous_definition); 3018 // Remove weak_import attribute on new declaration. 3019 New->dropAttr<WeakImportAttr>(); 3020 } 3021 3022 // Merge the types. 3023 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3024 3025 if (New->isInvalidDecl()) 3026 return; 3027 3028 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3029 if (New->getStorageClass() == SC_Static && 3030 !New->isStaticDataMember() && 3031 Old->hasExternalFormalLinkage()) { 3032 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3033 Diag(Old->getLocation(), diag::note_previous_definition); 3034 return New->setInvalidDecl(); 3035 } 3036 // C99 6.2.2p4: 3037 // For an identifier declared with the storage-class specifier 3038 // extern in a scope in which a prior declaration of that 3039 // identifier is visible,23) if the prior declaration specifies 3040 // internal or external linkage, the linkage of the identifier at 3041 // the later declaration is the same as the linkage specified at 3042 // the prior declaration. If no prior declaration is visible, or 3043 // if the prior declaration specifies no linkage, then the 3044 // identifier has external linkage. 3045 if (New->hasExternalStorage() && Old->hasLinkage()) 3046 /* Okay */; 3047 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3048 !New->isStaticDataMember() && 3049 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3050 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3051 Diag(Old->getLocation(), diag::note_previous_definition); 3052 return New->setInvalidDecl(); 3053 } 3054 3055 // Check if extern is followed by non-extern and vice-versa. 3056 if (New->hasExternalStorage() && 3057 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3058 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3059 Diag(Old->getLocation(), diag::note_previous_definition); 3060 return New->setInvalidDecl(); 3061 } 3062 if (Old->hasLinkage() && New->isLocalVarDecl() && 3063 !New->hasExternalStorage()) { 3064 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3065 Diag(Old->getLocation(), diag::note_previous_definition); 3066 return New->setInvalidDecl(); 3067 } 3068 3069 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3070 3071 // FIXME: The test for external storage here seems wrong? We still 3072 // need to check for mismatches. 3073 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3074 // Don't complain about out-of-line definitions of static members. 3075 !(Old->getLexicalDeclContext()->isRecord() && 3076 !New->getLexicalDeclContext()->isRecord())) { 3077 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3078 Diag(Old->getLocation(), diag::note_previous_definition); 3079 return New->setInvalidDecl(); 3080 } 3081 3082 if (New->getTLSKind() != Old->getTLSKind()) { 3083 if (!Old->getTLSKind()) { 3084 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3085 Diag(Old->getLocation(), diag::note_previous_declaration); 3086 } else if (!New->getTLSKind()) { 3087 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3088 Diag(Old->getLocation(), diag::note_previous_declaration); 3089 } else { 3090 // Do not allow redeclaration to change the variable between requiring 3091 // static and dynamic initialization. 3092 // FIXME: GCC allows this, but uses the TLS keyword on the first 3093 // declaration to determine the kind. Do we need to be compatible here? 3094 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3095 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3096 Diag(Old->getLocation(), diag::note_previous_declaration); 3097 } 3098 } 3099 3100 // C++ doesn't have tentative definitions, so go right ahead and check here. 3101 const VarDecl *Def; 3102 if (getLangOpts().CPlusPlus && 3103 New->isThisDeclarationADefinition() == VarDecl::Definition && 3104 (Def = Old->getDefinition())) { 3105 Diag(New->getLocation(), diag::err_redefinition) << New; 3106 Diag(Def->getLocation(), diag::note_previous_definition); 3107 New->setInvalidDecl(); 3108 return; 3109 } 3110 3111 if (haveIncompatibleLanguageLinkages(Old, New)) { 3112 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3113 Diag(Old->getLocation(), diag::note_previous_definition); 3114 New->setInvalidDecl(); 3115 return; 3116 } 3117 3118 // Merge "used" flag. 3119 if (Old->getMostRecentDecl()->isUsed(false)) 3120 New->setIsUsed(); 3121 3122 // Keep a chain of previous declarations. 3123 New->setPreviousDecl(Old); 3124 if (NewTemplate) 3125 NewTemplate->setPreviousDecl(OldTemplate); 3126 3127 // Inherit access appropriately. 3128 New->setAccess(Old->getAccess()); 3129 if (NewTemplate) 3130 NewTemplate->setAccess(New->getAccess()); 3131 } 3132 3133 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3134 /// no declarator (e.g. "struct foo;") is parsed. 3135 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3136 DeclSpec &DS) { 3137 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3138 } 3139 3140 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3141 if (!S.Context.getLangOpts().CPlusPlus) 3142 return; 3143 3144 if (isa<CXXRecordDecl>(Tag->getParent())) { 3145 // If this tag is the direct child of a class, number it if 3146 // it is anonymous. 3147 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3148 return; 3149 MangleNumberingContext &MCtx = 3150 S.Context.getManglingNumberContext(Tag->getParent()); 3151 S.Context.setManglingNumber( 3152 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3153 return; 3154 } 3155 3156 // If this tag isn't a direct child of a class, number it if it is local. 3157 Decl *ManglingContextDecl; 3158 if (MangleNumberingContext *MCtx = 3159 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3160 ManglingContextDecl)) { 3161 S.Context.setManglingNumber( 3162 Tag, 3163 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3164 } 3165 } 3166 3167 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3168 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3169 /// parameters to cope with template friend declarations. 3170 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3171 DeclSpec &DS, 3172 MultiTemplateParamsArg TemplateParams, 3173 bool IsExplicitInstantiation) { 3174 Decl *TagD = 0; 3175 TagDecl *Tag = 0; 3176 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3177 DS.getTypeSpecType() == DeclSpec::TST_struct || 3178 DS.getTypeSpecType() == DeclSpec::TST_interface || 3179 DS.getTypeSpecType() == DeclSpec::TST_union || 3180 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3181 TagD = DS.getRepAsDecl(); 3182 3183 if (!TagD) // We probably had an error 3184 return 0; 3185 3186 // Note that the above type specs guarantee that the 3187 // type rep is a Decl, whereas in many of the others 3188 // it's a Type. 3189 if (isa<TagDecl>(TagD)) 3190 Tag = cast<TagDecl>(TagD); 3191 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3192 Tag = CTD->getTemplatedDecl(); 3193 } 3194 3195 if (Tag) { 3196 HandleTagNumbering(*this, Tag, S); 3197 Tag->setFreeStanding(); 3198 if (Tag->isInvalidDecl()) 3199 return Tag; 3200 } 3201 3202 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3203 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3204 // or incomplete types shall not be restrict-qualified." 3205 if (TypeQuals & DeclSpec::TQ_restrict) 3206 Diag(DS.getRestrictSpecLoc(), 3207 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3208 << DS.getSourceRange(); 3209 } 3210 3211 if (DS.isConstexprSpecified()) { 3212 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3213 // and definitions of functions and variables. 3214 if (Tag) 3215 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3216 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3217 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3218 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3219 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3220 else 3221 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3222 // Don't emit warnings after this error. 3223 return TagD; 3224 } 3225 3226 DiagnoseFunctionSpecifiers(DS); 3227 3228 if (DS.isFriendSpecified()) { 3229 // If we're dealing with a decl but not a TagDecl, assume that 3230 // whatever routines created it handled the friendship aspect. 3231 if (TagD && !Tag) 3232 return 0; 3233 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3234 } 3235 3236 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3237 bool IsExplicitSpecialization = 3238 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3239 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3240 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3241 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3242 // nested-name-specifier unless it is an explicit instantiation 3243 // or an explicit specialization. 3244 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3245 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3246 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3247 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3248 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3249 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3250 << SS.getRange(); 3251 return 0; 3252 } 3253 3254 // Track whether this decl-specifier declares anything. 3255 bool DeclaresAnything = true; 3256 3257 // Handle anonymous struct definitions. 3258 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3259 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3260 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3261 if (getLangOpts().CPlusPlus || 3262 Record->getDeclContext()->isRecord()) 3263 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3264 3265 DeclaresAnything = false; 3266 } 3267 } 3268 3269 // Check for Microsoft C extension: anonymous struct member. 3270 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3271 CurContext->isRecord() && 3272 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3273 // Handle 2 kinds of anonymous struct: 3274 // struct STRUCT; 3275 // and 3276 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3277 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3278 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3279 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3280 DS.getRepAsType().get()->isStructureType())) { 3281 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3282 << DS.getSourceRange(); 3283 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3284 } 3285 } 3286 3287 // Skip all the checks below if we have a type error. 3288 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3289 (TagD && TagD->isInvalidDecl())) 3290 return TagD; 3291 3292 if (getLangOpts().CPlusPlus && 3293 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3294 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3295 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3296 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3297 DeclaresAnything = false; 3298 3299 if (!DS.isMissingDeclaratorOk()) { 3300 // Customize diagnostic for a typedef missing a name. 3301 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3302 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3303 << DS.getSourceRange(); 3304 else 3305 DeclaresAnything = false; 3306 } 3307 3308 if (DS.isModulePrivateSpecified() && 3309 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3310 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3311 << Tag->getTagKind() 3312 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3313 3314 ActOnDocumentableDecl(TagD); 3315 3316 // C 6.7/2: 3317 // A declaration [...] shall declare at least a declarator [...], a tag, 3318 // or the members of an enumeration. 3319 // C++ [dcl.dcl]p3: 3320 // [If there are no declarators], and except for the declaration of an 3321 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3322 // names into the program, or shall redeclare a name introduced by a 3323 // previous declaration. 3324 if (!DeclaresAnything) { 3325 // In C, we allow this as a (popular) extension / bug. Don't bother 3326 // producing further diagnostics for redundant qualifiers after this. 3327 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3328 return TagD; 3329 } 3330 3331 // C++ [dcl.stc]p1: 3332 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3333 // init-declarator-list of the declaration shall not be empty. 3334 // C++ [dcl.fct.spec]p1: 3335 // If a cv-qualifier appears in a decl-specifier-seq, the 3336 // init-declarator-list of the declaration shall not be empty. 3337 // 3338 // Spurious qualifiers here appear to be valid in C. 3339 unsigned DiagID = diag::warn_standalone_specifier; 3340 if (getLangOpts().CPlusPlus) 3341 DiagID = diag::ext_standalone_specifier; 3342 3343 // Note that a linkage-specification sets a storage class, but 3344 // 'extern "C" struct foo;' is actually valid and not theoretically 3345 // useless. 3346 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3347 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3348 Diag(DS.getStorageClassSpecLoc(), DiagID) 3349 << DeclSpec::getSpecifierName(SCS); 3350 3351 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3352 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3353 << DeclSpec::getSpecifierName(TSCS); 3354 if (DS.getTypeQualifiers()) { 3355 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3356 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3357 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3358 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3359 // Restrict is covered above. 3360 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3361 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3362 } 3363 3364 // Warn about ignored type attributes, for example: 3365 // __attribute__((aligned)) struct A; 3366 // Attributes should be placed after tag to apply to type declaration. 3367 if (!DS.getAttributes().empty()) { 3368 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3369 if (TypeSpecType == DeclSpec::TST_class || 3370 TypeSpecType == DeclSpec::TST_struct || 3371 TypeSpecType == DeclSpec::TST_interface || 3372 TypeSpecType == DeclSpec::TST_union || 3373 TypeSpecType == DeclSpec::TST_enum) { 3374 AttributeList* attrs = DS.getAttributes().getList(); 3375 while (attrs) { 3376 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3377 << attrs->getName() 3378 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3379 TypeSpecType == DeclSpec::TST_struct ? 1 : 3380 TypeSpecType == DeclSpec::TST_union ? 2 : 3381 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3382 attrs = attrs->getNext(); 3383 } 3384 } 3385 } 3386 3387 return TagD; 3388 } 3389 3390 /// We are trying to inject an anonymous member into the given scope; 3391 /// check if there's an existing declaration that can't be overloaded. 3392 /// 3393 /// \return true if this is a forbidden redeclaration 3394 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3395 Scope *S, 3396 DeclContext *Owner, 3397 DeclarationName Name, 3398 SourceLocation NameLoc, 3399 unsigned diagnostic) { 3400 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3401 Sema::ForRedeclaration); 3402 if (!SemaRef.LookupName(R, S)) return false; 3403 3404 if (R.getAsSingle<TagDecl>()) 3405 return false; 3406 3407 // Pick a representative declaration. 3408 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3409 assert(PrevDecl && "Expected a non-null Decl"); 3410 3411 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3412 return false; 3413 3414 SemaRef.Diag(NameLoc, diagnostic) << Name; 3415 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3416 3417 return true; 3418 } 3419 3420 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3421 /// anonymous struct or union AnonRecord into the owning context Owner 3422 /// and scope S. This routine will be invoked just after we realize 3423 /// that an unnamed union or struct is actually an anonymous union or 3424 /// struct, e.g., 3425 /// 3426 /// @code 3427 /// union { 3428 /// int i; 3429 /// float f; 3430 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3431 /// // f into the surrounding scope.x 3432 /// @endcode 3433 /// 3434 /// This routine is recursive, injecting the names of nested anonymous 3435 /// structs/unions into the owning context and scope as well. 3436 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3437 DeclContext *Owner, 3438 RecordDecl *AnonRecord, 3439 AccessSpecifier AS, 3440 SmallVectorImpl<NamedDecl *> &Chaining, 3441 bool MSAnonStruct) { 3442 unsigned diagKind 3443 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3444 : diag::err_anonymous_struct_member_redecl; 3445 3446 bool Invalid = false; 3447 3448 // Look every FieldDecl and IndirectFieldDecl with a name. 3449 for (auto *D : AnonRecord->decls()) { 3450 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3451 cast<NamedDecl>(D)->getDeclName()) { 3452 ValueDecl *VD = cast<ValueDecl>(D); 3453 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3454 VD->getLocation(), diagKind)) { 3455 // C++ [class.union]p2: 3456 // The names of the members of an anonymous union shall be 3457 // distinct from the names of any other entity in the 3458 // scope in which the anonymous union is declared. 3459 Invalid = true; 3460 } else { 3461 // C++ [class.union]p2: 3462 // For the purpose of name lookup, after the anonymous union 3463 // definition, the members of the anonymous union are 3464 // considered to have been defined in the scope in which the 3465 // anonymous union is declared. 3466 unsigned OldChainingSize = Chaining.size(); 3467 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3468 for (auto *PI : IF->chain()) 3469 Chaining.push_back(PI); 3470 else 3471 Chaining.push_back(VD); 3472 3473 assert(Chaining.size() >= 2); 3474 NamedDecl **NamedChain = 3475 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3476 for (unsigned i = 0; i < Chaining.size(); i++) 3477 NamedChain[i] = Chaining[i]; 3478 3479 IndirectFieldDecl* IndirectField = 3480 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3481 VD->getIdentifier(), VD->getType(), 3482 NamedChain, Chaining.size()); 3483 3484 IndirectField->setAccess(AS); 3485 IndirectField->setImplicit(); 3486 SemaRef.PushOnScopeChains(IndirectField, S); 3487 3488 // That includes picking up the appropriate access specifier. 3489 if (AS != AS_none) IndirectField->setAccess(AS); 3490 3491 Chaining.resize(OldChainingSize); 3492 } 3493 } 3494 } 3495 3496 return Invalid; 3497 } 3498 3499 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3500 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3501 /// illegal input values are mapped to SC_None. 3502 static StorageClass 3503 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3504 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3505 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3506 "Parser allowed 'typedef' as storage class VarDecl."); 3507 switch (StorageClassSpec) { 3508 case DeclSpec::SCS_unspecified: return SC_None; 3509 case DeclSpec::SCS_extern: 3510 if (DS.isExternInLinkageSpec()) 3511 return SC_None; 3512 return SC_Extern; 3513 case DeclSpec::SCS_static: return SC_Static; 3514 case DeclSpec::SCS_auto: return SC_Auto; 3515 case DeclSpec::SCS_register: return SC_Register; 3516 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3517 // Illegal SCSs map to None: error reporting is up to the caller. 3518 case DeclSpec::SCS_mutable: // Fall through. 3519 case DeclSpec::SCS_typedef: return SC_None; 3520 } 3521 llvm_unreachable("unknown storage class specifier"); 3522 } 3523 3524 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3525 assert(Record->hasInClassInitializer()); 3526 3527 for (const auto *I : Record->decls()) { 3528 const auto *FD = dyn_cast<FieldDecl>(I); 3529 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3530 FD = IFD->getAnonField(); 3531 if (FD && FD->hasInClassInitializer()) 3532 return FD->getLocation(); 3533 } 3534 3535 llvm_unreachable("couldn't find in-class initializer"); 3536 } 3537 3538 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3539 SourceLocation DefaultInitLoc) { 3540 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3541 return; 3542 3543 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3544 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3545 } 3546 3547 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3548 CXXRecordDecl *AnonUnion) { 3549 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3550 return; 3551 3552 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3553 } 3554 3555 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3556 /// anonymous structure or union. Anonymous unions are a C++ feature 3557 /// (C++ [class.union]) and a C11 feature; anonymous structures 3558 /// are a C11 feature and GNU C++ extension. 3559 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3560 AccessSpecifier AS, 3561 RecordDecl *Record, 3562 const PrintingPolicy &Policy) { 3563 DeclContext *Owner = Record->getDeclContext(); 3564 3565 // Diagnose whether this anonymous struct/union is an extension. 3566 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3567 Diag(Record->getLocation(), diag::ext_anonymous_union); 3568 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3569 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3570 else if (!Record->isUnion() && !getLangOpts().C11) 3571 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3572 3573 // C and C++ require different kinds of checks for anonymous 3574 // structs/unions. 3575 bool Invalid = false; 3576 if (getLangOpts().CPlusPlus) { 3577 const char* PrevSpec = 0; 3578 unsigned DiagID; 3579 if (Record->isUnion()) { 3580 // C++ [class.union]p6: 3581 // Anonymous unions declared in a named namespace or in the 3582 // global namespace shall be declared static. 3583 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3584 (isa<TranslationUnitDecl>(Owner) || 3585 (isa<NamespaceDecl>(Owner) && 3586 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3587 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3588 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3589 3590 // Recover by adding 'static'. 3591 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3592 PrevSpec, DiagID, Policy); 3593 } 3594 // C++ [class.union]p6: 3595 // A storage class is not allowed in a declaration of an 3596 // anonymous union in a class scope. 3597 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3598 isa<RecordDecl>(Owner)) { 3599 Diag(DS.getStorageClassSpecLoc(), 3600 diag::err_anonymous_union_with_storage_spec) 3601 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3602 3603 // Recover by removing the storage specifier. 3604 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3605 SourceLocation(), 3606 PrevSpec, DiagID, Context.getPrintingPolicy()); 3607 } 3608 } 3609 3610 // Ignore const/volatile/restrict qualifiers. 3611 if (DS.getTypeQualifiers()) { 3612 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3613 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3614 << Record->isUnion() << "const" 3615 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3616 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3617 Diag(DS.getVolatileSpecLoc(), 3618 diag::ext_anonymous_struct_union_qualified) 3619 << Record->isUnion() << "volatile" 3620 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3621 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3622 Diag(DS.getRestrictSpecLoc(), 3623 diag::ext_anonymous_struct_union_qualified) 3624 << Record->isUnion() << "restrict" 3625 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3626 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3627 Diag(DS.getAtomicSpecLoc(), 3628 diag::ext_anonymous_struct_union_qualified) 3629 << Record->isUnion() << "_Atomic" 3630 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3631 3632 DS.ClearTypeQualifiers(); 3633 } 3634 3635 // C++ [class.union]p2: 3636 // The member-specification of an anonymous union shall only 3637 // define non-static data members. [Note: nested types and 3638 // functions cannot be declared within an anonymous union. ] 3639 for (auto *Mem : Record->decls()) { 3640 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3641 // C++ [class.union]p3: 3642 // An anonymous union shall not have private or protected 3643 // members (clause 11). 3644 assert(FD->getAccess() != AS_none); 3645 if (FD->getAccess() != AS_public) { 3646 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3647 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3648 Invalid = true; 3649 } 3650 3651 // C++ [class.union]p1 3652 // An object of a class with a non-trivial constructor, a non-trivial 3653 // copy constructor, a non-trivial destructor, or a non-trivial copy 3654 // assignment operator cannot be a member of a union, nor can an 3655 // array of such objects. 3656 if (CheckNontrivialField(FD)) 3657 Invalid = true; 3658 } else if (Mem->isImplicit()) { 3659 // Any implicit members are fine. 3660 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3661 // This is a type that showed up in an 3662 // elaborated-type-specifier inside the anonymous struct or 3663 // union, but which actually declares a type outside of the 3664 // anonymous struct or union. It's okay. 3665 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3666 if (!MemRecord->isAnonymousStructOrUnion() && 3667 MemRecord->getDeclName()) { 3668 // Visual C++ allows type definition in anonymous struct or union. 3669 if (getLangOpts().MicrosoftExt) 3670 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3671 << (int)Record->isUnion(); 3672 else { 3673 // This is a nested type declaration. 3674 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3675 << (int)Record->isUnion(); 3676 Invalid = true; 3677 } 3678 } else { 3679 // This is an anonymous type definition within another anonymous type. 3680 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3681 // not part of standard C++. 3682 Diag(MemRecord->getLocation(), 3683 diag::ext_anonymous_record_with_anonymous_type) 3684 << (int)Record->isUnion(); 3685 } 3686 } else if (isa<AccessSpecDecl>(Mem)) { 3687 // Any access specifier is fine. 3688 } else { 3689 // We have something that isn't a non-static data 3690 // member. Complain about it. 3691 unsigned DK = diag::err_anonymous_record_bad_member; 3692 if (isa<TypeDecl>(Mem)) 3693 DK = diag::err_anonymous_record_with_type; 3694 else if (isa<FunctionDecl>(Mem)) 3695 DK = diag::err_anonymous_record_with_function; 3696 else if (isa<VarDecl>(Mem)) 3697 DK = diag::err_anonymous_record_with_static; 3698 3699 // Visual C++ allows type definition in anonymous struct or union. 3700 if (getLangOpts().MicrosoftExt && 3701 DK == diag::err_anonymous_record_with_type) 3702 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3703 << (int)Record->isUnion(); 3704 else { 3705 Diag(Mem->getLocation(), DK) 3706 << (int)Record->isUnion(); 3707 Invalid = true; 3708 } 3709 } 3710 } 3711 3712 // C++11 [class.union]p8 (DR1460): 3713 // At most one variant member of a union may have a 3714 // brace-or-equal-initializer. 3715 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3716 Owner->isRecord()) 3717 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3718 cast<CXXRecordDecl>(Record)); 3719 } 3720 3721 if (!Record->isUnion() && !Owner->isRecord()) { 3722 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3723 << (int)getLangOpts().CPlusPlus; 3724 Invalid = true; 3725 } 3726 3727 // Mock up a declarator. 3728 Declarator Dc(DS, Declarator::MemberContext); 3729 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3730 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3731 3732 // Create a declaration for this anonymous struct/union. 3733 NamedDecl *Anon = 0; 3734 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3735 Anon = FieldDecl::Create(Context, OwningClass, 3736 DS.getLocStart(), 3737 Record->getLocation(), 3738 /*IdentifierInfo=*/0, 3739 Context.getTypeDeclType(Record), 3740 TInfo, 3741 /*BitWidth=*/0, /*Mutable=*/false, 3742 /*InitStyle=*/ICIS_NoInit); 3743 Anon->setAccess(AS); 3744 if (getLangOpts().CPlusPlus) 3745 FieldCollector->Add(cast<FieldDecl>(Anon)); 3746 } else { 3747 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3748 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3749 if (SCSpec == DeclSpec::SCS_mutable) { 3750 // mutable can only appear on non-static class members, so it's always 3751 // an error here 3752 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3753 Invalid = true; 3754 SC = SC_None; 3755 } 3756 3757 Anon = VarDecl::Create(Context, Owner, 3758 DS.getLocStart(), 3759 Record->getLocation(), /*IdentifierInfo=*/0, 3760 Context.getTypeDeclType(Record), 3761 TInfo, SC); 3762 3763 // Default-initialize the implicit variable. This initialization will be 3764 // trivial in almost all cases, except if a union member has an in-class 3765 // initializer: 3766 // union { int n = 0; }; 3767 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3768 } 3769 Anon->setImplicit(); 3770 3771 // Mark this as an anonymous struct/union type. 3772 Record->setAnonymousStructOrUnion(true); 3773 3774 // Add the anonymous struct/union object to the current 3775 // context. We'll be referencing this object when we refer to one of 3776 // its members. 3777 Owner->addDecl(Anon); 3778 3779 // Inject the members of the anonymous struct/union into the owning 3780 // context and into the identifier resolver chain for name lookup 3781 // purposes. 3782 SmallVector<NamedDecl*, 2> Chain; 3783 Chain.push_back(Anon); 3784 3785 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3786 Chain, false)) 3787 Invalid = true; 3788 3789 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 3790 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 3791 Decl *ManglingContextDecl; 3792 if (MangleNumberingContext *MCtx = 3793 getCurrentMangleNumberContext(NewVD->getDeclContext(), 3794 ManglingContextDecl)) { 3795 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 3796 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 3797 } 3798 } 3799 } 3800 3801 if (Invalid) 3802 Anon->setInvalidDecl(); 3803 3804 return Anon; 3805 } 3806 3807 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3808 /// Microsoft C anonymous structure. 3809 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3810 /// Example: 3811 /// 3812 /// struct A { int a; }; 3813 /// struct B { struct A; int b; }; 3814 /// 3815 /// void foo() { 3816 /// B var; 3817 /// var.a = 3; 3818 /// } 3819 /// 3820 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3821 RecordDecl *Record) { 3822 3823 // If there is no Record, get the record via the typedef. 3824 if (!Record) 3825 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3826 3827 // Mock up a declarator. 3828 Declarator Dc(DS, Declarator::TypeNameContext); 3829 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3830 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3831 3832 // Create a declaration for this anonymous struct. 3833 NamedDecl* Anon = FieldDecl::Create(Context, 3834 cast<RecordDecl>(CurContext), 3835 DS.getLocStart(), 3836 DS.getLocStart(), 3837 /*IdentifierInfo=*/0, 3838 Context.getTypeDeclType(Record), 3839 TInfo, 3840 /*BitWidth=*/0, /*Mutable=*/false, 3841 /*InitStyle=*/ICIS_NoInit); 3842 Anon->setImplicit(); 3843 3844 // Add the anonymous struct object to the current context. 3845 CurContext->addDecl(Anon); 3846 3847 // Inject the members of the anonymous struct into the current 3848 // context and into the identifier resolver chain for name lookup 3849 // purposes. 3850 SmallVector<NamedDecl*, 2> Chain; 3851 Chain.push_back(Anon); 3852 3853 RecordDecl *RecordDef = Record->getDefinition(); 3854 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3855 RecordDef, AS_none, 3856 Chain, true)) 3857 Anon->setInvalidDecl(); 3858 3859 return Anon; 3860 } 3861 3862 /// GetNameForDeclarator - Determine the full declaration name for the 3863 /// given Declarator. 3864 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3865 return GetNameFromUnqualifiedId(D.getName()); 3866 } 3867 3868 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3869 DeclarationNameInfo 3870 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3871 DeclarationNameInfo NameInfo; 3872 NameInfo.setLoc(Name.StartLocation); 3873 3874 switch (Name.getKind()) { 3875 3876 case UnqualifiedId::IK_ImplicitSelfParam: 3877 case UnqualifiedId::IK_Identifier: 3878 NameInfo.setName(Name.Identifier); 3879 NameInfo.setLoc(Name.StartLocation); 3880 return NameInfo; 3881 3882 case UnqualifiedId::IK_OperatorFunctionId: 3883 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3884 Name.OperatorFunctionId.Operator)); 3885 NameInfo.setLoc(Name.StartLocation); 3886 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3887 = Name.OperatorFunctionId.SymbolLocations[0]; 3888 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3889 = Name.EndLocation.getRawEncoding(); 3890 return NameInfo; 3891 3892 case UnqualifiedId::IK_LiteralOperatorId: 3893 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3894 Name.Identifier)); 3895 NameInfo.setLoc(Name.StartLocation); 3896 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3897 return NameInfo; 3898 3899 case UnqualifiedId::IK_ConversionFunctionId: { 3900 TypeSourceInfo *TInfo; 3901 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3902 if (Ty.isNull()) 3903 return DeclarationNameInfo(); 3904 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3905 Context.getCanonicalType(Ty))); 3906 NameInfo.setLoc(Name.StartLocation); 3907 NameInfo.setNamedTypeInfo(TInfo); 3908 return NameInfo; 3909 } 3910 3911 case UnqualifiedId::IK_ConstructorName: { 3912 TypeSourceInfo *TInfo; 3913 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3914 if (Ty.isNull()) 3915 return DeclarationNameInfo(); 3916 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3917 Context.getCanonicalType(Ty))); 3918 NameInfo.setLoc(Name.StartLocation); 3919 NameInfo.setNamedTypeInfo(TInfo); 3920 return NameInfo; 3921 } 3922 3923 case UnqualifiedId::IK_ConstructorTemplateId: { 3924 // In well-formed code, we can only have a constructor 3925 // template-id that refers to the current context, so go there 3926 // to find the actual type being constructed. 3927 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3928 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3929 return DeclarationNameInfo(); 3930 3931 // Determine the type of the class being constructed. 3932 QualType CurClassType = Context.getTypeDeclType(CurClass); 3933 3934 // FIXME: Check two things: that the template-id names the same type as 3935 // CurClassType, and that the template-id does not occur when the name 3936 // was qualified. 3937 3938 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3939 Context.getCanonicalType(CurClassType))); 3940 NameInfo.setLoc(Name.StartLocation); 3941 // FIXME: should we retrieve TypeSourceInfo? 3942 NameInfo.setNamedTypeInfo(0); 3943 return NameInfo; 3944 } 3945 3946 case UnqualifiedId::IK_DestructorName: { 3947 TypeSourceInfo *TInfo; 3948 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3949 if (Ty.isNull()) 3950 return DeclarationNameInfo(); 3951 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3952 Context.getCanonicalType(Ty))); 3953 NameInfo.setLoc(Name.StartLocation); 3954 NameInfo.setNamedTypeInfo(TInfo); 3955 return NameInfo; 3956 } 3957 3958 case UnqualifiedId::IK_TemplateId: { 3959 TemplateName TName = Name.TemplateId->Template.get(); 3960 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3961 return Context.getNameForTemplate(TName, TNameLoc); 3962 } 3963 3964 } // switch (Name.getKind()) 3965 3966 llvm_unreachable("Unknown name kind"); 3967 } 3968 3969 static QualType getCoreType(QualType Ty) { 3970 do { 3971 if (Ty->isPointerType() || Ty->isReferenceType()) 3972 Ty = Ty->getPointeeType(); 3973 else if (Ty->isArrayType()) 3974 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3975 else 3976 return Ty.withoutLocalFastQualifiers(); 3977 } while (true); 3978 } 3979 3980 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3981 /// and Definition have "nearly" matching parameters. This heuristic is 3982 /// used to improve diagnostics in the case where an out-of-line function 3983 /// definition doesn't match any declaration within the class or namespace. 3984 /// Also sets Params to the list of indices to the parameters that differ 3985 /// between the declaration and the definition. If hasSimilarParameters 3986 /// returns true and Params is empty, then all of the parameters match. 3987 static bool hasSimilarParameters(ASTContext &Context, 3988 FunctionDecl *Declaration, 3989 FunctionDecl *Definition, 3990 SmallVectorImpl<unsigned> &Params) { 3991 Params.clear(); 3992 if (Declaration->param_size() != Definition->param_size()) 3993 return false; 3994 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3995 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3996 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3997 3998 // The parameter types are identical 3999 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4000 continue; 4001 4002 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4003 QualType DefParamBaseTy = getCoreType(DefParamTy); 4004 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4005 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4006 4007 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4008 (DeclTyName && DeclTyName == DefTyName)) 4009 Params.push_back(Idx); 4010 else // The two parameters aren't even close 4011 return false; 4012 } 4013 4014 return true; 4015 } 4016 4017 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4018 /// declarator needs to be rebuilt in the current instantiation. 4019 /// Any bits of declarator which appear before the name are valid for 4020 /// consideration here. That's specifically the type in the decl spec 4021 /// and the base type in any member-pointer chunks. 4022 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4023 DeclarationName Name) { 4024 // The types we specifically need to rebuild are: 4025 // - typenames, typeofs, and decltypes 4026 // - types which will become injected class names 4027 // Of course, we also need to rebuild any type referencing such a 4028 // type. It's safest to just say "dependent", but we call out a 4029 // few cases here. 4030 4031 DeclSpec &DS = D.getMutableDeclSpec(); 4032 switch (DS.getTypeSpecType()) { 4033 case DeclSpec::TST_typename: 4034 case DeclSpec::TST_typeofType: 4035 case DeclSpec::TST_underlyingType: 4036 case DeclSpec::TST_atomic: { 4037 // Grab the type from the parser. 4038 TypeSourceInfo *TSI = 0; 4039 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4040 if (T.isNull() || !T->isDependentType()) break; 4041 4042 // Make sure there's a type source info. This isn't really much 4043 // of a waste; most dependent types should have type source info 4044 // attached already. 4045 if (!TSI) 4046 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4047 4048 // Rebuild the type in the current instantiation. 4049 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4050 if (!TSI) return true; 4051 4052 // Store the new type back in the decl spec. 4053 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4054 DS.UpdateTypeRep(LocType); 4055 break; 4056 } 4057 4058 case DeclSpec::TST_decltype: 4059 case DeclSpec::TST_typeofExpr: { 4060 Expr *E = DS.getRepAsExpr(); 4061 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4062 if (Result.isInvalid()) return true; 4063 DS.UpdateExprRep(Result.get()); 4064 break; 4065 } 4066 4067 default: 4068 // Nothing to do for these decl specs. 4069 break; 4070 } 4071 4072 // It doesn't matter what order we do this in. 4073 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4074 DeclaratorChunk &Chunk = D.getTypeObject(I); 4075 4076 // The only type information in the declarator which can come 4077 // before the declaration name is the base type of a member 4078 // pointer. 4079 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4080 continue; 4081 4082 // Rebuild the scope specifier in-place. 4083 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4084 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4085 return true; 4086 } 4087 4088 return false; 4089 } 4090 4091 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4092 D.setFunctionDefinitionKind(FDK_Declaration); 4093 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4094 4095 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4096 Dcl && Dcl->getDeclContext()->isFileContext()) 4097 Dcl->setTopLevelDeclInObjCContainer(); 4098 4099 return Dcl; 4100 } 4101 4102 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4103 /// If T is the name of a class, then each of the following shall have a 4104 /// name different from T: 4105 /// - every static data member of class T; 4106 /// - every member function of class T 4107 /// - every member of class T that is itself a type; 4108 /// \returns true if the declaration name violates these rules. 4109 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4110 DeclarationNameInfo NameInfo) { 4111 DeclarationName Name = NameInfo.getName(); 4112 4113 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4114 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4115 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4116 return true; 4117 } 4118 4119 return false; 4120 } 4121 4122 /// \brief Diagnose a declaration whose declarator-id has the given 4123 /// nested-name-specifier. 4124 /// 4125 /// \param SS The nested-name-specifier of the declarator-id. 4126 /// 4127 /// \param DC The declaration context to which the nested-name-specifier 4128 /// resolves. 4129 /// 4130 /// \param Name The name of the entity being declared. 4131 /// 4132 /// \param Loc The location of the name of the entity being declared. 4133 /// 4134 /// \returns true if we cannot safely recover from this error, false otherwise. 4135 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4136 DeclarationName Name, 4137 SourceLocation Loc) { 4138 DeclContext *Cur = CurContext; 4139 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4140 Cur = Cur->getParent(); 4141 4142 // If the user provided a superfluous scope specifier that refers back to the 4143 // class in which the entity is already declared, diagnose and ignore it. 4144 // 4145 // class X { 4146 // void X::f(); 4147 // }; 4148 // 4149 // Note, it was once ill-formed to give redundant qualification in all 4150 // contexts, but that rule was removed by DR482. 4151 if (Cur->Equals(DC)) { 4152 if (Cur->isRecord()) { 4153 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4154 : diag::err_member_extra_qualification) 4155 << Name << FixItHint::CreateRemoval(SS.getRange()); 4156 SS.clear(); 4157 } else { 4158 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4159 } 4160 return false; 4161 } 4162 4163 // Check whether the qualifying scope encloses the scope of the original 4164 // declaration. 4165 if (!Cur->Encloses(DC)) { 4166 if (Cur->isRecord()) 4167 Diag(Loc, diag::err_member_qualification) 4168 << Name << SS.getRange(); 4169 else if (isa<TranslationUnitDecl>(DC)) 4170 Diag(Loc, diag::err_invalid_declarator_global_scope) 4171 << Name << SS.getRange(); 4172 else if (isa<FunctionDecl>(Cur)) 4173 Diag(Loc, diag::err_invalid_declarator_in_function) 4174 << Name << SS.getRange(); 4175 else if (isa<BlockDecl>(Cur)) 4176 Diag(Loc, diag::err_invalid_declarator_in_block) 4177 << Name << SS.getRange(); 4178 else 4179 Diag(Loc, diag::err_invalid_declarator_scope) 4180 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4181 4182 return true; 4183 } 4184 4185 if (Cur->isRecord()) { 4186 // Cannot qualify members within a class. 4187 Diag(Loc, diag::err_member_qualification) 4188 << Name << SS.getRange(); 4189 SS.clear(); 4190 4191 // C++ constructors and destructors with incorrect scopes can break 4192 // our AST invariants by having the wrong underlying types. If 4193 // that's the case, then drop this declaration entirely. 4194 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4195 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4196 !Context.hasSameType(Name.getCXXNameType(), 4197 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4198 return true; 4199 4200 return false; 4201 } 4202 4203 // C++11 [dcl.meaning]p1: 4204 // [...] "The nested-name-specifier of the qualified declarator-id shall 4205 // not begin with a decltype-specifer" 4206 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4207 while (SpecLoc.getPrefix()) 4208 SpecLoc = SpecLoc.getPrefix(); 4209 if (dyn_cast_or_null<DecltypeType>( 4210 SpecLoc.getNestedNameSpecifier()->getAsType())) 4211 Diag(Loc, diag::err_decltype_in_declarator) 4212 << SpecLoc.getTypeLoc().getSourceRange(); 4213 4214 return false; 4215 } 4216 4217 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4218 MultiTemplateParamsArg TemplateParamLists) { 4219 // TODO: consider using NameInfo for diagnostic. 4220 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4221 DeclarationName Name = NameInfo.getName(); 4222 4223 // All of these full declarators require an identifier. If it doesn't have 4224 // one, the ParsedFreeStandingDeclSpec action should be used. 4225 if (!Name) { 4226 if (!D.isInvalidType()) // Reject this if we think it is valid. 4227 Diag(D.getDeclSpec().getLocStart(), 4228 diag::err_declarator_need_ident) 4229 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4230 return 0; 4231 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4232 return 0; 4233 4234 // The scope passed in may not be a decl scope. Zip up the scope tree until 4235 // we find one that is. 4236 while ((S->getFlags() & Scope::DeclScope) == 0 || 4237 (S->getFlags() & Scope::TemplateParamScope) != 0) 4238 S = S->getParent(); 4239 4240 DeclContext *DC = CurContext; 4241 if (D.getCXXScopeSpec().isInvalid()) 4242 D.setInvalidType(); 4243 else if (D.getCXXScopeSpec().isSet()) { 4244 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4245 UPPC_DeclarationQualifier)) 4246 return 0; 4247 4248 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4249 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4250 if (!DC || isa<EnumDecl>(DC)) { 4251 // If we could not compute the declaration context, it's because the 4252 // declaration context is dependent but does not refer to a class, 4253 // class template, or class template partial specialization. Complain 4254 // and return early, to avoid the coming semantic disaster. 4255 Diag(D.getIdentifierLoc(), 4256 diag::err_template_qualified_declarator_no_match) 4257 << D.getCXXScopeSpec().getScopeRep() 4258 << D.getCXXScopeSpec().getRange(); 4259 return 0; 4260 } 4261 bool IsDependentContext = DC->isDependentContext(); 4262 4263 if (!IsDependentContext && 4264 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4265 return 0; 4266 4267 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4268 Diag(D.getIdentifierLoc(), 4269 diag::err_member_def_undefined_record) 4270 << Name << DC << D.getCXXScopeSpec().getRange(); 4271 D.setInvalidType(); 4272 } else if (!D.getDeclSpec().isFriendSpecified()) { 4273 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4274 Name, D.getIdentifierLoc())) { 4275 if (DC->isRecord()) 4276 return 0; 4277 4278 D.setInvalidType(); 4279 } 4280 } 4281 4282 // Check whether we need to rebuild the type of the given 4283 // declaration in the current instantiation. 4284 if (EnteringContext && IsDependentContext && 4285 TemplateParamLists.size() != 0) { 4286 ContextRAII SavedContext(*this, DC); 4287 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4288 D.setInvalidType(); 4289 } 4290 } 4291 4292 if (DiagnoseClassNameShadow(DC, NameInfo)) 4293 // If this is a typedef, we'll end up spewing multiple diagnostics. 4294 // Just return early; it's safer. 4295 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4296 return 0; 4297 4298 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4299 QualType R = TInfo->getType(); 4300 4301 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4302 UPPC_DeclarationType)) 4303 D.setInvalidType(); 4304 4305 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4306 ForRedeclaration); 4307 4308 // See if this is a redefinition of a variable in the same scope. 4309 if (!D.getCXXScopeSpec().isSet()) { 4310 bool IsLinkageLookup = false; 4311 bool CreateBuiltins = false; 4312 4313 // If the declaration we're planning to build will be a function 4314 // or object with linkage, then look for another declaration with 4315 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4316 // 4317 // If the declaration we're planning to build will be declared with 4318 // external linkage in the translation unit, create any builtin with 4319 // the same name. 4320 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4321 /* Do nothing*/; 4322 else if (CurContext->isFunctionOrMethod() && 4323 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4324 R->isFunctionType())) { 4325 IsLinkageLookup = true; 4326 CreateBuiltins = 4327 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4328 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4329 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4330 CreateBuiltins = true; 4331 4332 if (IsLinkageLookup) 4333 Previous.clear(LookupRedeclarationWithLinkage); 4334 4335 LookupName(Previous, S, CreateBuiltins); 4336 } else { // Something like "int foo::x;" 4337 LookupQualifiedName(Previous, DC); 4338 4339 // C++ [dcl.meaning]p1: 4340 // When the declarator-id is qualified, the declaration shall refer to a 4341 // previously declared member of the class or namespace to which the 4342 // qualifier refers (or, in the case of a namespace, of an element of the 4343 // inline namespace set of that namespace (7.3.1)) or to a specialization 4344 // thereof; [...] 4345 // 4346 // Note that we already checked the context above, and that we do not have 4347 // enough information to make sure that Previous contains the declaration 4348 // we want to match. For example, given: 4349 // 4350 // class X { 4351 // void f(); 4352 // void f(float); 4353 // }; 4354 // 4355 // void X::f(int) { } // ill-formed 4356 // 4357 // In this case, Previous will point to the overload set 4358 // containing the two f's declared in X, but neither of them 4359 // matches. 4360 4361 // C++ [dcl.meaning]p1: 4362 // [...] the member shall not merely have been introduced by a 4363 // using-declaration in the scope of the class or namespace nominated by 4364 // the nested-name-specifier of the declarator-id. 4365 RemoveUsingDecls(Previous); 4366 } 4367 4368 if (Previous.isSingleResult() && 4369 Previous.getFoundDecl()->isTemplateParameter()) { 4370 // Maybe we will complain about the shadowed template parameter. 4371 if (!D.isInvalidType()) 4372 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4373 Previous.getFoundDecl()); 4374 4375 // Just pretend that we didn't see the previous declaration. 4376 Previous.clear(); 4377 } 4378 4379 // In C++, the previous declaration we find might be a tag type 4380 // (class or enum). In this case, the new declaration will hide the 4381 // tag type. Note that this does does not apply if we're declaring a 4382 // typedef (C++ [dcl.typedef]p4). 4383 if (Previous.isSingleTagDecl() && 4384 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4385 Previous.clear(); 4386 4387 // Check that there are no default arguments other than in the parameters 4388 // of a function declaration (C++ only). 4389 if (getLangOpts().CPlusPlus) 4390 CheckExtraCXXDefaultArguments(D); 4391 4392 NamedDecl *New; 4393 4394 bool AddToScope = true; 4395 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4396 if (TemplateParamLists.size()) { 4397 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4398 return 0; 4399 } 4400 4401 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4402 } else if (R->isFunctionType()) { 4403 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4404 TemplateParamLists, 4405 AddToScope); 4406 } else { 4407 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4408 AddToScope); 4409 } 4410 4411 if (New == 0) 4412 return 0; 4413 4414 // If this has an identifier and is not an invalid redeclaration or 4415 // function template specialization, add it to the scope stack. 4416 if (New->getDeclName() && AddToScope && 4417 !(D.isRedeclaration() && New->isInvalidDecl())) { 4418 // Only make a locally-scoped extern declaration visible if it is the first 4419 // declaration of this entity. Qualified lookup for such an entity should 4420 // only find this declaration if there is no visible declaration of it. 4421 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4422 PushOnScopeChains(New, S, AddToContext); 4423 if (!AddToContext) 4424 CurContext->addHiddenDecl(New); 4425 } 4426 4427 return New; 4428 } 4429 4430 /// Helper method to turn variable array types into constant array 4431 /// types in certain situations which would otherwise be errors (for 4432 /// GCC compatibility). 4433 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4434 ASTContext &Context, 4435 bool &SizeIsNegative, 4436 llvm::APSInt &Oversized) { 4437 // This method tries to turn a variable array into a constant 4438 // array even when the size isn't an ICE. This is necessary 4439 // for compatibility with code that depends on gcc's buggy 4440 // constant expression folding, like struct {char x[(int)(char*)2];} 4441 SizeIsNegative = false; 4442 Oversized = 0; 4443 4444 if (T->isDependentType()) 4445 return QualType(); 4446 4447 QualifierCollector Qs; 4448 const Type *Ty = Qs.strip(T); 4449 4450 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4451 QualType Pointee = PTy->getPointeeType(); 4452 QualType FixedType = 4453 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4454 Oversized); 4455 if (FixedType.isNull()) return FixedType; 4456 FixedType = Context.getPointerType(FixedType); 4457 return Qs.apply(Context, FixedType); 4458 } 4459 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4460 QualType Inner = PTy->getInnerType(); 4461 QualType FixedType = 4462 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4463 Oversized); 4464 if (FixedType.isNull()) return FixedType; 4465 FixedType = Context.getParenType(FixedType); 4466 return Qs.apply(Context, FixedType); 4467 } 4468 4469 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4470 if (!VLATy) 4471 return QualType(); 4472 // FIXME: We should probably handle this case 4473 if (VLATy->getElementType()->isVariablyModifiedType()) 4474 return QualType(); 4475 4476 llvm::APSInt Res; 4477 if (!VLATy->getSizeExpr() || 4478 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4479 return QualType(); 4480 4481 // Check whether the array size is negative. 4482 if (Res.isSigned() && Res.isNegative()) { 4483 SizeIsNegative = true; 4484 return QualType(); 4485 } 4486 4487 // Check whether the array is too large to be addressed. 4488 unsigned ActiveSizeBits 4489 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4490 Res); 4491 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4492 Oversized = Res; 4493 return QualType(); 4494 } 4495 4496 return Context.getConstantArrayType(VLATy->getElementType(), 4497 Res, ArrayType::Normal, 0); 4498 } 4499 4500 static void 4501 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4502 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4503 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4504 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4505 DstPTL.getPointeeLoc()); 4506 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4507 return; 4508 } 4509 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4510 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4511 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4512 DstPTL.getInnerLoc()); 4513 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4514 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4515 return; 4516 } 4517 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4518 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4519 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4520 TypeLoc DstElemTL = DstATL.getElementLoc(); 4521 DstElemTL.initializeFullCopy(SrcElemTL); 4522 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4523 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4524 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4525 } 4526 4527 /// Helper method to turn variable array types into constant array 4528 /// types in certain situations which would otherwise be errors (for 4529 /// GCC compatibility). 4530 static TypeSourceInfo* 4531 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4532 ASTContext &Context, 4533 bool &SizeIsNegative, 4534 llvm::APSInt &Oversized) { 4535 QualType FixedTy 4536 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4537 SizeIsNegative, Oversized); 4538 if (FixedTy.isNull()) 4539 return 0; 4540 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4541 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4542 FixedTInfo->getTypeLoc()); 4543 return FixedTInfo; 4544 } 4545 4546 /// \brief Register the given locally-scoped extern "C" declaration so 4547 /// that it can be found later for redeclarations. We include any extern "C" 4548 /// declaration that is not visible in the translation unit here, not just 4549 /// function-scope declarations. 4550 void 4551 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4552 if (!getLangOpts().CPlusPlus && 4553 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4554 // Don't need to track declarations in the TU in C. 4555 return; 4556 4557 // Note that we have a locally-scoped external with this name. 4558 // FIXME: There can be multiple such declarations if they are functions marked 4559 // __attribute__((overloadable)) declared in function scope in C. 4560 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4561 } 4562 4563 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4564 if (ExternalSource) { 4565 // Load locally-scoped external decls from the external source. 4566 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4567 SmallVector<NamedDecl *, 4> Decls; 4568 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4569 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4570 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4571 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4572 if (Pos == LocallyScopedExternCDecls.end()) 4573 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4574 } 4575 } 4576 4577 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4578 return D ? D->getMostRecentDecl() : 0; 4579 } 4580 4581 /// \brief Diagnose function specifiers on a declaration of an identifier that 4582 /// does not identify a function. 4583 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4584 // FIXME: We should probably indicate the identifier in question to avoid 4585 // confusion for constructs like "inline int a(), b;" 4586 if (DS.isInlineSpecified()) 4587 Diag(DS.getInlineSpecLoc(), 4588 diag::err_inline_non_function); 4589 4590 if (DS.isVirtualSpecified()) 4591 Diag(DS.getVirtualSpecLoc(), 4592 diag::err_virtual_non_function); 4593 4594 if (DS.isExplicitSpecified()) 4595 Diag(DS.getExplicitSpecLoc(), 4596 diag::err_explicit_non_function); 4597 4598 if (DS.isNoreturnSpecified()) 4599 Diag(DS.getNoreturnSpecLoc(), 4600 diag::err_noreturn_non_function); 4601 } 4602 4603 NamedDecl* 4604 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4605 TypeSourceInfo *TInfo, LookupResult &Previous) { 4606 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4607 if (D.getCXXScopeSpec().isSet()) { 4608 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4609 << D.getCXXScopeSpec().getRange(); 4610 D.setInvalidType(); 4611 // Pretend we didn't see the scope specifier. 4612 DC = CurContext; 4613 Previous.clear(); 4614 } 4615 4616 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4617 4618 if (D.getDeclSpec().isConstexprSpecified()) 4619 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4620 << 1; 4621 4622 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4623 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4624 << D.getName().getSourceRange(); 4625 return 0; 4626 } 4627 4628 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4629 if (!NewTD) return 0; 4630 4631 // Handle attributes prior to checking for duplicates in MergeVarDecl 4632 ProcessDeclAttributes(S, NewTD, D); 4633 4634 CheckTypedefForVariablyModifiedType(S, NewTD); 4635 4636 bool Redeclaration = D.isRedeclaration(); 4637 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4638 D.setRedeclaration(Redeclaration); 4639 return ND; 4640 } 4641 4642 void 4643 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4644 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4645 // then it shall have block scope. 4646 // Note that variably modified types must be fixed before merging the decl so 4647 // that redeclarations will match. 4648 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4649 QualType T = TInfo->getType(); 4650 if (T->isVariablyModifiedType()) { 4651 getCurFunction()->setHasBranchProtectedScope(); 4652 4653 if (S->getFnParent() == 0) { 4654 bool SizeIsNegative; 4655 llvm::APSInt Oversized; 4656 TypeSourceInfo *FixedTInfo = 4657 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4658 SizeIsNegative, 4659 Oversized); 4660 if (FixedTInfo) { 4661 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4662 NewTD->setTypeSourceInfo(FixedTInfo); 4663 } else { 4664 if (SizeIsNegative) 4665 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4666 else if (T->isVariableArrayType()) 4667 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4668 else if (Oversized.getBoolValue()) 4669 Diag(NewTD->getLocation(), diag::err_array_too_large) 4670 << Oversized.toString(10); 4671 else 4672 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4673 NewTD->setInvalidDecl(); 4674 } 4675 } 4676 } 4677 } 4678 4679 4680 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4681 /// declares a typedef-name, either using the 'typedef' type specifier or via 4682 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4683 NamedDecl* 4684 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4685 LookupResult &Previous, bool &Redeclaration) { 4686 // Merge the decl with the existing one if appropriate. If the decl is 4687 // in an outer scope, it isn't the same thing. 4688 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4689 /*AllowInlineNamespace*/false); 4690 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4691 if (!Previous.empty()) { 4692 Redeclaration = true; 4693 MergeTypedefNameDecl(NewTD, Previous); 4694 } 4695 4696 // If this is the C FILE type, notify the AST context. 4697 if (IdentifierInfo *II = NewTD->getIdentifier()) 4698 if (!NewTD->isInvalidDecl() && 4699 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4700 if (II->isStr("FILE")) 4701 Context.setFILEDecl(NewTD); 4702 else if (II->isStr("jmp_buf")) 4703 Context.setjmp_bufDecl(NewTD); 4704 else if (II->isStr("sigjmp_buf")) 4705 Context.setsigjmp_bufDecl(NewTD); 4706 else if (II->isStr("ucontext_t")) 4707 Context.setucontext_tDecl(NewTD); 4708 } 4709 4710 return NewTD; 4711 } 4712 4713 /// \brief Determines whether the given declaration is an out-of-scope 4714 /// previous declaration. 4715 /// 4716 /// This routine should be invoked when name lookup has found a 4717 /// previous declaration (PrevDecl) that is not in the scope where a 4718 /// new declaration by the same name is being introduced. If the new 4719 /// declaration occurs in a local scope, previous declarations with 4720 /// linkage may still be considered previous declarations (C99 4721 /// 6.2.2p4-5, C++ [basic.link]p6). 4722 /// 4723 /// \param PrevDecl the previous declaration found by name 4724 /// lookup 4725 /// 4726 /// \param DC the context in which the new declaration is being 4727 /// declared. 4728 /// 4729 /// \returns true if PrevDecl is an out-of-scope previous declaration 4730 /// for a new delcaration with the same name. 4731 static bool 4732 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4733 ASTContext &Context) { 4734 if (!PrevDecl) 4735 return false; 4736 4737 if (!PrevDecl->hasLinkage()) 4738 return false; 4739 4740 if (Context.getLangOpts().CPlusPlus) { 4741 // C++ [basic.link]p6: 4742 // If there is a visible declaration of an entity with linkage 4743 // having the same name and type, ignoring entities declared 4744 // outside the innermost enclosing namespace scope, the block 4745 // scope declaration declares that same entity and receives the 4746 // linkage of the previous declaration. 4747 DeclContext *OuterContext = DC->getRedeclContext(); 4748 if (!OuterContext->isFunctionOrMethod()) 4749 // This rule only applies to block-scope declarations. 4750 return false; 4751 4752 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4753 if (PrevOuterContext->isRecord()) 4754 // We found a member function: ignore it. 4755 return false; 4756 4757 // Find the innermost enclosing namespace for the new and 4758 // previous declarations. 4759 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4760 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4761 4762 // The previous declaration is in a different namespace, so it 4763 // isn't the same function. 4764 if (!OuterContext->Equals(PrevOuterContext)) 4765 return false; 4766 } 4767 4768 return true; 4769 } 4770 4771 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4772 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4773 if (!SS.isSet()) return; 4774 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4775 } 4776 4777 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4778 QualType type = decl->getType(); 4779 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4780 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4781 // Various kinds of declaration aren't allowed to be __autoreleasing. 4782 unsigned kind = -1U; 4783 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4784 if (var->hasAttr<BlocksAttr>()) 4785 kind = 0; // __block 4786 else if (!var->hasLocalStorage()) 4787 kind = 1; // global 4788 } else if (isa<ObjCIvarDecl>(decl)) { 4789 kind = 3; // ivar 4790 } else if (isa<FieldDecl>(decl)) { 4791 kind = 2; // field 4792 } 4793 4794 if (kind != -1U) { 4795 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4796 << kind; 4797 } 4798 } else if (lifetime == Qualifiers::OCL_None) { 4799 // Try to infer lifetime. 4800 if (!type->isObjCLifetimeType()) 4801 return false; 4802 4803 lifetime = type->getObjCARCImplicitLifetime(); 4804 type = Context.getLifetimeQualifiedType(type, lifetime); 4805 decl->setType(type); 4806 } 4807 4808 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4809 // Thread-local variables cannot have lifetime. 4810 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4811 var->getTLSKind()) { 4812 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4813 << var->getType(); 4814 return true; 4815 } 4816 } 4817 4818 return false; 4819 } 4820 4821 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4822 // Ensure that an auto decl is deduced otherwise the checks below might cache 4823 // the wrong linkage. 4824 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4825 4826 // 'weak' only applies to declarations with external linkage. 4827 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4828 if (!ND.isExternallyVisible()) { 4829 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4830 ND.dropAttr<WeakAttr>(); 4831 } 4832 } 4833 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4834 if (ND.isExternallyVisible()) { 4835 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4836 ND.dropAttr<WeakRefAttr>(); 4837 } 4838 } 4839 4840 // 'selectany' only applies to externally visible varable declarations. 4841 // It does not apply to functions. 4842 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4843 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4844 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4845 ND.dropAttr<SelectAnyAttr>(); 4846 } 4847 } 4848 4849 // dll attributes require external linkage. 4850 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) { 4851 if (!ND.isExternallyVisible()) { 4852 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4853 << &ND << Attr; 4854 ND.setInvalidDecl(); 4855 } 4856 } 4857 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) { 4858 if (!ND.isExternallyVisible()) { 4859 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4860 << &ND << Attr; 4861 ND.setInvalidDecl(); 4862 } 4863 } 4864 } 4865 4866 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 4867 NamedDecl *NewDecl, 4868 bool IsSpecialization) { 4869 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 4870 OldDecl = OldTD->getTemplatedDecl(); 4871 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 4872 NewDecl = NewTD->getTemplatedDecl(); 4873 4874 if (!OldDecl || !NewDecl) 4875 return; 4876 4877 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 4878 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 4879 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 4880 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 4881 4882 // dllimport and dllexport are inheritable attributes so we have to exclude 4883 // inherited attribute instances. 4884 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 4885 (NewExportAttr && !NewExportAttr->isInherited()); 4886 4887 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 4888 // the only exception being explicit specializations. 4889 // Implicitly generated declarations are also excluded for now because there 4890 // is no other way to switch these to use dllimport or dllexport. 4891 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 4892 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 4893 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration) 4894 << NewDecl 4895 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 4896 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4897 NewDecl->setInvalidDecl(); 4898 return; 4899 } 4900 4901 // A redeclaration is not allowed to drop a dllimport attribute, the only 4902 // exception being inline function definitions. 4903 // FIXME: Handle inline functions. 4904 // NB: MSVC converts such a declaration to dllexport. 4905 if (OldImportAttr && !HasNewAttr) { 4906 S.Diag(NewDecl->getLocation(), 4907 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4908 << NewDecl << OldImportAttr; 4909 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4910 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 4911 OldDecl->dropAttr<DLLImportAttr>(); 4912 NewDecl->dropAttr<DLLImportAttr>(); 4913 } 4914 } 4915 4916 /// Given that we are within the definition of the given function, 4917 /// will that definition behave like C99's 'inline', where the 4918 /// definition is discarded except for optimization purposes? 4919 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4920 // Try to avoid calling GetGVALinkageForFunction. 4921 4922 // All cases of this require the 'inline' keyword. 4923 if (!FD->isInlined()) return false; 4924 4925 // This is only possible in C++ with the gnu_inline attribute. 4926 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4927 return false; 4928 4929 // Okay, go ahead and call the relatively-more-expensive function. 4930 4931 #ifndef NDEBUG 4932 // AST quite reasonably asserts that it's working on a function 4933 // definition. We don't really have a way to tell it that we're 4934 // currently defining the function, so just lie to it in +Asserts 4935 // builds. This is an awful hack. 4936 FD->setLazyBody(1); 4937 #endif 4938 4939 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4940 4941 #ifndef NDEBUG 4942 FD->setLazyBody(0); 4943 #endif 4944 4945 return isC99Inline; 4946 } 4947 4948 /// Determine whether a variable is extern "C" prior to attaching 4949 /// an initializer. We can't just call isExternC() here, because that 4950 /// will also compute and cache whether the declaration is externally 4951 /// visible, which might change when we attach the initializer. 4952 /// 4953 /// This can only be used if the declaration is known to not be a 4954 /// redeclaration of an internal linkage declaration. 4955 /// 4956 /// For instance: 4957 /// 4958 /// auto x = []{}; 4959 /// 4960 /// Attaching the initializer here makes this declaration not externally 4961 /// visible, because its type has internal linkage. 4962 /// 4963 /// FIXME: This is a hack. 4964 template<typename T> 4965 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4966 if (S.getLangOpts().CPlusPlus) { 4967 // In C++, the overloadable attribute negates the effects of extern "C". 4968 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4969 return false; 4970 } 4971 return D->isExternC(); 4972 } 4973 4974 static bool shouldConsiderLinkage(const VarDecl *VD) { 4975 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4976 if (DC->isFunctionOrMethod()) 4977 return VD->hasExternalStorage(); 4978 if (DC->isFileContext()) 4979 return true; 4980 if (DC->isRecord()) 4981 return false; 4982 llvm_unreachable("Unexpected context"); 4983 } 4984 4985 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4986 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4987 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4988 return true; 4989 if (DC->isRecord()) 4990 return false; 4991 llvm_unreachable("Unexpected context"); 4992 } 4993 4994 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 4995 AttributeList::Kind Kind) { 4996 for (const AttributeList *L = AttrList; L; L = L->getNext()) 4997 if (L->getKind() == Kind) 4998 return true; 4999 return false; 5000 } 5001 5002 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5003 AttributeList::Kind Kind) { 5004 // Check decl attributes on the DeclSpec. 5005 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5006 return true; 5007 5008 // Walk the declarator structure, checking decl attributes that were in a type 5009 // position to the decl itself. 5010 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5011 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5012 return true; 5013 } 5014 5015 // Finally, check attributes on the decl itself. 5016 return hasParsedAttr(S, PD.getAttributes(), Kind); 5017 } 5018 5019 /// Adjust the \c DeclContext for a function or variable that might be a 5020 /// function-local external declaration. 5021 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5022 if (!DC->isFunctionOrMethod()) 5023 return false; 5024 5025 // If this is a local extern function or variable declared within a function 5026 // template, don't add it into the enclosing namespace scope until it is 5027 // instantiated; it might have a dependent type right now. 5028 if (DC->isDependentContext()) 5029 return true; 5030 5031 // C++11 [basic.link]p7: 5032 // When a block scope declaration of an entity with linkage is not found to 5033 // refer to some other declaration, then that entity is a member of the 5034 // innermost enclosing namespace. 5035 // 5036 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5037 // semantically-enclosing namespace, not a lexically-enclosing one. 5038 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5039 DC = DC->getParent(); 5040 return true; 5041 } 5042 5043 NamedDecl * 5044 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5045 TypeSourceInfo *TInfo, LookupResult &Previous, 5046 MultiTemplateParamsArg TemplateParamLists, 5047 bool &AddToScope) { 5048 QualType R = TInfo->getType(); 5049 DeclarationName Name = GetNameForDeclarator(D).getName(); 5050 5051 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5052 VarDecl::StorageClass SC = 5053 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5054 5055 // dllimport globals without explicit storage class are treated as extern. We 5056 // have to change the storage class this early to get the right DeclContext. 5057 if (SC == SC_None && !DC->isRecord() && 5058 hasParsedAttr(S, D, AttributeList::AT_DLLImport)) 5059 SC = SC_Extern; 5060 5061 DeclContext *OriginalDC = DC; 5062 bool IsLocalExternDecl = SC == SC_Extern && 5063 adjustContextForLocalExternDecl(DC); 5064 5065 if (getLangOpts().OpenCL) { 5066 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5067 QualType NR = R; 5068 while (NR->isPointerType()) { 5069 if (NR->isFunctionPointerType()) { 5070 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5071 D.setInvalidType(); 5072 break; 5073 } 5074 NR = NR->getPointeeType(); 5075 } 5076 5077 if (!getOpenCLOptions().cl_khr_fp16) { 5078 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5079 // half array type (unless the cl_khr_fp16 extension is enabled). 5080 if (Context.getBaseElementType(R)->isHalfType()) { 5081 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5082 D.setInvalidType(); 5083 } 5084 } 5085 } 5086 5087 if (SCSpec == DeclSpec::SCS_mutable) { 5088 // mutable can only appear on non-static class members, so it's always 5089 // an error here 5090 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5091 D.setInvalidType(); 5092 SC = SC_None; 5093 } 5094 5095 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5096 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5097 D.getDeclSpec().getStorageClassSpecLoc())) { 5098 // In C++11, the 'register' storage class specifier is deprecated. 5099 // Suppress the warning in system macros, it's used in macros in some 5100 // popular C system headers, such as in glibc's htonl() macro. 5101 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5102 diag::warn_deprecated_register) 5103 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5104 } 5105 5106 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5107 if (!II) { 5108 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5109 << Name; 5110 return 0; 5111 } 5112 5113 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5114 5115 if (!DC->isRecord() && S->getFnParent() == 0) { 5116 // C99 6.9p2: The storage-class specifiers auto and register shall not 5117 // appear in the declaration specifiers in an external declaration. 5118 if (SC == SC_Auto || SC == SC_Register) { 5119 // If this is a register variable with an asm label specified, then this 5120 // is a GNU extension. 5121 if (SC == SC_Register && D.getAsmLabel()) 5122 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 5123 else 5124 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5125 D.setInvalidType(); 5126 } 5127 } 5128 5129 if (getLangOpts().OpenCL) { 5130 // Set up the special work-group-local storage class for variables in the 5131 // OpenCL __local address space. 5132 if (R.getAddressSpace() == LangAS::opencl_local) { 5133 SC = SC_OpenCLWorkGroupLocal; 5134 } 5135 5136 // OpenCL v1.2 s6.9.b p4: 5137 // The sampler type cannot be used with the __local and __global address 5138 // space qualifiers. 5139 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5140 R.getAddressSpace() == LangAS::opencl_global)) { 5141 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5142 } 5143 5144 // OpenCL 1.2 spec, p6.9 r: 5145 // The event type cannot be used to declare a program scope variable. 5146 // The event type cannot be used with the __local, __constant and __global 5147 // address space qualifiers. 5148 if (R->isEventT()) { 5149 if (S->getParent() == 0) { 5150 Diag(D.getLocStart(), diag::err_event_t_global_var); 5151 D.setInvalidType(); 5152 } 5153 5154 if (R.getAddressSpace()) { 5155 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5156 D.setInvalidType(); 5157 } 5158 } 5159 } 5160 5161 bool IsExplicitSpecialization = false; 5162 bool IsVariableTemplateSpecialization = false; 5163 bool IsPartialSpecialization = false; 5164 bool IsVariableTemplate = false; 5165 VarDecl *NewVD = 0; 5166 VarTemplateDecl *NewTemplate = 0; 5167 TemplateParameterList *TemplateParams = 0; 5168 if (!getLangOpts().CPlusPlus) { 5169 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5170 D.getIdentifierLoc(), II, 5171 R, TInfo, SC); 5172 5173 if (D.isInvalidType()) 5174 NewVD->setInvalidDecl(); 5175 } else { 5176 bool Invalid = false; 5177 5178 if (DC->isRecord() && !CurContext->isRecord()) { 5179 // This is an out-of-line definition of a static data member. 5180 switch (SC) { 5181 case SC_None: 5182 break; 5183 case SC_Static: 5184 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5185 diag::err_static_out_of_line) 5186 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5187 break; 5188 case SC_Auto: 5189 case SC_Register: 5190 case SC_Extern: 5191 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5192 // to names of variables declared in a block or to function parameters. 5193 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5194 // of class members 5195 5196 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5197 diag::err_storage_class_for_static_member) 5198 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5199 break; 5200 case SC_PrivateExtern: 5201 llvm_unreachable("C storage class in c++!"); 5202 case SC_OpenCLWorkGroupLocal: 5203 llvm_unreachable("OpenCL storage class in c++!"); 5204 } 5205 } 5206 5207 if (SC == SC_Static && CurContext->isRecord()) { 5208 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5209 if (RD->isLocalClass()) 5210 Diag(D.getIdentifierLoc(), 5211 diag::err_static_data_member_not_allowed_in_local_class) 5212 << Name << RD->getDeclName(); 5213 5214 // C++98 [class.union]p1: If a union contains a static data member, 5215 // the program is ill-formed. C++11 drops this restriction. 5216 if (RD->isUnion()) 5217 Diag(D.getIdentifierLoc(), 5218 getLangOpts().CPlusPlus11 5219 ? diag::warn_cxx98_compat_static_data_member_in_union 5220 : diag::ext_static_data_member_in_union) << Name; 5221 // We conservatively disallow static data members in anonymous structs. 5222 else if (!RD->getDeclName()) 5223 Diag(D.getIdentifierLoc(), 5224 diag::err_static_data_member_not_allowed_in_anon_struct) 5225 << Name << RD->isUnion(); 5226 } 5227 } 5228 5229 // Match up the template parameter lists with the scope specifier, then 5230 // determine whether we have a template or a template specialization. 5231 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5232 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5233 D.getCXXScopeSpec(), 5234 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5235 ? D.getName().TemplateId 5236 : 0, 5237 TemplateParamLists, 5238 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5239 5240 if (TemplateParams) { 5241 if (!TemplateParams->size() && 5242 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5243 // There is an extraneous 'template<>' for this variable. Complain 5244 // about it, but allow the declaration of the variable. 5245 Diag(TemplateParams->getTemplateLoc(), 5246 diag::err_template_variable_noparams) 5247 << II 5248 << SourceRange(TemplateParams->getTemplateLoc(), 5249 TemplateParams->getRAngleLoc()); 5250 TemplateParams = 0; 5251 } else { 5252 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5253 // This is an explicit specialization or a partial specialization. 5254 // FIXME: Check that we can declare a specialization here. 5255 IsVariableTemplateSpecialization = true; 5256 IsPartialSpecialization = TemplateParams->size() > 0; 5257 } else { // if (TemplateParams->size() > 0) 5258 // This is a template declaration. 5259 IsVariableTemplate = true; 5260 5261 // Check that we can declare a template here. 5262 if (CheckTemplateDeclScope(S, TemplateParams)) 5263 return 0; 5264 5265 // Only C++1y supports variable templates (N3651). 5266 Diag(D.getIdentifierLoc(), 5267 getLangOpts().CPlusPlus1y 5268 ? diag::warn_cxx11_compat_variable_template 5269 : diag::ext_variable_template); 5270 } 5271 } 5272 } else { 5273 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId && 5274 "should have a 'template<>' for this decl"); 5275 } 5276 5277 if (IsVariableTemplateSpecialization) { 5278 SourceLocation TemplateKWLoc = 5279 TemplateParamLists.size() > 0 5280 ? TemplateParamLists[0]->getTemplateLoc() 5281 : SourceLocation(); 5282 DeclResult Res = ActOnVarTemplateSpecialization( 5283 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5284 IsPartialSpecialization); 5285 if (Res.isInvalid()) 5286 return 0; 5287 NewVD = cast<VarDecl>(Res.get()); 5288 AddToScope = false; 5289 } else 5290 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5291 D.getIdentifierLoc(), II, R, TInfo, SC); 5292 5293 // If this is supposed to be a variable template, create it as such. 5294 if (IsVariableTemplate) { 5295 NewTemplate = 5296 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5297 TemplateParams, NewVD); 5298 NewVD->setDescribedVarTemplate(NewTemplate); 5299 } 5300 5301 // If this decl has an auto type in need of deduction, make a note of the 5302 // Decl so we can diagnose uses of it in its own initializer. 5303 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5304 ParsingInitForAutoVars.insert(NewVD); 5305 5306 if (D.isInvalidType() || Invalid) { 5307 NewVD->setInvalidDecl(); 5308 if (NewTemplate) 5309 NewTemplate->setInvalidDecl(); 5310 } 5311 5312 SetNestedNameSpecifier(NewVD, D); 5313 5314 // If we have any template parameter lists that don't directly belong to 5315 // the variable (matching the scope specifier), store them. 5316 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5317 if (TemplateParamLists.size() > VDTemplateParamLists) 5318 NewVD->setTemplateParameterListsInfo( 5319 Context, TemplateParamLists.size() - VDTemplateParamLists, 5320 TemplateParamLists.data()); 5321 5322 if (D.getDeclSpec().isConstexprSpecified()) 5323 NewVD->setConstexpr(true); 5324 } 5325 5326 // Set the lexical context. If the declarator has a C++ scope specifier, the 5327 // lexical context will be different from the semantic context. 5328 NewVD->setLexicalDeclContext(CurContext); 5329 if (NewTemplate) 5330 NewTemplate->setLexicalDeclContext(CurContext); 5331 5332 if (IsLocalExternDecl) 5333 NewVD->setLocalExternDecl(); 5334 5335 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5336 if (NewVD->hasLocalStorage()) { 5337 // C++11 [dcl.stc]p4: 5338 // When thread_local is applied to a variable of block scope the 5339 // storage-class-specifier static is implied if it does not appear 5340 // explicitly. 5341 // Core issue: 'static' is not implied if the variable is declared 5342 // 'extern'. 5343 if (SCSpec == DeclSpec::SCS_unspecified && 5344 TSCS == DeclSpec::TSCS_thread_local && 5345 DC->isFunctionOrMethod()) 5346 NewVD->setTSCSpec(TSCS); 5347 else 5348 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5349 diag::err_thread_non_global) 5350 << DeclSpec::getSpecifierName(TSCS); 5351 } else if (!Context.getTargetInfo().isTLSSupported()) 5352 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5353 diag::err_thread_unsupported); 5354 else 5355 NewVD->setTSCSpec(TSCS); 5356 } 5357 5358 // C99 6.7.4p3 5359 // An inline definition of a function with external linkage shall 5360 // not contain a definition of a modifiable object with static or 5361 // thread storage duration... 5362 // We only apply this when the function is required to be defined 5363 // elsewhere, i.e. when the function is not 'extern inline'. Note 5364 // that a local variable with thread storage duration still has to 5365 // be marked 'static'. Also note that it's possible to get these 5366 // semantics in C++ using __attribute__((gnu_inline)). 5367 if (SC == SC_Static && S->getFnParent() != 0 && 5368 !NewVD->getType().isConstQualified()) { 5369 FunctionDecl *CurFD = getCurFunctionDecl(); 5370 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5371 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5372 diag::warn_static_local_in_extern_inline); 5373 MaybeSuggestAddingStaticToDecl(CurFD); 5374 } 5375 } 5376 5377 if (D.getDeclSpec().isModulePrivateSpecified()) { 5378 if (IsVariableTemplateSpecialization) 5379 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5380 << (IsPartialSpecialization ? 1 : 0) 5381 << FixItHint::CreateRemoval( 5382 D.getDeclSpec().getModulePrivateSpecLoc()); 5383 else if (IsExplicitSpecialization) 5384 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5385 << 2 5386 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5387 else if (NewVD->hasLocalStorage()) 5388 Diag(NewVD->getLocation(), diag::err_module_private_local) 5389 << 0 << NewVD->getDeclName() 5390 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5391 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5392 else { 5393 NewVD->setModulePrivate(); 5394 if (NewTemplate) 5395 NewTemplate->setModulePrivate(); 5396 } 5397 } 5398 5399 // Handle attributes prior to checking for duplicates in MergeVarDecl 5400 ProcessDeclAttributes(S, NewVD, D); 5401 5402 if (getLangOpts().CUDA) { 5403 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5404 // storage [duration]." 5405 if (SC == SC_None && S->getFnParent() != 0 && 5406 (NewVD->hasAttr<CUDASharedAttr>() || 5407 NewVD->hasAttr<CUDAConstantAttr>())) { 5408 NewVD->setStorageClass(SC_Static); 5409 } 5410 } 5411 5412 // Ensure that dllimport globals without explicit storage class are treated as 5413 // extern. The storage class is set above using parsed attributes. Now we can 5414 // check the VarDecl itself. 5415 assert(!NewVD->hasAttr<DLLImportAttr>() || 5416 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5417 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5418 5419 // In auto-retain/release, infer strong retension for variables of 5420 // retainable type. 5421 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5422 NewVD->setInvalidDecl(); 5423 5424 // Handle GNU asm-label extension (encoded as an attribute). 5425 if (Expr *E = (Expr*)D.getAsmLabel()) { 5426 // The parser guarantees this is a string. 5427 StringLiteral *SE = cast<StringLiteral>(E); 5428 StringRef Label = SE->getString(); 5429 if (S->getFnParent() != 0) { 5430 switch (SC) { 5431 case SC_None: 5432 case SC_Auto: 5433 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5434 break; 5435 case SC_Register: 5436 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5437 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5438 break; 5439 case SC_Static: 5440 case SC_Extern: 5441 case SC_PrivateExtern: 5442 case SC_OpenCLWorkGroupLocal: 5443 break; 5444 } 5445 } 5446 5447 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5448 Context, Label, 0)); 5449 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5450 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5451 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5452 if (I != ExtnameUndeclaredIdentifiers.end()) { 5453 NewVD->addAttr(I->second); 5454 ExtnameUndeclaredIdentifiers.erase(I); 5455 } 5456 } 5457 5458 // Diagnose shadowed variables before filtering for scope. 5459 if (D.getCXXScopeSpec().isEmpty()) 5460 CheckShadow(S, NewVD, Previous); 5461 5462 // Don't consider existing declarations that are in a different 5463 // scope and are out-of-semantic-context declarations (if the new 5464 // declaration has linkage). 5465 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5466 D.getCXXScopeSpec().isNotEmpty() || 5467 IsExplicitSpecialization || 5468 IsVariableTemplateSpecialization); 5469 5470 // Check whether the previous declaration is in the same block scope. This 5471 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5472 if (getLangOpts().CPlusPlus && 5473 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5474 NewVD->setPreviousDeclInSameBlockScope( 5475 Previous.isSingleResult() && !Previous.isShadowed() && 5476 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5477 5478 if (!getLangOpts().CPlusPlus) { 5479 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5480 } else { 5481 // If this is an explicit specialization of a static data member, check it. 5482 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5483 CheckMemberSpecialization(NewVD, Previous)) 5484 NewVD->setInvalidDecl(); 5485 5486 // Merge the decl with the existing one if appropriate. 5487 if (!Previous.empty()) { 5488 if (Previous.isSingleResult() && 5489 isa<FieldDecl>(Previous.getFoundDecl()) && 5490 D.getCXXScopeSpec().isSet()) { 5491 // The user tried to define a non-static data member 5492 // out-of-line (C++ [dcl.meaning]p1). 5493 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5494 << D.getCXXScopeSpec().getRange(); 5495 Previous.clear(); 5496 NewVD->setInvalidDecl(); 5497 } 5498 } else if (D.getCXXScopeSpec().isSet()) { 5499 // No previous declaration in the qualifying scope. 5500 Diag(D.getIdentifierLoc(), diag::err_no_member) 5501 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5502 << D.getCXXScopeSpec().getRange(); 5503 NewVD->setInvalidDecl(); 5504 } 5505 5506 if (!IsVariableTemplateSpecialization) 5507 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5508 5509 if (NewTemplate) { 5510 VarTemplateDecl *PrevVarTemplate = 5511 NewVD->getPreviousDecl() 5512 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5513 : 0; 5514 5515 // Check the template parameter list of this declaration, possibly 5516 // merging in the template parameter list from the previous variable 5517 // template declaration. 5518 if (CheckTemplateParameterList( 5519 TemplateParams, 5520 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5521 : 0, 5522 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5523 DC->isDependentContext()) 5524 ? TPC_ClassTemplateMember 5525 : TPC_VarTemplate)) 5526 NewVD->setInvalidDecl(); 5527 5528 // If we are providing an explicit specialization of a static variable 5529 // template, make a note of that. 5530 if (PrevVarTemplate && 5531 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5532 PrevVarTemplate->setMemberSpecialization(); 5533 } 5534 } 5535 5536 ProcessPragmaWeak(S, NewVD); 5537 5538 // If this is the first declaration of an extern C variable, update 5539 // the map of such variables. 5540 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5541 isIncompleteDeclExternC(*this, NewVD)) 5542 RegisterLocallyScopedExternCDecl(NewVD, S); 5543 5544 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5545 Decl *ManglingContextDecl; 5546 if (MangleNumberingContext *MCtx = 5547 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5548 ManglingContextDecl)) { 5549 Context.setManglingNumber( 5550 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5551 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5552 } 5553 } 5554 5555 if (D.isRedeclaration() && !Previous.empty()) { 5556 checkDLLAttributeRedeclaration( 5557 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5558 IsExplicitSpecialization); 5559 } 5560 5561 if (NewTemplate) { 5562 if (NewVD->isInvalidDecl()) 5563 NewTemplate->setInvalidDecl(); 5564 ActOnDocumentableDecl(NewTemplate); 5565 return NewTemplate; 5566 } 5567 5568 return NewVD; 5569 } 5570 5571 /// \brief Diagnose variable or built-in function shadowing. Implements 5572 /// -Wshadow. 5573 /// 5574 /// This method is called whenever a VarDecl is added to a "useful" 5575 /// scope. 5576 /// 5577 /// \param S the scope in which the shadowing name is being declared 5578 /// \param R the lookup of the name 5579 /// 5580 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5581 // Return if warning is ignored. 5582 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5583 DiagnosticsEngine::Ignored) 5584 return; 5585 5586 // Don't diagnose declarations at file scope. 5587 if (D->hasGlobalStorage()) 5588 return; 5589 5590 DeclContext *NewDC = D->getDeclContext(); 5591 5592 // Only diagnose if we're shadowing an unambiguous field or variable. 5593 if (R.getResultKind() != LookupResult::Found) 5594 return; 5595 5596 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5597 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5598 return; 5599 5600 // Fields are not shadowed by variables in C++ static methods. 5601 if (isa<FieldDecl>(ShadowedDecl)) 5602 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5603 if (MD->isStatic()) 5604 return; 5605 5606 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5607 if (shadowedVar->isExternC()) { 5608 // For shadowing external vars, make sure that we point to the global 5609 // declaration, not a locally scoped extern declaration. 5610 for (auto I : shadowedVar->redecls()) 5611 if (I->isFileVarDecl()) { 5612 ShadowedDecl = I; 5613 break; 5614 } 5615 } 5616 5617 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5618 5619 // Only warn about certain kinds of shadowing for class members. 5620 if (NewDC && NewDC->isRecord()) { 5621 // In particular, don't warn about shadowing non-class members. 5622 if (!OldDC->isRecord()) 5623 return; 5624 5625 // TODO: should we warn about static data members shadowing 5626 // static data members from base classes? 5627 5628 // TODO: don't diagnose for inaccessible shadowed members. 5629 // This is hard to do perfectly because we might friend the 5630 // shadowing context, but that's just a false negative. 5631 } 5632 5633 // Determine what kind of declaration we're shadowing. 5634 unsigned Kind; 5635 if (isa<RecordDecl>(OldDC)) { 5636 if (isa<FieldDecl>(ShadowedDecl)) 5637 Kind = 3; // field 5638 else 5639 Kind = 2; // static data member 5640 } else if (OldDC->isFileContext()) 5641 Kind = 1; // global 5642 else 5643 Kind = 0; // local 5644 5645 DeclarationName Name = R.getLookupName(); 5646 5647 // Emit warning and note. 5648 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5649 return; 5650 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5651 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5652 } 5653 5654 /// \brief Check -Wshadow without the advantage of a previous lookup. 5655 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5656 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5657 DiagnosticsEngine::Ignored) 5658 return; 5659 5660 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5661 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5662 LookupName(R, S); 5663 CheckShadow(S, D, R); 5664 } 5665 5666 /// Check for conflict between this global or extern "C" declaration and 5667 /// previous global or extern "C" declarations. This is only used in C++. 5668 template<typename T> 5669 static bool checkGlobalOrExternCConflict( 5670 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5671 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5672 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5673 5674 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5675 // The common case: this global doesn't conflict with any extern "C" 5676 // declaration. 5677 return false; 5678 } 5679 5680 if (Prev) { 5681 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5682 // Both the old and new declarations have C language linkage. This is a 5683 // redeclaration. 5684 Previous.clear(); 5685 Previous.addDecl(Prev); 5686 return true; 5687 } 5688 5689 // This is a global, non-extern "C" declaration, and there is a previous 5690 // non-global extern "C" declaration. Diagnose if this is a variable 5691 // declaration. 5692 if (!isa<VarDecl>(ND)) 5693 return false; 5694 } else { 5695 // The declaration is extern "C". Check for any declaration in the 5696 // translation unit which might conflict. 5697 if (IsGlobal) { 5698 // We have already performed the lookup into the translation unit. 5699 IsGlobal = false; 5700 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5701 I != E; ++I) { 5702 if (isa<VarDecl>(*I)) { 5703 Prev = *I; 5704 break; 5705 } 5706 } 5707 } else { 5708 DeclContext::lookup_result R = 5709 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5710 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5711 I != E; ++I) { 5712 if (isa<VarDecl>(*I)) { 5713 Prev = *I; 5714 break; 5715 } 5716 // FIXME: If we have any other entity with this name in global scope, 5717 // the declaration is ill-formed, but that is a defect: it breaks the 5718 // 'stat' hack, for instance. Only variables can have mangled name 5719 // clashes with extern "C" declarations, so only they deserve a 5720 // diagnostic. 5721 } 5722 } 5723 5724 if (!Prev) 5725 return false; 5726 } 5727 5728 // Use the first declaration's location to ensure we point at something which 5729 // is lexically inside an extern "C" linkage-spec. 5730 assert(Prev && "should have found a previous declaration to diagnose"); 5731 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5732 Prev = FD->getFirstDecl(); 5733 else 5734 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5735 5736 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5737 << IsGlobal << ND; 5738 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5739 << IsGlobal; 5740 return false; 5741 } 5742 5743 /// Apply special rules for handling extern "C" declarations. Returns \c true 5744 /// if we have found that this is a redeclaration of some prior entity. 5745 /// 5746 /// Per C++ [dcl.link]p6: 5747 /// Two declarations [for a function or variable] with C language linkage 5748 /// with the same name that appear in different scopes refer to the same 5749 /// [entity]. An entity with C language linkage shall not be declared with 5750 /// the same name as an entity in global scope. 5751 template<typename T> 5752 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5753 LookupResult &Previous) { 5754 if (!S.getLangOpts().CPlusPlus) { 5755 // In C, when declaring a global variable, look for a corresponding 'extern' 5756 // variable declared in function scope. We don't need this in C++, because 5757 // we find local extern decls in the surrounding file-scope DeclContext. 5758 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5759 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5760 Previous.clear(); 5761 Previous.addDecl(Prev); 5762 return true; 5763 } 5764 } 5765 return false; 5766 } 5767 5768 // A declaration in the translation unit can conflict with an extern "C" 5769 // declaration. 5770 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5771 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5772 5773 // An extern "C" declaration can conflict with a declaration in the 5774 // translation unit or can be a redeclaration of an extern "C" declaration 5775 // in another scope. 5776 if (isIncompleteDeclExternC(S,ND)) 5777 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5778 5779 // Neither global nor extern "C": nothing to do. 5780 return false; 5781 } 5782 5783 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5784 // If the decl is already known invalid, don't check it. 5785 if (NewVD->isInvalidDecl()) 5786 return; 5787 5788 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5789 QualType T = TInfo->getType(); 5790 5791 // Defer checking an 'auto' type until its initializer is attached. 5792 if (T->isUndeducedType()) 5793 return; 5794 5795 if (NewVD->hasAttrs()) 5796 CheckAlignasUnderalignment(NewVD); 5797 5798 if (T->isObjCObjectType()) { 5799 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5800 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5801 T = Context.getObjCObjectPointerType(T); 5802 NewVD->setType(T); 5803 } 5804 5805 // Emit an error if an address space was applied to decl with local storage. 5806 // This includes arrays of objects with address space qualifiers, but not 5807 // automatic variables that point to other address spaces. 5808 // ISO/IEC TR 18037 S5.1.2 5809 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5810 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5811 NewVD->setInvalidDecl(); 5812 return; 5813 } 5814 5815 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5816 // __constant address space. 5817 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5818 && T.getAddressSpace() != LangAS::opencl_constant 5819 && !T->isSamplerT()){ 5820 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5821 NewVD->setInvalidDecl(); 5822 return; 5823 } 5824 5825 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5826 // scope. 5827 if ((getLangOpts().OpenCLVersion >= 120) 5828 && NewVD->isStaticLocal()) { 5829 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5830 NewVD->setInvalidDecl(); 5831 return; 5832 } 5833 5834 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5835 && !NewVD->hasAttr<BlocksAttr>()) { 5836 if (getLangOpts().getGC() != LangOptions::NonGC) 5837 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5838 else { 5839 assert(!getLangOpts().ObjCAutoRefCount); 5840 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5841 } 5842 } 5843 5844 bool isVM = T->isVariablyModifiedType(); 5845 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5846 NewVD->hasAttr<BlocksAttr>()) 5847 getCurFunction()->setHasBranchProtectedScope(); 5848 5849 if ((isVM && NewVD->hasLinkage()) || 5850 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5851 bool SizeIsNegative; 5852 llvm::APSInt Oversized; 5853 TypeSourceInfo *FixedTInfo = 5854 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5855 SizeIsNegative, Oversized); 5856 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5857 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5858 // FIXME: This won't give the correct result for 5859 // int a[10][n]; 5860 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5861 5862 if (NewVD->isFileVarDecl()) 5863 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5864 << SizeRange; 5865 else if (NewVD->isStaticLocal()) 5866 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5867 << SizeRange; 5868 else 5869 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5870 << SizeRange; 5871 NewVD->setInvalidDecl(); 5872 return; 5873 } 5874 5875 if (FixedTInfo == 0) { 5876 if (NewVD->isFileVarDecl()) 5877 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5878 else 5879 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5880 NewVD->setInvalidDecl(); 5881 return; 5882 } 5883 5884 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5885 NewVD->setType(FixedTInfo->getType()); 5886 NewVD->setTypeSourceInfo(FixedTInfo); 5887 } 5888 5889 if (T->isVoidType()) { 5890 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5891 // of objects and functions. 5892 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5893 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5894 << T; 5895 NewVD->setInvalidDecl(); 5896 return; 5897 } 5898 } 5899 5900 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5901 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5902 NewVD->setInvalidDecl(); 5903 return; 5904 } 5905 5906 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5907 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5908 NewVD->setInvalidDecl(); 5909 return; 5910 } 5911 5912 if (NewVD->isConstexpr() && !T->isDependentType() && 5913 RequireLiteralType(NewVD->getLocation(), T, 5914 diag::err_constexpr_var_non_literal)) { 5915 NewVD->setInvalidDecl(); 5916 return; 5917 } 5918 } 5919 5920 /// \brief Perform semantic checking on a newly-created variable 5921 /// declaration. 5922 /// 5923 /// This routine performs all of the type-checking required for a 5924 /// variable declaration once it has been built. It is used both to 5925 /// check variables after they have been parsed and their declarators 5926 /// have been translated into a declaration, and to check variables 5927 /// that have been instantiated from a template. 5928 /// 5929 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5930 /// 5931 /// Returns true if the variable declaration is a redeclaration. 5932 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5933 CheckVariableDeclarationType(NewVD); 5934 5935 // If the decl is already known invalid, don't check it. 5936 if (NewVD->isInvalidDecl()) 5937 return false; 5938 5939 // If we did not find anything by this name, look for a non-visible 5940 // extern "C" declaration with the same name. 5941 if (Previous.empty() && 5942 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5943 Previous.setShadowed(); 5944 5945 // Filter out any non-conflicting previous declarations. 5946 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5947 5948 if (!Previous.empty()) { 5949 MergeVarDecl(NewVD, Previous); 5950 return true; 5951 } 5952 return false; 5953 } 5954 5955 /// \brief Data used with FindOverriddenMethod 5956 struct FindOverriddenMethodData { 5957 Sema *S; 5958 CXXMethodDecl *Method; 5959 }; 5960 5961 /// \brief Member lookup function that determines whether a given C++ 5962 /// method overrides a method in a base class, to be used with 5963 /// CXXRecordDecl::lookupInBases(). 5964 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5965 CXXBasePath &Path, 5966 void *UserData) { 5967 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5968 5969 FindOverriddenMethodData *Data 5970 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5971 5972 DeclarationName Name = Data->Method->getDeclName(); 5973 5974 // FIXME: Do we care about other names here too? 5975 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5976 // We really want to find the base class destructor here. 5977 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5978 CanQualType CT = Data->S->Context.getCanonicalType(T); 5979 5980 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5981 } 5982 5983 for (Path.Decls = BaseRecord->lookup(Name); 5984 !Path.Decls.empty(); 5985 Path.Decls = Path.Decls.slice(1)) { 5986 NamedDecl *D = Path.Decls.front(); 5987 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5988 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5989 return true; 5990 } 5991 } 5992 5993 return false; 5994 } 5995 5996 namespace { 5997 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5998 } 5999 /// \brief Report an error regarding overriding, along with any relevant 6000 /// overriden methods. 6001 /// 6002 /// \param DiagID the primary error to report. 6003 /// \param MD the overriding method. 6004 /// \param OEK which overrides to include as notes. 6005 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6006 OverrideErrorKind OEK = OEK_All) { 6007 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6008 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6009 E = MD->end_overridden_methods(); 6010 I != E; ++I) { 6011 // This check (& the OEK parameter) could be replaced by a predicate, but 6012 // without lambdas that would be overkill. This is still nicer than writing 6013 // out the diag loop 3 times. 6014 if ((OEK == OEK_All) || 6015 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6016 (OEK == OEK_Deleted && (*I)->isDeleted())) 6017 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6018 } 6019 } 6020 6021 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6022 /// and if so, check that it's a valid override and remember it. 6023 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6024 // Look for virtual methods in base classes that this method might override. 6025 CXXBasePaths Paths; 6026 FindOverriddenMethodData Data; 6027 Data.Method = MD; 6028 Data.S = this; 6029 bool hasDeletedOverridenMethods = false; 6030 bool hasNonDeletedOverridenMethods = false; 6031 bool AddedAny = false; 6032 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6033 for (auto *I : Paths.found_decls()) { 6034 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6035 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6036 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6037 !CheckOverridingFunctionAttributes(MD, OldMD) && 6038 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6039 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6040 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6041 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6042 AddedAny = true; 6043 } 6044 } 6045 } 6046 } 6047 6048 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6049 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6050 } 6051 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6052 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6053 } 6054 6055 return AddedAny; 6056 } 6057 6058 namespace { 6059 // Struct for holding all of the extra arguments needed by 6060 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6061 struct ActOnFDArgs { 6062 Scope *S; 6063 Declarator &D; 6064 MultiTemplateParamsArg TemplateParamLists; 6065 bool AddToScope; 6066 }; 6067 } 6068 6069 namespace { 6070 6071 // Callback to only accept typo corrections that have a non-zero edit distance. 6072 // Also only accept corrections that have the same parent decl. 6073 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6074 public: 6075 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6076 CXXRecordDecl *Parent) 6077 : Context(Context), OriginalFD(TypoFD), 6078 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 6079 6080 bool ValidateCandidate(const TypoCorrection &candidate) override { 6081 if (candidate.getEditDistance() == 0) 6082 return false; 6083 6084 SmallVector<unsigned, 1> MismatchedParams; 6085 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6086 CDeclEnd = candidate.end(); 6087 CDecl != CDeclEnd; ++CDecl) { 6088 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6089 6090 if (FD && !FD->hasBody() && 6091 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6092 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6093 CXXRecordDecl *Parent = MD->getParent(); 6094 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6095 return true; 6096 } else if (!ExpectedParent) { 6097 return true; 6098 } 6099 } 6100 } 6101 6102 return false; 6103 } 6104 6105 private: 6106 ASTContext &Context; 6107 FunctionDecl *OriginalFD; 6108 CXXRecordDecl *ExpectedParent; 6109 }; 6110 6111 } 6112 6113 /// \brief Generate diagnostics for an invalid function redeclaration. 6114 /// 6115 /// This routine handles generating the diagnostic messages for an invalid 6116 /// function redeclaration, including finding possible similar declarations 6117 /// or performing typo correction if there are no previous declarations with 6118 /// the same name. 6119 /// 6120 /// Returns a NamedDecl iff typo correction was performed and substituting in 6121 /// the new declaration name does not cause new errors. 6122 static NamedDecl *DiagnoseInvalidRedeclaration( 6123 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6124 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6125 DeclarationName Name = NewFD->getDeclName(); 6126 DeclContext *NewDC = NewFD->getDeclContext(); 6127 SmallVector<unsigned, 1> MismatchedParams; 6128 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6129 TypoCorrection Correction; 6130 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6131 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6132 : diag::err_member_decl_does_not_match; 6133 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6134 IsLocalFriend ? Sema::LookupLocalFriendName 6135 : Sema::LookupOrdinaryName, 6136 Sema::ForRedeclaration); 6137 6138 NewFD->setInvalidDecl(); 6139 if (IsLocalFriend) 6140 SemaRef.LookupName(Prev, S); 6141 else 6142 SemaRef.LookupQualifiedName(Prev, NewDC); 6143 assert(!Prev.isAmbiguous() && 6144 "Cannot have an ambiguity in previous-declaration lookup"); 6145 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6146 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6147 MD ? MD->getParent() : 0); 6148 if (!Prev.empty()) { 6149 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6150 Func != FuncEnd; ++Func) { 6151 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6152 if (FD && 6153 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6154 // Add 1 to the index so that 0 can mean the mismatch didn't 6155 // involve a parameter 6156 unsigned ParamNum = 6157 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6158 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6159 } 6160 } 6161 // If the qualified name lookup yielded nothing, try typo correction 6162 } else if ((Correction = SemaRef.CorrectTypo( 6163 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6164 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6165 Sema::CTK_ErrorRecovery, IsLocalFriend ? 0 : NewDC))) { 6166 // Set up everything for the call to ActOnFunctionDeclarator 6167 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6168 ExtraArgs.D.getIdentifierLoc()); 6169 Previous.clear(); 6170 Previous.setLookupName(Correction.getCorrection()); 6171 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6172 CDeclEnd = Correction.end(); 6173 CDecl != CDeclEnd; ++CDecl) { 6174 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6175 if (FD && !FD->hasBody() && 6176 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6177 Previous.addDecl(FD); 6178 } 6179 } 6180 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6181 6182 NamedDecl *Result; 6183 // Retry building the function declaration with the new previous 6184 // declarations, and with errors suppressed. 6185 { 6186 // Trap errors. 6187 Sema::SFINAETrap Trap(SemaRef); 6188 6189 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6190 // pieces need to verify the typo-corrected C++ declaration and hopefully 6191 // eliminate the need for the parameter pack ExtraArgs. 6192 Result = SemaRef.ActOnFunctionDeclarator( 6193 ExtraArgs.S, ExtraArgs.D, 6194 Correction.getCorrectionDecl()->getDeclContext(), 6195 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6196 ExtraArgs.AddToScope); 6197 6198 if (Trap.hasErrorOccurred()) 6199 Result = 0; 6200 } 6201 6202 if (Result) { 6203 // Determine which correction we picked. 6204 Decl *Canonical = Result->getCanonicalDecl(); 6205 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6206 I != E; ++I) 6207 if ((*I)->getCanonicalDecl() == Canonical) 6208 Correction.setCorrectionDecl(*I); 6209 6210 SemaRef.diagnoseTypo( 6211 Correction, 6212 SemaRef.PDiag(IsLocalFriend 6213 ? diag::err_no_matching_local_friend_suggest 6214 : diag::err_member_decl_does_not_match_suggest) 6215 << Name << NewDC << IsDefinition); 6216 return Result; 6217 } 6218 6219 // Pretend the typo correction never occurred 6220 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6221 ExtraArgs.D.getIdentifierLoc()); 6222 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6223 Previous.clear(); 6224 Previous.setLookupName(Name); 6225 } 6226 6227 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6228 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6229 6230 bool NewFDisConst = false; 6231 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6232 NewFDisConst = NewMD->isConst(); 6233 6234 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6235 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6236 NearMatch != NearMatchEnd; ++NearMatch) { 6237 FunctionDecl *FD = NearMatch->first; 6238 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6239 bool FDisConst = MD && MD->isConst(); 6240 bool IsMember = MD || !IsLocalFriend; 6241 6242 // FIXME: These notes are poorly worded for the local friend case. 6243 if (unsigned Idx = NearMatch->second) { 6244 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6245 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6246 if (Loc.isInvalid()) Loc = FD->getLocation(); 6247 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6248 : diag::note_local_decl_close_param_match) 6249 << Idx << FDParam->getType() 6250 << NewFD->getParamDecl(Idx - 1)->getType(); 6251 } else if (FDisConst != NewFDisConst) { 6252 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6253 << NewFDisConst << FD->getSourceRange().getEnd(); 6254 } else 6255 SemaRef.Diag(FD->getLocation(), 6256 IsMember ? diag::note_member_def_close_match 6257 : diag::note_local_decl_close_match); 6258 } 6259 return 0; 6260 } 6261 6262 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6263 Declarator &D) { 6264 switch (D.getDeclSpec().getStorageClassSpec()) { 6265 default: llvm_unreachable("Unknown storage class!"); 6266 case DeclSpec::SCS_auto: 6267 case DeclSpec::SCS_register: 6268 case DeclSpec::SCS_mutable: 6269 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6270 diag::err_typecheck_sclass_func); 6271 D.setInvalidType(); 6272 break; 6273 case DeclSpec::SCS_unspecified: break; 6274 case DeclSpec::SCS_extern: 6275 if (D.getDeclSpec().isExternInLinkageSpec()) 6276 return SC_None; 6277 return SC_Extern; 6278 case DeclSpec::SCS_static: { 6279 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6280 // C99 6.7.1p5: 6281 // The declaration of an identifier for a function that has 6282 // block scope shall have no explicit storage-class specifier 6283 // other than extern 6284 // See also (C++ [dcl.stc]p4). 6285 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6286 diag::err_static_block_func); 6287 break; 6288 } else 6289 return SC_Static; 6290 } 6291 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6292 } 6293 6294 // No explicit storage class has already been returned 6295 return SC_None; 6296 } 6297 6298 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6299 DeclContext *DC, QualType &R, 6300 TypeSourceInfo *TInfo, 6301 FunctionDecl::StorageClass SC, 6302 bool &IsVirtualOkay) { 6303 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6304 DeclarationName Name = NameInfo.getName(); 6305 6306 FunctionDecl *NewFD = 0; 6307 bool isInline = D.getDeclSpec().isInlineSpecified(); 6308 6309 if (!SemaRef.getLangOpts().CPlusPlus) { 6310 // Determine whether the function was written with a 6311 // prototype. This true when: 6312 // - there is a prototype in the declarator, or 6313 // - the type R of the function is some kind of typedef or other reference 6314 // to a type name (which eventually refers to a function type). 6315 bool HasPrototype = 6316 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6317 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6318 6319 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6320 D.getLocStart(), NameInfo, R, 6321 TInfo, SC, isInline, 6322 HasPrototype, false); 6323 if (D.isInvalidType()) 6324 NewFD->setInvalidDecl(); 6325 6326 // Set the lexical context. 6327 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6328 6329 return NewFD; 6330 } 6331 6332 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6333 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6334 6335 // Check that the return type is not an abstract class type. 6336 // For record types, this is done by the AbstractClassUsageDiagnoser once 6337 // the class has been completely parsed. 6338 if (!DC->isRecord() && 6339 SemaRef.RequireNonAbstractType( 6340 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6341 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6342 D.setInvalidType(); 6343 6344 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6345 // This is a C++ constructor declaration. 6346 assert(DC->isRecord() && 6347 "Constructors can only be declared in a member context"); 6348 6349 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6350 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6351 D.getLocStart(), NameInfo, 6352 R, TInfo, isExplicit, isInline, 6353 /*isImplicitlyDeclared=*/false, 6354 isConstexpr); 6355 6356 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6357 // This is a C++ destructor declaration. 6358 if (DC->isRecord()) { 6359 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6360 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6361 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6362 SemaRef.Context, Record, 6363 D.getLocStart(), 6364 NameInfo, R, TInfo, isInline, 6365 /*isImplicitlyDeclared=*/false); 6366 6367 // If the class is complete, then we now create the implicit exception 6368 // specification. If the class is incomplete or dependent, we can't do 6369 // it yet. 6370 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6371 Record->getDefinition() && !Record->isBeingDefined() && 6372 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6373 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6374 } 6375 6376 IsVirtualOkay = true; 6377 return NewDD; 6378 6379 } else { 6380 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6381 D.setInvalidType(); 6382 6383 // Create a FunctionDecl to satisfy the function definition parsing 6384 // code path. 6385 return FunctionDecl::Create(SemaRef.Context, DC, 6386 D.getLocStart(), 6387 D.getIdentifierLoc(), Name, R, TInfo, 6388 SC, isInline, 6389 /*hasPrototype=*/true, isConstexpr); 6390 } 6391 6392 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6393 if (!DC->isRecord()) { 6394 SemaRef.Diag(D.getIdentifierLoc(), 6395 diag::err_conv_function_not_member); 6396 return 0; 6397 } 6398 6399 SemaRef.CheckConversionDeclarator(D, R, SC); 6400 IsVirtualOkay = true; 6401 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6402 D.getLocStart(), NameInfo, 6403 R, TInfo, isInline, isExplicit, 6404 isConstexpr, SourceLocation()); 6405 6406 } else if (DC->isRecord()) { 6407 // If the name of the function is the same as the name of the record, 6408 // then this must be an invalid constructor that has a return type. 6409 // (The parser checks for a return type and makes the declarator a 6410 // constructor if it has no return type). 6411 if (Name.getAsIdentifierInfo() && 6412 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6413 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6414 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6415 << SourceRange(D.getIdentifierLoc()); 6416 return 0; 6417 } 6418 6419 // This is a C++ method declaration. 6420 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6421 cast<CXXRecordDecl>(DC), 6422 D.getLocStart(), NameInfo, R, 6423 TInfo, SC, isInline, 6424 isConstexpr, SourceLocation()); 6425 IsVirtualOkay = !Ret->isStatic(); 6426 return Ret; 6427 } else { 6428 // Determine whether the function was written with a 6429 // prototype. This true when: 6430 // - we're in C++ (where every function has a prototype), 6431 return FunctionDecl::Create(SemaRef.Context, DC, 6432 D.getLocStart(), 6433 NameInfo, R, TInfo, SC, isInline, 6434 true/*HasPrototype*/, isConstexpr); 6435 } 6436 } 6437 6438 enum OpenCLParamType { 6439 ValidKernelParam, 6440 PtrPtrKernelParam, 6441 PtrKernelParam, 6442 PrivatePtrKernelParam, 6443 InvalidKernelParam, 6444 RecordKernelParam 6445 }; 6446 6447 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6448 if (PT->isPointerType()) { 6449 QualType PointeeType = PT->getPointeeType(); 6450 if (PointeeType->isPointerType()) 6451 return PtrPtrKernelParam; 6452 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6453 : PtrKernelParam; 6454 } 6455 6456 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6457 // be used as builtin types. 6458 6459 if (PT->isImageType()) 6460 return PtrKernelParam; 6461 6462 if (PT->isBooleanType()) 6463 return InvalidKernelParam; 6464 6465 if (PT->isEventT()) 6466 return InvalidKernelParam; 6467 6468 if (PT->isHalfType()) 6469 return InvalidKernelParam; 6470 6471 if (PT->isRecordType()) 6472 return RecordKernelParam; 6473 6474 return ValidKernelParam; 6475 } 6476 6477 static void checkIsValidOpenCLKernelParameter( 6478 Sema &S, 6479 Declarator &D, 6480 ParmVarDecl *Param, 6481 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6482 QualType PT = Param->getType(); 6483 6484 // Cache the valid types we encounter to avoid rechecking structs that are 6485 // used again 6486 if (ValidTypes.count(PT.getTypePtr())) 6487 return; 6488 6489 switch (getOpenCLKernelParameterType(PT)) { 6490 case PtrPtrKernelParam: 6491 // OpenCL v1.2 s6.9.a: 6492 // A kernel function argument cannot be declared as a 6493 // pointer to a pointer type. 6494 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6495 D.setInvalidType(); 6496 return; 6497 6498 case PrivatePtrKernelParam: 6499 // OpenCL v1.2 s6.9.a: 6500 // A kernel function argument cannot be declared as a 6501 // pointer to the private address space. 6502 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6503 D.setInvalidType(); 6504 return; 6505 6506 // OpenCL v1.2 s6.9.k: 6507 // Arguments to kernel functions in a program cannot be declared with the 6508 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6509 // uintptr_t or a struct and/or union that contain fields declared to be 6510 // one of these built-in scalar types. 6511 6512 case InvalidKernelParam: 6513 // OpenCL v1.2 s6.8 n: 6514 // A kernel function argument cannot be declared 6515 // of event_t type. 6516 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6517 D.setInvalidType(); 6518 return; 6519 6520 case PtrKernelParam: 6521 case ValidKernelParam: 6522 ValidTypes.insert(PT.getTypePtr()); 6523 return; 6524 6525 case RecordKernelParam: 6526 break; 6527 } 6528 6529 // Track nested structs we will inspect 6530 SmallVector<const Decl *, 4> VisitStack; 6531 6532 // Track where we are in the nested structs. Items will migrate from 6533 // VisitStack to HistoryStack as we do the DFS for bad field. 6534 SmallVector<const FieldDecl *, 4> HistoryStack; 6535 HistoryStack.push_back((const FieldDecl *) 0); 6536 6537 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6538 VisitStack.push_back(PD); 6539 6540 assert(VisitStack.back() && "First decl null?"); 6541 6542 do { 6543 const Decl *Next = VisitStack.pop_back_val(); 6544 if (!Next) { 6545 assert(!HistoryStack.empty()); 6546 // Found a marker, we have gone up a level 6547 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6548 ValidTypes.insert(Hist->getType().getTypePtr()); 6549 6550 continue; 6551 } 6552 6553 // Adds everything except the original parameter declaration (which is not a 6554 // field itself) to the history stack. 6555 const RecordDecl *RD; 6556 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6557 HistoryStack.push_back(Field); 6558 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6559 } else { 6560 RD = cast<RecordDecl>(Next); 6561 } 6562 6563 // Add a null marker so we know when we've gone back up a level 6564 VisitStack.push_back((const Decl *) 0); 6565 6566 for (const auto *FD : RD->fields()) { 6567 QualType QT = FD->getType(); 6568 6569 if (ValidTypes.count(QT.getTypePtr())) 6570 continue; 6571 6572 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6573 if (ParamType == ValidKernelParam) 6574 continue; 6575 6576 if (ParamType == RecordKernelParam) { 6577 VisitStack.push_back(FD); 6578 continue; 6579 } 6580 6581 // OpenCL v1.2 s6.9.p: 6582 // Arguments to kernel functions that are declared to be a struct or union 6583 // do not allow OpenCL objects to be passed as elements of the struct or 6584 // union. 6585 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6586 ParamType == PrivatePtrKernelParam) { 6587 S.Diag(Param->getLocation(), 6588 diag::err_record_with_pointers_kernel_param) 6589 << PT->isUnionType() 6590 << PT; 6591 } else { 6592 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6593 } 6594 6595 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6596 << PD->getDeclName(); 6597 6598 // We have an error, now let's go back up through history and show where 6599 // the offending field came from 6600 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6601 E = HistoryStack.end(); I != E; ++I) { 6602 const FieldDecl *OuterField = *I; 6603 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6604 << OuterField->getType(); 6605 } 6606 6607 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6608 << QT->isPointerType() 6609 << QT; 6610 D.setInvalidType(); 6611 return; 6612 } 6613 } while (!VisitStack.empty()); 6614 } 6615 6616 NamedDecl* 6617 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6618 TypeSourceInfo *TInfo, LookupResult &Previous, 6619 MultiTemplateParamsArg TemplateParamLists, 6620 bool &AddToScope) { 6621 QualType R = TInfo->getType(); 6622 6623 assert(R.getTypePtr()->isFunctionType()); 6624 6625 // TODO: consider using NameInfo for diagnostic. 6626 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6627 DeclarationName Name = NameInfo.getName(); 6628 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6629 6630 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6631 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6632 diag::err_invalid_thread) 6633 << DeclSpec::getSpecifierName(TSCS); 6634 6635 if (D.isFirstDeclarationOfMember()) 6636 adjustMemberFunctionCC(R, D.isStaticMember()); 6637 6638 bool isFriend = false; 6639 FunctionTemplateDecl *FunctionTemplate = 0; 6640 bool isExplicitSpecialization = false; 6641 bool isFunctionTemplateSpecialization = false; 6642 6643 bool isDependentClassScopeExplicitSpecialization = false; 6644 bool HasExplicitTemplateArgs = false; 6645 TemplateArgumentListInfo TemplateArgs; 6646 6647 bool isVirtualOkay = false; 6648 6649 DeclContext *OriginalDC = DC; 6650 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6651 6652 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6653 isVirtualOkay); 6654 if (!NewFD) return 0; 6655 6656 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6657 NewFD->setTopLevelDeclInObjCContainer(); 6658 6659 // Set the lexical context. If this is a function-scope declaration, or has a 6660 // C++ scope specifier, or is the object of a friend declaration, the lexical 6661 // context will be different from the semantic context. 6662 NewFD->setLexicalDeclContext(CurContext); 6663 6664 if (IsLocalExternDecl) 6665 NewFD->setLocalExternDecl(); 6666 6667 if (getLangOpts().CPlusPlus) { 6668 bool isInline = D.getDeclSpec().isInlineSpecified(); 6669 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6670 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6671 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6672 isFriend = D.getDeclSpec().isFriendSpecified(); 6673 if (isFriend && !isInline && D.isFunctionDefinition()) { 6674 // C++ [class.friend]p5 6675 // A function can be defined in a friend declaration of a 6676 // class . . . . Such a function is implicitly inline. 6677 NewFD->setImplicitlyInline(); 6678 } 6679 6680 // If this is a method defined in an __interface, and is not a constructor 6681 // or an overloaded operator, then set the pure flag (isVirtual will already 6682 // return true). 6683 if (const CXXRecordDecl *Parent = 6684 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6685 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6686 NewFD->setPure(true); 6687 } 6688 6689 SetNestedNameSpecifier(NewFD, D); 6690 isExplicitSpecialization = false; 6691 isFunctionTemplateSpecialization = false; 6692 if (D.isInvalidType()) 6693 NewFD->setInvalidDecl(); 6694 6695 // Match up the template parameter lists with the scope specifier, then 6696 // determine whether we have a template or a template specialization. 6697 bool Invalid = false; 6698 if (TemplateParameterList *TemplateParams = 6699 MatchTemplateParametersToScopeSpecifier( 6700 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6701 D.getCXXScopeSpec(), 6702 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6703 ? D.getName().TemplateId 6704 : 0, 6705 TemplateParamLists, isFriend, isExplicitSpecialization, 6706 Invalid)) { 6707 if (TemplateParams->size() > 0) { 6708 // This is a function template 6709 6710 // Check that we can declare a template here. 6711 if (CheckTemplateDeclScope(S, TemplateParams)) 6712 return 0; 6713 6714 // A destructor cannot be a template. 6715 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6716 Diag(NewFD->getLocation(), diag::err_destructor_template); 6717 return 0; 6718 } 6719 6720 // If we're adding a template to a dependent context, we may need to 6721 // rebuilding some of the types used within the template parameter list, 6722 // now that we know what the current instantiation is. 6723 if (DC->isDependentContext()) { 6724 ContextRAII SavedContext(*this, DC); 6725 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6726 Invalid = true; 6727 } 6728 6729 6730 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6731 NewFD->getLocation(), 6732 Name, TemplateParams, 6733 NewFD); 6734 FunctionTemplate->setLexicalDeclContext(CurContext); 6735 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6736 6737 // For source fidelity, store the other template param lists. 6738 if (TemplateParamLists.size() > 1) { 6739 NewFD->setTemplateParameterListsInfo(Context, 6740 TemplateParamLists.size() - 1, 6741 TemplateParamLists.data()); 6742 } 6743 } else { 6744 // This is a function template specialization. 6745 isFunctionTemplateSpecialization = true; 6746 // For source fidelity, store all the template param lists. 6747 if (TemplateParamLists.size() > 0) 6748 NewFD->setTemplateParameterListsInfo(Context, 6749 TemplateParamLists.size(), 6750 TemplateParamLists.data()); 6751 6752 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6753 if (isFriend) { 6754 // We want to remove the "template<>", found here. 6755 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6756 6757 // If we remove the template<> and the name is not a 6758 // template-id, we're actually silently creating a problem: 6759 // the friend declaration will refer to an untemplated decl, 6760 // and clearly the user wants a template specialization. So 6761 // we need to insert '<>' after the name. 6762 SourceLocation InsertLoc; 6763 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6764 InsertLoc = D.getName().getSourceRange().getEnd(); 6765 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6766 } 6767 6768 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6769 << Name << RemoveRange 6770 << FixItHint::CreateRemoval(RemoveRange) 6771 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6772 } 6773 } 6774 } 6775 else { 6776 // All template param lists were matched against the scope specifier: 6777 // this is NOT (an explicit specialization of) a template. 6778 if (TemplateParamLists.size() > 0) 6779 // For source fidelity, store all the template param lists. 6780 NewFD->setTemplateParameterListsInfo(Context, 6781 TemplateParamLists.size(), 6782 TemplateParamLists.data()); 6783 } 6784 6785 if (Invalid) { 6786 NewFD->setInvalidDecl(); 6787 if (FunctionTemplate) 6788 FunctionTemplate->setInvalidDecl(); 6789 } 6790 6791 // C++ [dcl.fct.spec]p5: 6792 // The virtual specifier shall only be used in declarations of 6793 // nonstatic class member functions that appear within a 6794 // member-specification of a class declaration; see 10.3. 6795 // 6796 if (isVirtual && !NewFD->isInvalidDecl()) { 6797 if (!isVirtualOkay) { 6798 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6799 diag::err_virtual_non_function); 6800 } else if (!CurContext->isRecord()) { 6801 // 'virtual' was specified outside of the class. 6802 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6803 diag::err_virtual_out_of_class) 6804 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6805 } else if (NewFD->getDescribedFunctionTemplate()) { 6806 // C++ [temp.mem]p3: 6807 // A member function template shall not be virtual. 6808 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6809 diag::err_virtual_member_function_template) 6810 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6811 } else { 6812 // Okay: Add virtual to the method. 6813 NewFD->setVirtualAsWritten(true); 6814 } 6815 6816 if (getLangOpts().CPlusPlus1y && 6817 NewFD->getReturnType()->isUndeducedType()) 6818 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6819 } 6820 6821 if (getLangOpts().CPlusPlus1y && 6822 (NewFD->isDependentContext() || 6823 (isFriend && CurContext->isDependentContext())) && 6824 NewFD->getReturnType()->isUndeducedType()) { 6825 // If the function template is referenced directly (for instance, as a 6826 // member of the current instantiation), pretend it has a dependent type. 6827 // This is not really justified by the standard, but is the only sane 6828 // thing to do. 6829 // FIXME: For a friend function, we have not marked the function as being 6830 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6831 const FunctionProtoType *FPT = 6832 NewFD->getType()->castAs<FunctionProtoType>(); 6833 QualType Result = 6834 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6835 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6836 FPT->getExtProtoInfo())); 6837 } 6838 6839 // C++ [dcl.fct.spec]p3: 6840 // The inline specifier shall not appear on a block scope function 6841 // declaration. 6842 if (isInline && !NewFD->isInvalidDecl()) { 6843 if (CurContext->isFunctionOrMethod()) { 6844 // 'inline' is not allowed on block scope function declaration. 6845 Diag(D.getDeclSpec().getInlineSpecLoc(), 6846 diag::err_inline_declaration_block_scope) << Name 6847 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6848 } 6849 } 6850 6851 // C++ [dcl.fct.spec]p6: 6852 // The explicit specifier shall be used only in the declaration of a 6853 // constructor or conversion function within its class definition; 6854 // see 12.3.1 and 12.3.2. 6855 if (isExplicit && !NewFD->isInvalidDecl()) { 6856 if (!CurContext->isRecord()) { 6857 // 'explicit' was specified outside of the class. 6858 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6859 diag::err_explicit_out_of_class) 6860 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6861 } else if (!isa<CXXConstructorDecl>(NewFD) && 6862 !isa<CXXConversionDecl>(NewFD)) { 6863 // 'explicit' was specified on a function that wasn't a constructor 6864 // or conversion function. 6865 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6866 diag::err_explicit_non_ctor_or_conv_function) 6867 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6868 } 6869 } 6870 6871 if (isConstexpr) { 6872 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6873 // are implicitly inline. 6874 NewFD->setImplicitlyInline(); 6875 6876 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6877 // be either constructors or to return a literal type. Therefore, 6878 // destructors cannot be declared constexpr. 6879 if (isa<CXXDestructorDecl>(NewFD)) 6880 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6881 } 6882 6883 // If __module_private__ was specified, mark the function accordingly. 6884 if (D.getDeclSpec().isModulePrivateSpecified()) { 6885 if (isFunctionTemplateSpecialization) { 6886 SourceLocation ModulePrivateLoc 6887 = D.getDeclSpec().getModulePrivateSpecLoc(); 6888 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6889 << 0 6890 << FixItHint::CreateRemoval(ModulePrivateLoc); 6891 } else { 6892 NewFD->setModulePrivate(); 6893 if (FunctionTemplate) 6894 FunctionTemplate->setModulePrivate(); 6895 } 6896 } 6897 6898 if (isFriend) { 6899 if (FunctionTemplate) { 6900 FunctionTemplate->setObjectOfFriendDecl(); 6901 FunctionTemplate->setAccess(AS_public); 6902 } 6903 NewFD->setObjectOfFriendDecl(); 6904 NewFD->setAccess(AS_public); 6905 } 6906 6907 // If a function is defined as defaulted or deleted, mark it as such now. 6908 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6909 // definition kind to FDK_Definition. 6910 switch (D.getFunctionDefinitionKind()) { 6911 case FDK_Declaration: 6912 case FDK_Definition: 6913 break; 6914 6915 case FDK_Defaulted: 6916 NewFD->setDefaulted(); 6917 break; 6918 6919 case FDK_Deleted: 6920 NewFD->setDeletedAsWritten(); 6921 break; 6922 } 6923 6924 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6925 D.isFunctionDefinition()) { 6926 // C++ [class.mfct]p2: 6927 // A member function may be defined (8.4) in its class definition, in 6928 // which case it is an inline member function (7.1.2) 6929 NewFD->setImplicitlyInline(); 6930 } 6931 6932 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6933 !CurContext->isRecord()) { 6934 // C++ [class.static]p1: 6935 // A data or function member of a class may be declared static 6936 // in a class definition, in which case it is a static member of 6937 // the class. 6938 6939 // Complain about the 'static' specifier if it's on an out-of-line 6940 // member function definition. 6941 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6942 diag::err_static_out_of_line) 6943 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6944 } 6945 6946 // C++11 [except.spec]p15: 6947 // A deallocation function with no exception-specification is treated 6948 // as if it were specified with noexcept(true). 6949 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6950 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6951 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6952 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6953 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6954 EPI.ExceptionSpecType = EST_BasicNoexcept; 6955 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 6956 FPT->getParamTypes(), EPI)); 6957 } 6958 } 6959 6960 // Filter out previous declarations that don't match the scope. 6961 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6962 D.getCXXScopeSpec().isNotEmpty() || 6963 isExplicitSpecialization || 6964 isFunctionTemplateSpecialization); 6965 6966 // Handle GNU asm-label extension (encoded as an attribute). 6967 if (Expr *E = (Expr*) D.getAsmLabel()) { 6968 // The parser guarantees this is a string. 6969 StringLiteral *SE = cast<StringLiteral>(E); 6970 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6971 SE->getString(), 0)); 6972 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6973 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6974 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6975 if (I != ExtnameUndeclaredIdentifiers.end()) { 6976 NewFD->addAttr(I->second); 6977 ExtnameUndeclaredIdentifiers.erase(I); 6978 } 6979 } 6980 6981 // Copy the parameter declarations from the declarator D to the function 6982 // declaration NewFD, if they are available. First scavenge them into Params. 6983 SmallVector<ParmVarDecl*, 16> Params; 6984 if (D.isFunctionDeclarator()) { 6985 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6986 6987 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6988 // function that takes no arguments, not a function that takes a 6989 // single void argument. 6990 // We let through "const void" here because Sema::GetTypeForDeclarator 6991 // already checks for that case. 6992 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 && 6993 FTI.Params[0].Param && 6994 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) { 6995 // Empty arg list, don't push any params. 6996 } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) { 6997 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 6998 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 6999 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7000 Param->setDeclContext(NewFD); 7001 Params.push_back(Param); 7002 7003 if (Param->isInvalidDecl()) 7004 NewFD->setInvalidDecl(); 7005 } 7006 } 7007 7008 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7009 // When we're declaring a function with a typedef, typeof, etc as in the 7010 // following example, we'll need to synthesize (unnamed) 7011 // parameters for use in the declaration. 7012 // 7013 // @code 7014 // typedef void fn(int); 7015 // fn f; 7016 // @endcode 7017 7018 // Synthesize a parameter for each argument type. 7019 for (const auto &AI : FT->param_types()) { 7020 ParmVarDecl *Param = 7021 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7022 Param->setScopeInfo(0, Params.size()); 7023 Params.push_back(Param); 7024 } 7025 } else { 7026 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7027 "Should not need args for typedef of non-prototype fn"); 7028 } 7029 7030 // Finally, we know we have the right number of parameters, install them. 7031 NewFD->setParams(Params); 7032 7033 // Find all anonymous symbols defined during the declaration of this function 7034 // and add to NewFD. This lets us track decls such 'enum Y' in: 7035 // 7036 // void f(enum Y {AA} x) {} 7037 // 7038 // which would otherwise incorrectly end up in the translation unit scope. 7039 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7040 DeclsInPrototypeScope.clear(); 7041 7042 if (D.getDeclSpec().isNoreturnSpecified()) 7043 NewFD->addAttr( 7044 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7045 Context, 0)); 7046 7047 // Functions returning a variably modified type violate C99 6.7.5.2p2 7048 // because all functions have linkage. 7049 if (!NewFD->isInvalidDecl() && 7050 NewFD->getReturnType()->isVariablyModifiedType()) { 7051 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7052 NewFD->setInvalidDecl(); 7053 } 7054 7055 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7056 !NewFD->hasAttr<SectionAttr>()) { 7057 NewFD->addAttr( 7058 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7059 CodeSegStack.CurrentValue->getString(), 7060 CodeSegStack.CurrentPragmaLocation)); 7061 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7062 PSF_Implicit | PSF_Execute | PSF_Read, NewFD)) 7063 NewFD->dropAttr<SectionAttr>(); 7064 } 7065 7066 // Handle attributes. 7067 ProcessDeclAttributes(S, NewFD, D); 7068 7069 QualType RetType = NewFD->getReturnType(); 7070 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7071 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7072 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7073 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7074 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7075 // Attach WarnUnusedResult to functions returning types with that attribute. 7076 // Don't apply the attribute to that type's own non-static member functions 7077 // (to avoid warning on things like assignment operators) 7078 if (!MD || MD->getParent() != Ret) 7079 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7080 } 7081 7082 if (getLangOpts().OpenCL) { 7083 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7084 // type declaration will generate a compilation error. 7085 unsigned AddressSpace = RetType.getAddressSpace(); 7086 if (AddressSpace == LangAS::opencl_local || 7087 AddressSpace == LangAS::opencl_global || 7088 AddressSpace == LangAS::opencl_constant) { 7089 Diag(NewFD->getLocation(), 7090 diag::err_opencl_return_value_with_address_space); 7091 NewFD->setInvalidDecl(); 7092 } 7093 } 7094 7095 if (!getLangOpts().CPlusPlus) { 7096 // Perform semantic checking on the function declaration. 7097 bool isExplicitSpecialization=false; 7098 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7099 CheckMain(NewFD, D.getDeclSpec()); 7100 7101 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7102 CheckMSVCRTEntryPoint(NewFD); 7103 7104 if (!NewFD->isInvalidDecl()) 7105 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7106 isExplicitSpecialization)); 7107 else if (!Previous.empty()) 7108 // Make graceful recovery from an invalid redeclaration. 7109 D.setRedeclaration(true); 7110 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7111 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7112 "previous declaration set still overloaded"); 7113 } else { 7114 // C++11 [replacement.functions]p3: 7115 // The program's definitions shall not be specified as inline. 7116 // 7117 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7118 // 7119 // Suppress the diagnostic if the function is __attribute__((used)), since 7120 // that forces an external definition to be emitted. 7121 if (D.getDeclSpec().isInlineSpecified() && 7122 NewFD->isReplaceableGlobalAllocationFunction() && 7123 !NewFD->hasAttr<UsedAttr>()) 7124 Diag(D.getDeclSpec().getInlineSpecLoc(), 7125 diag::ext_operator_new_delete_declared_inline) 7126 << NewFD->getDeclName(); 7127 7128 // If the declarator is a template-id, translate the parser's template 7129 // argument list into our AST format. 7130 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7131 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7132 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7133 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7134 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7135 TemplateId->NumArgs); 7136 translateTemplateArguments(TemplateArgsPtr, 7137 TemplateArgs); 7138 7139 HasExplicitTemplateArgs = true; 7140 7141 if (NewFD->isInvalidDecl()) { 7142 HasExplicitTemplateArgs = false; 7143 } else if (FunctionTemplate) { 7144 // Function template with explicit template arguments. 7145 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7146 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7147 7148 HasExplicitTemplateArgs = false; 7149 } else { 7150 assert((isFunctionTemplateSpecialization || 7151 D.getDeclSpec().isFriendSpecified()) && 7152 "should have a 'template<>' for this decl"); 7153 // "friend void foo<>(int);" is an implicit specialization decl. 7154 isFunctionTemplateSpecialization = true; 7155 } 7156 } else if (isFriend && isFunctionTemplateSpecialization) { 7157 // This combination is only possible in a recovery case; the user 7158 // wrote something like: 7159 // template <> friend void foo(int); 7160 // which we're recovering from as if the user had written: 7161 // friend void foo<>(int); 7162 // Go ahead and fake up a template id. 7163 HasExplicitTemplateArgs = true; 7164 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7165 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7166 } 7167 7168 // If it's a friend (and only if it's a friend), it's possible 7169 // that either the specialized function type or the specialized 7170 // template is dependent, and therefore matching will fail. In 7171 // this case, don't check the specialization yet. 7172 bool InstantiationDependent = false; 7173 if (isFunctionTemplateSpecialization && isFriend && 7174 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7175 TemplateSpecializationType::anyDependentTemplateArguments( 7176 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7177 InstantiationDependent))) { 7178 assert(HasExplicitTemplateArgs && 7179 "friend function specialization without template args"); 7180 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7181 Previous)) 7182 NewFD->setInvalidDecl(); 7183 } else if (isFunctionTemplateSpecialization) { 7184 if (CurContext->isDependentContext() && CurContext->isRecord() 7185 && !isFriend) { 7186 isDependentClassScopeExplicitSpecialization = true; 7187 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7188 diag::ext_function_specialization_in_class : 7189 diag::err_function_specialization_in_class) 7190 << NewFD->getDeclName(); 7191 } else if (CheckFunctionTemplateSpecialization(NewFD, 7192 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7193 Previous)) 7194 NewFD->setInvalidDecl(); 7195 7196 // C++ [dcl.stc]p1: 7197 // A storage-class-specifier shall not be specified in an explicit 7198 // specialization (14.7.3) 7199 FunctionTemplateSpecializationInfo *Info = 7200 NewFD->getTemplateSpecializationInfo(); 7201 if (Info && SC != SC_None) { 7202 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7203 Diag(NewFD->getLocation(), 7204 diag::err_explicit_specialization_inconsistent_storage_class) 7205 << SC 7206 << FixItHint::CreateRemoval( 7207 D.getDeclSpec().getStorageClassSpecLoc()); 7208 7209 else 7210 Diag(NewFD->getLocation(), 7211 diag::ext_explicit_specialization_storage_class) 7212 << FixItHint::CreateRemoval( 7213 D.getDeclSpec().getStorageClassSpecLoc()); 7214 } 7215 7216 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7217 if (CheckMemberSpecialization(NewFD, Previous)) 7218 NewFD->setInvalidDecl(); 7219 } 7220 7221 // Perform semantic checking on the function declaration. 7222 if (!isDependentClassScopeExplicitSpecialization) { 7223 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7224 CheckMain(NewFD, D.getDeclSpec()); 7225 7226 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7227 CheckMSVCRTEntryPoint(NewFD); 7228 7229 if (!NewFD->isInvalidDecl()) 7230 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7231 isExplicitSpecialization)); 7232 } 7233 7234 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7235 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7236 "previous declaration set still overloaded"); 7237 7238 NamedDecl *PrincipalDecl = (FunctionTemplate 7239 ? cast<NamedDecl>(FunctionTemplate) 7240 : NewFD); 7241 7242 if (isFriend && D.isRedeclaration()) { 7243 AccessSpecifier Access = AS_public; 7244 if (!NewFD->isInvalidDecl()) 7245 Access = NewFD->getPreviousDecl()->getAccess(); 7246 7247 NewFD->setAccess(Access); 7248 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7249 } 7250 7251 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7252 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7253 PrincipalDecl->setNonMemberOperator(); 7254 7255 // If we have a function template, check the template parameter 7256 // list. This will check and merge default template arguments. 7257 if (FunctionTemplate) { 7258 FunctionTemplateDecl *PrevTemplate = 7259 FunctionTemplate->getPreviousDecl(); 7260 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7261 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7262 D.getDeclSpec().isFriendSpecified() 7263 ? (D.isFunctionDefinition() 7264 ? TPC_FriendFunctionTemplateDefinition 7265 : TPC_FriendFunctionTemplate) 7266 : (D.getCXXScopeSpec().isSet() && 7267 DC && DC->isRecord() && 7268 DC->isDependentContext()) 7269 ? TPC_ClassTemplateMember 7270 : TPC_FunctionTemplate); 7271 } 7272 7273 if (NewFD->isInvalidDecl()) { 7274 // Ignore all the rest of this. 7275 } else if (!D.isRedeclaration()) { 7276 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7277 AddToScope }; 7278 // Fake up an access specifier if it's supposed to be a class member. 7279 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7280 NewFD->setAccess(AS_public); 7281 7282 // Qualified decls generally require a previous declaration. 7283 if (D.getCXXScopeSpec().isSet()) { 7284 // ...with the major exception of templated-scope or 7285 // dependent-scope friend declarations. 7286 7287 // TODO: we currently also suppress this check in dependent 7288 // contexts because (1) the parameter depth will be off when 7289 // matching friend templates and (2) we might actually be 7290 // selecting a friend based on a dependent factor. But there 7291 // are situations where these conditions don't apply and we 7292 // can actually do this check immediately. 7293 if (isFriend && 7294 (TemplateParamLists.size() || 7295 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7296 CurContext->isDependentContext())) { 7297 // ignore these 7298 } else { 7299 // The user tried to provide an out-of-line definition for a 7300 // function that is a member of a class or namespace, but there 7301 // was no such member function declared (C++ [class.mfct]p2, 7302 // C++ [namespace.memdef]p2). For example: 7303 // 7304 // class X { 7305 // void f() const; 7306 // }; 7307 // 7308 // void X::f() { } // ill-formed 7309 // 7310 // Complain about this problem, and attempt to suggest close 7311 // matches (e.g., those that differ only in cv-qualifiers and 7312 // whether the parameter types are references). 7313 7314 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7315 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7316 AddToScope = ExtraArgs.AddToScope; 7317 return Result; 7318 } 7319 } 7320 7321 // Unqualified local friend declarations are required to resolve 7322 // to something. 7323 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7324 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7325 *this, Previous, NewFD, ExtraArgs, true, S)) { 7326 AddToScope = ExtraArgs.AddToScope; 7327 return Result; 7328 } 7329 } 7330 7331 } else if (!D.isFunctionDefinition() && 7332 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7333 !isFriend && !isFunctionTemplateSpecialization && 7334 !isExplicitSpecialization) { 7335 // An out-of-line member function declaration must also be a 7336 // definition (C++ [class.mfct]p2). 7337 // Note that this is not the case for explicit specializations of 7338 // function templates or member functions of class templates, per 7339 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7340 // extension for compatibility with old SWIG code which likes to 7341 // generate them. 7342 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7343 << D.getCXXScopeSpec().getRange(); 7344 } 7345 } 7346 7347 ProcessPragmaWeak(S, NewFD); 7348 checkAttributesAfterMerging(*this, *NewFD); 7349 7350 AddKnownFunctionAttributes(NewFD); 7351 7352 if (NewFD->hasAttr<OverloadableAttr>() && 7353 !NewFD->getType()->getAs<FunctionProtoType>()) { 7354 Diag(NewFD->getLocation(), 7355 diag::err_attribute_overloadable_no_prototype) 7356 << NewFD; 7357 7358 // Turn this into a variadic function with no parameters. 7359 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7360 FunctionProtoType::ExtProtoInfo EPI( 7361 Context.getDefaultCallingConvention(true, false)); 7362 EPI.Variadic = true; 7363 EPI.ExtInfo = FT->getExtInfo(); 7364 7365 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7366 NewFD->setType(R); 7367 } 7368 7369 // If there's a #pragma GCC visibility in scope, and this isn't a class 7370 // member, set the visibility of this function. 7371 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7372 AddPushedVisibilityAttribute(NewFD); 7373 7374 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7375 // marking the function. 7376 AddCFAuditedAttribute(NewFD); 7377 7378 // If this is the first declaration of an extern C variable, update 7379 // the map of such variables. 7380 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7381 isIncompleteDeclExternC(*this, NewFD)) 7382 RegisterLocallyScopedExternCDecl(NewFD, S); 7383 7384 // Set this FunctionDecl's range up to the right paren. 7385 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7386 7387 if (D.isRedeclaration() && !Previous.empty()) { 7388 checkDLLAttributeRedeclaration( 7389 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7390 isExplicitSpecialization || isFunctionTemplateSpecialization); 7391 } 7392 7393 if (getLangOpts().CPlusPlus) { 7394 if (FunctionTemplate) { 7395 if (NewFD->isInvalidDecl()) 7396 FunctionTemplate->setInvalidDecl(); 7397 return FunctionTemplate; 7398 } 7399 } 7400 7401 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7402 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7403 if ((getLangOpts().OpenCLVersion >= 120) 7404 && (SC == SC_Static)) { 7405 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7406 D.setInvalidType(); 7407 } 7408 7409 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7410 if (!NewFD->getReturnType()->isVoidType()) { 7411 Diag(D.getIdentifierLoc(), 7412 diag::err_expected_kernel_void_return_type); 7413 D.setInvalidType(); 7414 } 7415 7416 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7417 for (auto Param : NewFD->params()) 7418 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7419 } 7420 7421 MarkUnusedFileScopedDecl(NewFD); 7422 7423 if (getLangOpts().CUDA) 7424 if (IdentifierInfo *II = NewFD->getIdentifier()) 7425 if (!NewFD->isInvalidDecl() && 7426 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7427 if (II->isStr("cudaConfigureCall")) { 7428 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7429 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7430 7431 Context.setcudaConfigureCallDecl(NewFD); 7432 } 7433 } 7434 7435 // Here we have an function template explicit specialization at class scope. 7436 // The actually specialization will be postponed to template instatiation 7437 // time via the ClassScopeFunctionSpecializationDecl node. 7438 if (isDependentClassScopeExplicitSpecialization) { 7439 ClassScopeFunctionSpecializationDecl *NewSpec = 7440 ClassScopeFunctionSpecializationDecl::Create( 7441 Context, CurContext, SourceLocation(), 7442 cast<CXXMethodDecl>(NewFD), 7443 HasExplicitTemplateArgs, TemplateArgs); 7444 CurContext->addDecl(NewSpec); 7445 AddToScope = false; 7446 } 7447 7448 return NewFD; 7449 } 7450 7451 /// \brief Perform semantic checking of a new function declaration. 7452 /// 7453 /// Performs semantic analysis of the new function declaration 7454 /// NewFD. This routine performs all semantic checking that does not 7455 /// require the actual declarator involved in the declaration, and is 7456 /// used both for the declaration of functions as they are parsed 7457 /// (called via ActOnDeclarator) and for the declaration of functions 7458 /// that have been instantiated via C++ template instantiation (called 7459 /// via InstantiateDecl). 7460 /// 7461 /// \param IsExplicitSpecialization whether this new function declaration is 7462 /// an explicit specialization of the previous declaration. 7463 /// 7464 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7465 /// 7466 /// \returns true if the function declaration is a redeclaration. 7467 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7468 LookupResult &Previous, 7469 bool IsExplicitSpecialization) { 7470 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7471 "Variably modified return types are not handled here"); 7472 7473 // Determine whether the type of this function should be merged with 7474 // a previous visible declaration. This never happens for functions in C++, 7475 // and always happens in C if the previous declaration was visible. 7476 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7477 !Previous.isShadowed(); 7478 7479 // Filter out any non-conflicting previous declarations. 7480 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7481 7482 bool Redeclaration = false; 7483 NamedDecl *OldDecl = 0; 7484 7485 // Merge or overload the declaration with an existing declaration of 7486 // the same name, if appropriate. 7487 if (!Previous.empty()) { 7488 // Determine whether NewFD is an overload of PrevDecl or 7489 // a declaration that requires merging. If it's an overload, 7490 // there's no more work to do here; we'll just add the new 7491 // function to the scope. 7492 if (!AllowOverloadingOfFunction(Previous, Context)) { 7493 NamedDecl *Candidate = Previous.getFoundDecl(); 7494 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7495 Redeclaration = true; 7496 OldDecl = Candidate; 7497 } 7498 } else { 7499 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7500 /*NewIsUsingDecl*/ false)) { 7501 case Ovl_Match: 7502 Redeclaration = true; 7503 break; 7504 7505 case Ovl_NonFunction: 7506 Redeclaration = true; 7507 break; 7508 7509 case Ovl_Overload: 7510 Redeclaration = false; 7511 break; 7512 } 7513 7514 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7515 // If a function name is overloadable in C, then every function 7516 // with that name must be marked "overloadable". 7517 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7518 << Redeclaration << NewFD; 7519 NamedDecl *OverloadedDecl = 0; 7520 if (Redeclaration) 7521 OverloadedDecl = OldDecl; 7522 else if (!Previous.empty()) 7523 OverloadedDecl = Previous.getRepresentativeDecl(); 7524 if (OverloadedDecl) 7525 Diag(OverloadedDecl->getLocation(), 7526 diag::note_attribute_overloadable_prev_overload); 7527 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7528 } 7529 } 7530 } 7531 7532 // Check for a previous extern "C" declaration with this name. 7533 if (!Redeclaration && 7534 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7535 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7536 if (!Previous.empty()) { 7537 // This is an extern "C" declaration with the same name as a previous 7538 // declaration, and thus redeclares that entity... 7539 Redeclaration = true; 7540 OldDecl = Previous.getFoundDecl(); 7541 MergeTypeWithPrevious = false; 7542 7543 // ... except in the presence of __attribute__((overloadable)). 7544 if (OldDecl->hasAttr<OverloadableAttr>()) { 7545 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7546 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7547 << Redeclaration << NewFD; 7548 Diag(Previous.getFoundDecl()->getLocation(), 7549 diag::note_attribute_overloadable_prev_overload); 7550 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7551 } 7552 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7553 Redeclaration = false; 7554 OldDecl = 0; 7555 } 7556 } 7557 } 7558 } 7559 7560 // C++11 [dcl.constexpr]p8: 7561 // A constexpr specifier for a non-static member function that is not 7562 // a constructor declares that member function to be const. 7563 // 7564 // This needs to be delayed until we know whether this is an out-of-line 7565 // definition of a static member function. 7566 // 7567 // This rule is not present in C++1y, so we produce a backwards 7568 // compatibility warning whenever it happens in C++11. 7569 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7570 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7571 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7572 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7573 CXXMethodDecl *OldMD = 0; 7574 if (OldDecl) 7575 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7576 if (!OldMD || !OldMD->isStatic()) { 7577 const FunctionProtoType *FPT = 7578 MD->getType()->castAs<FunctionProtoType>(); 7579 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7580 EPI.TypeQuals |= Qualifiers::Const; 7581 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7582 FPT->getParamTypes(), EPI)); 7583 7584 // Warn that we did this, if we're not performing template instantiation. 7585 // In that case, we'll have warned already when the template was defined. 7586 if (ActiveTemplateInstantiations.empty()) { 7587 SourceLocation AddConstLoc; 7588 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7589 .IgnoreParens().getAs<FunctionTypeLoc>()) 7590 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7591 7592 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7593 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7594 } 7595 } 7596 } 7597 7598 if (Redeclaration) { 7599 // NewFD and OldDecl represent declarations that need to be 7600 // merged. 7601 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7602 NewFD->setInvalidDecl(); 7603 return Redeclaration; 7604 } 7605 7606 Previous.clear(); 7607 Previous.addDecl(OldDecl); 7608 7609 if (FunctionTemplateDecl *OldTemplateDecl 7610 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7611 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7612 FunctionTemplateDecl *NewTemplateDecl 7613 = NewFD->getDescribedFunctionTemplate(); 7614 assert(NewTemplateDecl && "Template/non-template mismatch"); 7615 if (CXXMethodDecl *Method 7616 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7617 Method->setAccess(OldTemplateDecl->getAccess()); 7618 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7619 } 7620 7621 // If this is an explicit specialization of a member that is a function 7622 // template, mark it as a member specialization. 7623 if (IsExplicitSpecialization && 7624 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7625 NewTemplateDecl->setMemberSpecialization(); 7626 assert(OldTemplateDecl->isMemberSpecialization()); 7627 } 7628 7629 } else { 7630 // This needs to happen first so that 'inline' propagates. 7631 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7632 7633 if (isa<CXXMethodDecl>(NewFD)) { 7634 // A valid redeclaration of a C++ method must be out-of-line, 7635 // but (unfortunately) it's not necessarily a definition 7636 // because of templates, which means that the previous 7637 // declaration is not necessarily from the class definition. 7638 7639 // For just setting the access, that doesn't matter. 7640 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7641 NewFD->setAccess(oldMethod->getAccess()); 7642 7643 // Update the key-function state if necessary for this ABI. 7644 if (NewFD->isInlined() && 7645 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7646 // setNonKeyFunction needs to work with the original 7647 // declaration from the class definition, and isVirtual() is 7648 // just faster in that case, so map back to that now. 7649 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7650 if (oldMethod->isVirtual()) { 7651 Context.setNonKeyFunction(oldMethod); 7652 } 7653 } 7654 } 7655 } 7656 } 7657 7658 // Semantic checking for this function declaration (in isolation). 7659 if (getLangOpts().CPlusPlus) { 7660 // C++-specific checks. 7661 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7662 CheckConstructor(Constructor); 7663 } else if (CXXDestructorDecl *Destructor = 7664 dyn_cast<CXXDestructorDecl>(NewFD)) { 7665 CXXRecordDecl *Record = Destructor->getParent(); 7666 QualType ClassType = Context.getTypeDeclType(Record); 7667 7668 // FIXME: Shouldn't we be able to perform this check even when the class 7669 // type is dependent? Both gcc and edg can handle that. 7670 if (!ClassType->isDependentType()) { 7671 DeclarationName Name 7672 = Context.DeclarationNames.getCXXDestructorName( 7673 Context.getCanonicalType(ClassType)); 7674 if (NewFD->getDeclName() != Name) { 7675 Diag(NewFD->getLocation(), diag::err_destructor_name); 7676 NewFD->setInvalidDecl(); 7677 return Redeclaration; 7678 } 7679 } 7680 } else if (CXXConversionDecl *Conversion 7681 = dyn_cast<CXXConversionDecl>(NewFD)) { 7682 ActOnConversionDeclarator(Conversion); 7683 } 7684 7685 // Find any virtual functions that this function overrides. 7686 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7687 if (!Method->isFunctionTemplateSpecialization() && 7688 !Method->getDescribedFunctionTemplate() && 7689 Method->isCanonicalDecl()) { 7690 if (AddOverriddenMethods(Method->getParent(), Method)) { 7691 // If the function was marked as "static", we have a problem. 7692 if (NewFD->getStorageClass() == SC_Static) { 7693 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7694 } 7695 } 7696 } 7697 7698 if (Method->isStatic()) 7699 checkThisInStaticMemberFunctionType(Method); 7700 } 7701 7702 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7703 if (NewFD->isOverloadedOperator() && 7704 CheckOverloadedOperatorDeclaration(NewFD)) { 7705 NewFD->setInvalidDecl(); 7706 return Redeclaration; 7707 } 7708 7709 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7710 if (NewFD->getLiteralIdentifier() && 7711 CheckLiteralOperatorDeclaration(NewFD)) { 7712 NewFD->setInvalidDecl(); 7713 return Redeclaration; 7714 } 7715 7716 // In C++, check default arguments now that we have merged decls. Unless 7717 // the lexical context is the class, because in this case this is done 7718 // during delayed parsing anyway. 7719 if (!CurContext->isRecord()) 7720 CheckCXXDefaultArguments(NewFD); 7721 7722 // If this function declares a builtin function, check the type of this 7723 // declaration against the expected type for the builtin. 7724 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7725 ASTContext::GetBuiltinTypeError Error; 7726 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7727 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7728 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7729 // The type of this function differs from the type of the builtin, 7730 // so forget about the builtin entirely. 7731 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7732 } 7733 } 7734 7735 // If this function is declared as being extern "C", then check to see if 7736 // the function returns a UDT (class, struct, or union type) that is not C 7737 // compatible, and if it does, warn the user. 7738 // But, issue any diagnostic on the first declaration only. 7739 if (NewFD->isExternC() && Previous.empty()) { 7740 QualType R = NewFD->getReturnType(); 7741 if (R->isIncompleteType() && !R->isVoidType()) 7742 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7743 << NewFD << R; 7744 else if (!R.isPODType(Context) && !R->isVoidType() && 7745 !R->isObjCObjectPointerType()) 7746 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7747 } 7748 } 7749 return Redeclaration; 7750 } 7751 7752 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7753 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7754 if (!TSI) 7755 return SourceRange(); 7756 7757 TypeLoc TL = TSI->getTypeLoc(); 7758 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7759 if (!FunctionTL) 7760 return SourceRange(); 7761 7762 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7763 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7764 return ResultTL.getSourceRange(); 7765 7766 return SourceRange(); 7767 } 7768 7769 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7770 // C++11 [basic.start.main]p3: 7771 // A program that [...] declares main to be inline, static or 7772 // constexpr is ill-formed. 7773 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7774 // appear in a declaration of main. 7775 // static main is not an error under C99, but we should warn about it. 7776 // We accept _Noreturn main as an extension. 7777 if (FD->getStorageClass() == SC_Static) 7778 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7779 ? diag::err_static_main : diag::warn_static_main) 7780 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7781 if (FD->isInlineSpecified()) 7782 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7783 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7784 if (DS.isNoreturnSpecified()) { 7785 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7786 SourceRange NoreturnRange(NoreturnLoc, 7787 PP.getLocForEndOfToken(NoreturnLoc)); 7788 Diag(NoreturnLoc, diag::ext_noreturn_main); 7789 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7790 << FixItHint::CreateRemoval(NoreturnRange); 7791 } 7792 if (FD->isConstexpr()) { 7793 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7794 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7795 FD->setConstexpr(false); 7796 } 7797 7798 if (getLangOpts().OpenCL) { 7799 Diag(FD->getLocation(), diag::err_opencl_no_main) 7800 << FD->hasAttr<OpenCLKernelAttr>(); 7801 FD->setInvalidDecl(); 7802 return; 7803 } 7804 7805 QualType T = FD->getType(); 7806 assert(T->isFunctionType() && "function decl is not of function type"); 7807 const FunctionType* FT = T->castAs<FunctionType>(); 7808 7809 // All the standards say that main() should should return 'int'. 7810 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7811 // In C and C++, main magically returns 0 if you fall off the end; 7812 // set the flag which tells us that. 7813 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7814 FD->setHasImplicitReturnZero(true); 7815 7816 // In C with GNU extensions we allow main() to have non-integer return 7817 // type, but we should warn about the extension, and we disable the 7818 // implicit-return-zero rule. 7819 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7820 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7821 7822 SourceRange ResultRange = getResultSourceRange(FD); 7823 if (ResultRange.isValid()) 7824 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7825 << FixItHint::CreateReplacement(ResultRange, "int"); 7826 7827 // Otherwise, this is just a flat-out error. 7828 } else { 7829 SourceRange ResultRange = getResultSourceRange(FD); 7830 if (ResultRange.isValid()) 7831 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7832 << FixItHint::CreateReplacement(ResultRange, "int"); 7833 else 7834 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7835 7836 FD->setInvalidDecl(true); 7837 } 7838 7839 // Treat protoless main() as nullary. 7840 if (isa<FunctionNoProtoType>(FT)) return; 7841 7842 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7843 unsigned nparams = FTP->getNumParams(); 7844 assert(FD->getNumParams() == nparams); 7845 7846 bool HasExtraParameters = (nparams > 3); 7847 7848 // Darwin passes an undocumented fourth argument of type char**. If 7849 // other platforms start sprouting these, the logic below will start 7850 // getting shifty. 7851 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7852 HasExtraParameters = false; 7853 7854 if (HasExtraParameters) { 7855 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7856 FD->setInvalidDecl(true); 7857 nparams = 3; 7858 } 7859 7860 // FIXME: a lot of the following diagnostics would be improved 7861 // if we had some location information about types. 7862 7863 QualType CharPP = 7864 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7865 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7866 7867 for (unsigned i = 0; i < nparams; ++i) { 7868 QualType AT = FTP->getParamType(i); 7869 7870 bool mismatch = true; 7871 7872 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7873 mismatch = false; 7874 else if (Expected[i] == CharPP) { 7875 // As an extension, the following forms are okay: 7876 // char const ** 7877 // char const * const * 7878 // char * const * 7879 7880 QualifierCollector qs; 7881 const PointerType* PT; 7882 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7883 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7884 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7885 Context.CharTy)) { 7886 qs.removeConst(); 7887 mismatch = !qs.empty(); 7888 } 7889 } 7890 7891 if (mismatch) { 7892 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7893 // TODO: suggest replacing given type with expected type 7894 FD->setInvalidDecl(true); 7895 } 7896 } 7897 7898 if (nparams == 1 && !FD->isInvalidDecl()) { 7899 Diag(FD->getLocation(), diag::warn_main_one_arg); 7900 } 7901 7902 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7903 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7904 FD->setInvalidDecl(); 7905 } 7906 } 7907 7908 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7909 QualType T = FD->getType(); 7910 assert(T->isFunctionType() && "function decl is not of function type"); 7911 const FunctionType *FT = T->castAs<FunctionType>(); 7912 7913 // Set an implicit return of 'zero' if the function can return some integral, 7914 // enumeration, pointer or nullptr type. 7915 if (FT->getReturnType()->isIntegralOrEnumerationType() || 7916 FT->getReturnType()->isAnyPointerType() || 7917 FT->getReturnType()->isNullPtrType()) 7918 // DllMain is exempt because a return value of zero means it failed. 7919 if (FD->getName() != "DllMain") 7920 FD->setHasImplicitReturnZero(true); 7921 7922 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7923 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7924 FD->setInvalidDecl(); 7925 } 7926 } 7927 7928 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7929 // FIXME: Need strict checking. In C89, we need to check for 7930 // any assignment, increment, decrement, function-calls, or 7931 // commas outside of a sizeof. In C99, it's the same list, 7932 // except that the aforementioned are allowed in unevaluated 7933 // expressions. Everything else falls under the 7934 // "may accept other forms of constant expressions" exception. 7935 // (We never end up here for C++, so the constant expression 7936 // rules there don't matter.) 7937 if (Init->isConstantInitializer(Context, false)) 7938 return false; 7939 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7940 << Init->getSourceRange(); 7941 return true; 7942 } 7943 7944 namespace { 7945 // Visits an initialization expression to see if OrigDecl is evaluated in 7946 // its own initialization and throws a warning if it does. 7947 class SelfReferenceChecker 7948 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7949 Sema &S; 7950 Decl *OrigDecl; 7951 bool isRecordType; 7952 bool isPODType; 7953 bool isReferenceType; 7954 7955 public: 7956 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7957 7958 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7959 S(S), OrigDecl(OrigDecl) { 7960 isPODType = false; 7961 isRecordType = false; 7962 isReferenceType = false; 7963 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7964 isPODType = VD->getType().isPODType(S.Context); 7965 isRecordType = VD->getType()->isRecordType(); 7966 isReferenceType = VD->getType()->isReferenceType(); 7967 } 7968 } 7969 7970 // For most expressions, the cast is directly above the DeclRefExpr. 7971 // For conditional operators, the cast can be outside the conditional 7972 // operator if both expressions are DeclRefExpr's. 7973 void HandleValue(Expr *E) { 7974 if (isReferenceType) 7975 return; 7976 E = E->IgnoreParenImpCasts(); 7977 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7978 HandleDeclRefExpr(DRE); 7979 return; 7980 } 7981 7982 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7983 HandleValue(CO->getTrueExpr()); 7984 HandleValue(CO->getFalseExpr()); 7985 return; 7986 } 7987 7988 if (isa<MemberExpr>(E)) { 7989 Expr *Base = E->IgnoreParenImpCasts(); 7990 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7991 // Check for static member variables and don't warn on them. 7992 if (!isa<FieldDecl>(ME->getMemberDecl())) 7993 return; 7994 Base = ME->getBase()->IgnoreParenImpCasts(); 7995 } 7996 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7997 HandleDeclRefExpr(DRE); 7998 return; 7999 } 8000 } 8001 8002 // Reference types are handled here since all uses of references are 8003 // bad, not just r-value uses. 8004 void VisitDeclRefExpr(DeclRefExpr *E) { 8005 if (isReferenceType) 8006 HandleDeclRefExpr(E); 8007 } 8008 8009 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8010 if (E->getCastKind() == CK_LValueToRValue || 8011 (isRecordType && E->getCastKind() == CK_NoOp)) 8012 HandleValue(E->getSubExpr()); 8013 8014 Inherited::VisitImplicitCastExpr(E); 8015 } 8016 8017 void VisitMemberExpr(MemberExpr *E) { 8018 // Don't warn on arrays since they can be treated as pointers. 8019 if (E->getType()->canDecayToPointerType()) return; 8020 8021 // Warn when a non-static method call is followed by non-static member 8022 // field accesses, which is followed by a DeclRefExpr. 8023 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8024 bool Warn = (MD && !MD->isStatic()); 8025 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8026 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8027 if (!isa<FieldDecl>(ME->getMemberDecl())) 8028 Warn = false; 8029 Base = ME->getBase()->IgnoreParenImpCasts(); 8030 } 8031 8032 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8033 if (Warn) 8034 HandleDeclRefExpr(DRE); 8035 return; 8036 } 8037 8038 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8039 // Visit that expression. 8040 Visit(Base); 8041 } 8042 8043 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8044 if (E->getNumArgs() > 0) 8045 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 8046 HandleDeclRefExpr(DRE); 8047 8048 Inherited::VisitCXXOperatorCallExpr(E); 8049 } 8050 8051 void VisitUnaryOperator(UnaryOperator *E) { 8052 // For POD record types, addresses of its own members are well-defined. 8053 if (E->getOpcode() == UO_AddrOf && isRecordType && 8054 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8055 if (!isPODType) 8056 HandleValue(E->getSubExpr()); 8057 return; 8058 } 8059 Inherited::VisitUnaryOperator(E); 8060 } 8061 8062 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8063 8064 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8065 Decl* ReferenceDecl = DRE->getDecl(); 8066 if (OrigDecl != ReferenceDecl) return; 8067 unsigned diag; 8068 if (isReferenceType) { 8069 diag = diag::warn_uninit_self_reference_in_reference_init; 8070 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8071 diag = diag::warn_static_self_reference_in_init; 8072 } else { 8073 diag = diag::warn_uninit_self_reference_in_init; 8074 } 8075 8076 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8077 S.PDiag(diag) 8078 << DRE->getNameInfo().getName() 8079 << OrigDecl->getLocation() 8080 << DRE->getSourceRange()); 8081 } 8082 }; 8083 8084 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8085 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8086 bool DirectInit) { 8087 // Parameters arguments are occassionially constructed with itself, 8088 // for instance, in recursive functions. Skip them. 8089 if (isa<ParmVarDecl>(OrigDecl)) 8090 return; 8091 8092 E = E->IgnoreParens(); 8093 8094 // Skip checking T a = a where T is not a record or reference type. 8095 // Doing so is a way to silence uninitialized warnings. 8096 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8097 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8098 if (ICE->getCastKind() == CK_LValueToRValue) 8099 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8100 if (DRE->getDecl() == OrigDecl) 8101 return; 8102 8103 SelfReferenceChecker(S, OrigDecl).Visit(E); 8104 } 8105 } 8106 8107 /// AddInitializerToDecl - Adds the initializer Init to the 8108 /// declaration dcl. If DirectInit is true, this is C++ direct 8109 /// initialization rather than copy initialization. 8110 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8111 bool DirectInit, bool TypeMayContainAuto) { 8112 // If there is no declaration, there was an error parsing it. Just ignore 8113 // the initializer. 8114 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8115 return; 8116 8117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8118 // With declarators parsed the way they are, the parser cannot 8119 // distinguish between a normal initializer and a pure-specifier. 8120 // Thus this grotesque test. 8121 IntegerLiteral *IL; 8122 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8123 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8124 CheckPureMethod(Method, Init->getSourceRange()); 8125 else { 8126 Diag(Method->getLocation(), diag::err_member_function_initialization) 8127 << Method->getDeclName() << Init->getSourceRange(); 8128 Method->setInvalidDecl(); 8129 } 8130 return; 8131 } 8132 8133 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8134 if (!VDecl) { 8135 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8136 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8137 RealDecl->setInvalidDecl(); 8138 return; 8139 } 8140 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8141 8142 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8143 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8144 Expr *DeduceInit = Init; 8145 // Initializer could be a C++ direct-initializer. Deduction only works if it 8146 // contains exactly one expression. 8147 if (CXXDirectInit) { 8148 if (CXXDirectInit->getNumExprs() == 0) { 8149 // It isn't possible to write this directly, but it is possible to 8150 // end up in this situation with "auto x(some_pack...);" 8151 Diag(CXXDirectInit->getLocStart(), 8152 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8153 : diag::err_auto_var_init_no_expression) 8154 << VDecl->getDeclName() << VDecl->getType() 8155 << VDecl->getSourceRange(); 8156 RealDecl->setInvalidDecl(); 8157 return; 8158 } else if (CXXDirectInit->getNumExprs() > 1) { 8159 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8160 VDecl->isInitCapture() 8161 ? diag::err_init_capture_multiple_expressions 8162 : diag::err_auto_var_init_multiple_expressions) 8163 << VDecl->getDeclName() << VDecl->getType() 8164 << VDecl->getSourceRange(); 8165 RealDecl->setInvalidDecl(); 8166 return; 8167 } else { 8168 DeduceInit = CXXDirectInit->getExpr(0); 8169 if (isa<InitListExpr>(DeduceInit)) 8170 Diag(CXXDirectInit->getLocStart(), 8171 diag::err_auto_var_init_paren_braces) 8172 << VDecl->getDeclName() << VDecl->getType() 8173 << VDecl->getSourceRange(); 8174 } 8175 } 8176 8177 // Expressions default to 'id' when we're in a debugger. 8178 bool DefaultedToAuto = false; 8179 if (getLangOpts().DebuggerCastResultToId && 8180 Init->getType() == Context.UnknownAnyTy) { 8181 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8182 if (Result.isInvalid()) { 8183 VDecl->setInvalidDecl(); 8184 return; 8185 } 8186 Init = Result.take(); 8187 DefaultedToAuto = true; 8188 } 8189 8190 QualType DeducedType; 8191 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8192 DAR_Failed) 8193 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8194 if (DeducedType.isNull()) { 8195 RealDecl->setInvalidDecl(); 8196 return; 8197 } 8198 VDecl->setType(DeducedType); 8199 assert(VDecl->isLinkageValid()); 8200 8201 // In ARC, infer lifetime. 8202 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8203 VDecl->setInvalidDecl(); 8204 8205 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8206 // 'id' instead of a specific object type prevents most of our usual checks. 8207 // We only want to warn outside of template instantiations, though: 8208 // inside a template, the 'id' could have come from a parameter. 8209 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8210 DeducedType->isObjCIdType()) { 8211 SourceLocation Loc = 8212 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8213 Diag(Loc, diag::warn_auto_var_is_id) 8214 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8215 } 8216 8217 // If this is a redeclaration, check that the type we just deduced matches 8218 // the previously declared type. 8219 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8220 // We never need to merge the type, because we cannot form an incomplete 8221 // array of auto, nor deduce such a type. 8222 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8223 } 8224 8225 // Check the deduced type is valid for a variable declaration. 8226 CheckVariableDeclarationType(VDecl); 8227 if (VDecl->isInvalidDecl()) 8228 return; 8229 } 8230 8231 // dllimport cannot be used on variable definitions. 8232 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8233 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8234 VDecl->setInvalidDecl(); 8235 return; 8236 } 8237 8238 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8239 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8240 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8241 VDecl->setInvalidDecl(); 8242 return; 8243 } 8244 8245 if (!VDecl->getType()->isDependentType()) { 8246 // A definition must end up with a complete type, which means it must be 8247 // complete with the restriction that an array type might be completed by 8248 // the initializer; note that later code assumes this restriction. 8249 QualType BaseDeclType = VDecl->getType(); 8250 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8251 BaseDeclType = Array->getElementType(); 8252 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8253 diag::err_typecheck_decl_incomplete_type)) { 8254 RealDecl->setInvalidDecl(); 8255 return; 8256 } 8257 8258 // The variable can not have an abstract class type. 8259 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8260 diag::err_abstract_type_in_decl, 8261 AbstractVariableType)) 8262 VDecl->setInvalidDecl(); 8263 } 8264 8265 const VarDecl *Def; 8266 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8267 Diag(VDecl->getLocation(), diag::err_redefinition) 8268 << VDecl->getDeclName(); 8269 Diag(Def->getLocation(), diag::note_previous_definition); 8270 VDecl->setInvalidDecl(); 8271 return; 8272 } 8273 8274 const VarDecl* PrevInit = 0; 8275 if (getLangOpts().CPlusPlus) { 8276 // C++ [class.static.data]p4 8277 // If a static data member is of const integral or const 8278 // enumeration type, its declaration in the class definition can 8279 // specify a constant-initializer which shall be an integral 8280 // constant expression (5.19). In that case, the member can appear 8281 // in integral constant expressions. The member shall still be 8282 // defined in a namespace scope if it is used in the program and the 8283 // namespace scope definition shall not contain an initializer. 8284 // 8285 // We already performed a redefinition check above, but for static 8286 // data members we also need to check whether there was an in-class 8287 // declaration with an initializer. 8288 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8289 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8290 << VDecl->getDeclName(); 8291 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8292 return; 8293 } 8294 8295 if (VDecl->hasLocalStorage()) 8296 getCurFunction()->setHasBranchProtectedScope(); 8297 8298 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8299 VDecl->setInvalidDecl(); 8300 return; 8301 } 8302 } 8303 8304 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8305 // a kernel function cannot be initialized." 8306 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8307 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8308 VDecl->setInvalidDecl(); 8309 return; 8310 } 8311 8312 // Get the decls type and save a reference for later, since 8313 // CheckInitializerTypes may change it. 8314 QualType DclT = VDecl->getType(), SavT = DclT; 8315 8316 // Expressions default to 'id' when we're in a debugger 8317 // and we are assigning it to a variable of Objective-C pointer type. 8318 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8319 Init->getType() == Context.UnknownAnyTy) { 8320 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8321 if (Result.isInvalid()) { 8322 VDecl->setInvalidDecl(); 8323 return; 8324 } 8325 Init = Result.take(); 8326 } 8327 8328 // Perform the initialization. 8329 if (!VDecl->isInvalidDecl()) { 8330 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8331 InitializationKind Kind 8332 = DirectInit ? 8333 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8334 Init->getLocStart(), 8335 Init->getLocEnd()) 8336 : InitializationKind::CreateDirectList( 8337 VDecl->getLocation()) 8338 : InitializationKind::CreateCopy(VDecl->getLocation(), 8339 Init->getLocStart()); 8340 8341 MultiExprArg Args = Init; 8342 if (CXXDirectInit) 8343 Args = MultiExprArg(CXXDirectInit->getExprs(), 8344 CXXDirectInit->getNumExprs()); 8345 8346 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8347 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8348 if (Result.isInvalid()) { 8349 VDecl->setInvalidDecl(); 8350 return; 8351 } 8352 8353 Init = Result.takeAs<Expr>(); 8354 } 8355 8356 // Check for self-references within variable initializers. 8357 // Variables declared within a function/method body (except for references) 8358 // are handled by a dataflow analysis. 8359 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8360 VDecl->getType()->isReferenceType()) { 8361 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8362 } 8363 8364 // If the type changed, it means we had an incomplete type that was 8365 // completed by the initializer. For example: 8366 // int ary[] = { 1, 3, 5 }; 8367 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8368 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8369 VDecl->setType(DclT); 8370 8371 if (!VDecl->isInvalidDecl()) { 8372 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8373 8374 if (VDecl->hasAttr<BlocksAttr>()) 8375 checkRetainCycles(VDecl, Init); 8376 8377 // It is safe to assign a weak reference into a strong variable. 8378 // Although this code can still have problems: 8379 // id x = self.weakProp; 8380 // id y = self.weakProp; 8381 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8382 // paths through the function. This should be revisited if 8383 // -Wrepeated-use-of-weak is made flow-sensitive. 8384 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8385 DiagnosticsEngine::Level Level = 8386 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8387 Init->getLocStart()); 8388 if (Level != DiagnosticsEngine::Ignored) 8389 getCurFunction()->markSafeWeakUse(Init); 8390 } 8391 } 8392 8393 // The initialization is usually a full-expression. 8394 // 8395 // FIXME: If this is a braced initialization of an aggregate, it is not 8396 // an expression, and each individual field initializer is a separate 8397 // full-expression. For instance, in: 8398 // 8399 // struct Temp { ~Temp(); }; 8400 // struct S { S(Temp); }; 8401 // struct T { S a, b; } t = { Temp(), Temp() } 8402 // 8403 // we should destroy the first Temp before constructing the second. 8404 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8405 false, 8406 VDecl->isConstexpr()); 8407 if (Result.isInvalid()) { 8408 VDecl->setInvalidDecl(); 8409 return; 8410 } 8411 Init = Result.take(); 8412 8413 // Attach the initializer to the decl. 8414 VDecl->setInit(Init); 8415 8416 if (VDecl->isLocalVarDecl()) { 8417 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8418 // static storage duration shall be constant expressions or string literals. 8419 // C++ does not have this restriction. 8420 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8421 if (VDecl->getStorageClass() == SC_Static) 8422 CheckForConstantInitializer(Init, DclT); 8423 // C89 is stricter than C99 for non-static aggregate types. 8424 // C89 6.5.7p3: All the expressions [...] in an initializer list 8425 // for an object that has aggregate or union type shall be 8426 // constant expressions. 8427 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8428 isa<InitListExpr>(Init) && 8429 !Init->isConstantInitializer(Context, false)) 8430 Diag(Init->getExprLoc(), 8431 diag::ext_aggregate_init_not_constant) 8432 << Init->getSourceRange(); 8433 } 8434 } else if (VDecl->isStaticDataMember() && 8435 VDecl->getLexicalDeclContext()->isRecord()) { 8436 // This is an in-class initialization for a static data member, e.g., 8437 // 8438 // struct S { 8439 // static const int value = 17; 8440 // }; 8441 8442 // C++ [class.mem]p4: 8443 // A member-declarator can contain a constant-initializer only 8444 // if it declares a static member (9.4) of const integral or 8445 // const enumeration type, see 9.4.2. 8446 // 8447 // C++11 [class.static.data]p3: 8448 // If a non-volatile const static data member is of integral or 8449 // enumeration type, its declaration in the class definition can 8450 // specify a brace-or-equal-initializer in which every initalizer-clause 8451 // that is an assignment-expression is a constant expression. A static 8452 // data member of literal type can be declared in the class definition 8453 // with the constexpr specifier; if so, its declaration shall specify a 8454 // brace-or-equal-initializer in which every initializer-clause that is 8455 // an assignment-expression is a constant expression. 8456 8457 // Do nothing on dependent types. 8458 if (DclT->isDependentType()) { 8459 8460 // Allow any 'static constexpr' members, whether or not they are of literal 8461 // type. We separately check that every constexpr variable is of literal 8462 // type. 8463 } else if (VDecl->isConstexpr()) { 8464 8465 // Require constness. 8466 } else if (!DclT.isConstQualified()) { 8467 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8468 << Init->getSourceRange(); 8469 VDecl->setInvalidDecl(); 8470 8471 // We allow integer constant expressions in all cases. 8472 } else if (DclT->isIntegralOrEnumerationType()) { 8473 // Check whether the expression is a constant expression. 8474 SourceLocation Loc; 8475 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8476 // In C++11, a non-constexpr const static data member with an 8477 // in-class initializer cannot be volatile. 8478 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8479 else if (Init->isValueDependent()) 8480 ; // Nothing to check. 8481 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8482 ; // Ok, it's an ICE! 8483 else if (Init->isEvaluatable(Context)) { 8484 // If we can constant fold the initializer through heroics, accept it, 8485 // but report this as a use of an extension for -pedantic. 8486 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8487 << Init->getSourceRange(); 8488 } else { 8489 // Otherwise, this is some crazy unknown case. Report the issue at the 8490 // location provided by the isIntegerConstantExpr failed check. 8491 Diag(Loc, diag::err_in_class_initializer_non_constant) 8492 << Init->getSourceRange(); 8493 VDecl->setInvalidDecl(); 8494 } 8495 8496 // We allow foldable floating-point constants as an extension. 8497 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8498 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8499 // it anyway and provide a fixit to add the 'constexpr'. 8500 if (getLangOpts().CPlusPlus11) { 8501 Diag(VDecl->getLocation(), 8502 diag::ext_in_class_initializer_float_type_cxx11) 8503 << DclT << Init->getSourceRange(); 8504 Diag(VDecl->getLocStart(), 8505 diag::note_in_class_initializer_float_type_cxx11) 8506 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8507 } else { 8508 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8509 << DclT << Init->getSourceRange(); 8510 8511 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8512 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8513 << Init->getSourceRange(); 8514 VDecl->setInvalidDecl(); 8515 } 8516 } 8517 8518 // Suggest adding 'constexpr' in C++11 for literal types. 8519 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8520 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8521 << DclT << Init->getSourceRange() 8522 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8523 VDecl->setConstexpr(true); 8524 8525 } else { 8526 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8527 << DclT << Init->getSourceRange(); 8528 VDecl->setInvalidDecl(); 8529 } 8530 } else if (VDecl->isFileVarDecl()) { 8531 if (VDecl->getStorageClass() == SC_Extern && 8532 (!getLangOpts().CPlusPlus || 8533 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8534 VDecl->isExternC())) && 8535 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8536 Diag(VDecl->getLocation(), diag::warn_extern_init); 8537 8538 // C99 6.7.8p4. All file scoped initializers need to be constant. 8539 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8540 CheckForConstantInitializer(Init, DclT); 8541 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8542 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8543 !Init->isValueDependent() && !VDecl->isConstexpr() && 8544 !Init->isConstantInitializer( 8545 Context, VDecl->getType()->isReferenceType())) { 8546 // GNU C++98 edits for __thread, [basic.start.init]p4: 8547 // An object of thread storage duration shall not require dynamic 8548 // initialization. 8549 // FIXME: Need strict checking here. 8550 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8551 if (getLangOpts().CPlusPlus11) 8552 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8553 } 8554 } 8555 8556 // We will represent direct-initialization similarly to copy-initialization: 8557 // int x(1); -as-> int x = 1; 8558 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8559 // 8560 // Clients that want to distinguish between the two forms, can check for 8561 // direct initializer using VarDecl::getInitStyle(). 8562 // A major benefit is that clients that don't particularly care about which 8563 // exactly form was it (like the CodeGen) can handle both cases without 8564 // special case code. 8565 8566 // C++ 8.5p11: 8567 // The form of initialization (using parentheses or '=') is generally 8568 // insignificant, but does matter when the entity being initialized has a 8569 // class type. 8570 if (CXXDirectInit) { 8571 assert(DirectInit && "Call-style initializer must be direct init."); 8572 VDecl->setInitStyle(VarDecl::CallInit); 8573 } else if (DirectInit) { 8574 // This must be list-initialization. No other way is direct-initialization. 8575 VDecl->setInitStyle(VarDecl::ListInit); 8576 } 8577 8578 CheckCompleteVariableDeclaration(VDecl); 8579 } 8580 8581 /// ActOnInitializerError - Given that there was an error parsing an 8582 /// initializer for the given declaration, try to return to some form 8583 /// of sanity. 8584 void Sema::ActOnInitializerError(Decl *D) { 8585 // Our main concern here is re-establishing invariants like "a 8586 // variable's type is either dependent or complete". 8587 if (!D || D->isInvalidDecl()) return; 8588 8589 VarDecl *VD = dyn_cast<VarDecl>(D); 8590 if (!VD) return; 8591 8592 // Auto types are meaningless if we can't make sense of the initializer. 8593 if (ParsingInitForAutoVars.count(D)) { 8594 D->setInvalidDecl(); 8595 return; 8596 } 8597 8598 QualType Ty = VD->getType(); 8599 if (Ty->isDependentType()) return; 8600 8601 // Require a complete type. 8602 if (RequireCompleteType(VD->getLocation(), 8603 Context.getBaseElementType(Ty), 8604 diag::err_typecheck_decl_incomplete_type)) { 8605 VD->setInvalidDecl(); 8606 return; 8607 } 8608 8609 // Require a non-abstract type. 8610 if (RequireNonAbstractType(VD->getLocation(), Ty, 8611 diag::err_abstract_type_in_decl, 8612 AbstractVariableType)) { 8613 VD->setInvalidDecl(); 8614 return; 8615 } 8616 8617 // Don't bother complaining about constructors or destructors, 8618 // though. 8619 } 8620 8621 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8622 bool TypeMayContainAuto) { 8623 // If there is no declaration, there was an error parsing it. Just ignore it. 8624 if (RealDecl == 0) 8625 return; 8626 8627 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8628 QualType Type = Var->getType(); 8629 8630 // C++11 [dcl.spec.auto]p3 8631 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8632 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8633 << Var->getDeclName() << Type; 8634 Var->setInvalidDecl(); 8635 return; 8636 } 8637 8638 // C++11 [class.static.data]p3: A static data member can be declared with 8639 // the constexpr specifier; if so, its declaration shall specify 8640 // a brace-or-equal-initializer. 8641 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8642 // the definition of a variable [...] or the declaration of a static data 8643 // member. 8644 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8645 if (Var->isStaticDataMember()) 8646 Diag(Var->getLocation(), 8647 diag::err_constexpr_static_mem_var_requires_init) 8648 << Var->getDeclName(); 8649 else 8650 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8651 Var->setInvalidDecl(); 8652 return; 8653 } 8654 8655 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8656 // be initialized. 8657 if (!Var->isInvalidDecl() && 8658 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8659 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8660 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 8661 Var->setInvalidDecl(); 8662 return; 8663 } 8664 8665 switch (Var->isThisDeclarationADefinition()) { 8666 case VarDecl::Definition: 8667 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8668 break; 8669 8670 // We have an out-of-line definition of a static data member 8671 // that has an in-class initializer, so we type-check this like 8672 // a declaration. 8673 // 8674 // Fall through 8675 8676 case VarDecl::DeclarationOnly: 8677 // It's only a declaration. 8678 8679 // Block scope. C99 6.7p7: If an identifier for an object is 8680 // declared with no linkage (C99 6.2.2p6), the type for the 8681 // object shall be complete. 8682 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8683 !Var->hasLinkage() && !Var->isInvalidDecl() && 8684 RequireCompleteType(Var->getLocation(), Type, 8685 diag::err_typecheck_decl_incomplete_type)) 8686 Var->setInvalidDecl(); 8687 8688 // Make sure that the type is not abstract. 8689 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8690 RequireNonAbstractType(Var->getLocation(), Type, 8691 diag::err_abstract_type_in_decl, 8692 AbstractVariableType)) 8693 Var->setInvalidDecl(); 8694 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8695 Var->getStorageClass() == SC_PrivateExtern) { 8696 Diag(Var->getLocation(), diag::warn_private_extern); 8697 Diag(Var->getLocation(), diag::note_private_extern); 8698 } 8699 8700 return; 8701 8702 case VarDecl::TentativeDefinition: 8703 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8704 // object that has file scope without an initializer, and without a 8705 // storage-class specifier or with the storage-class specifier "static", 8706 // constitutes a tentative definition. Note: A tentative definition with 8707 // external linkage is valid (C99 6.2.2p5). 8708 if (!Var->isInvalidDecl()) { 8709 if (const IncompleteArrayType *ArrayT 8710 = Context.getAsIncompleteArrayType(Type)) { 8711 if (RequireCompleteType(Var->getLocation(), 8712 ArrayT->getElementType(), 8713 diag::err_illegal_decl_array_incomplete_type)) 8714 Var->setInvalidDecl(); 8715 } else if (Var->getStorageClass() == SC_Static) { 8716 // C99 6.9.2p3: If the declaration of an identifier for an object is 8717 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8718 // declared type shall not be an incomplete type. 8719 // NOTE: code such as the following 8720 // static struct s; 8721 // struct s { int a; }; 8722 // is accepted by gcc. Hence here we issue a warning instead of 8723 // an error and we do not invalidate the static declaration. 8724 // NOTE: to avoid multiple warnings, only check the first declaration. 8725 if (Var->isFirstDecl()) 8726 RequireCompleteType(Var->getLocation(), Type, 8727 diag::ext_typecheck_decl_incomplete_type); 8728 } 8729 } 8730 8731 // Record the tentative definition; we're done. 8732 if (!Var->isInvalidDecl()) 8733 TentativeDefinitions.push_back(Var); 8734 return; 8735 } 8736 8737 // Provide a specific diagnostic for uninitialized variable 8738 // definitions with incomplete array type. 8739 if (Type->isIncompleteArrayType()) { 8740 Diag(Var->getLocation(), 8741 diag::err_typecheck_incomplete_array_needs_initializer); 8742 Var->setInvalidDecl(); 8743 return; 8744 } 8745 8746 // Provide a specific diagnostic for uninitialized variable 8747 // definitions with reference type. 8748 if (Type->isReferenceType()) { 8749 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8750 << Var->getDeclName() 8751 << SourceRange(Var->getLocation(), Var->getLocation()); 8752 Var->setInvalidDecl(); 8753 return; 8754 } 8755 8756 // Do not attempt to type-check the default initializer for a 8757 // variable with dependent type. 8758 if (Type->isDependentType()) 8759 return; 8760 8761 if (Var->isInvalidDecl()) 8762 return; 8763 8764 if (RequireCompleteType(Var->getLocation(), 8765 Context.getBaseElementType(Type), 8766 diag::err_typecheck_decl_incomplete_type)) { 8767 Var->setInvalidDecl(); 8768 return; 8769 } 8770 8771 // The variable can not have an abstract class type. 8772 if (RequireNonAbstractType(Var->getLocation(), Type, 8773 diag::err_abstract_type_in_decl, 8774 AbstractVariableType)) { 8775 Var->setInvalidDecl(); 8776 return; 8777 } 8778 8779 // Check for jumps past the implicit initializer. C++0x 8780 // clarifies that this applies to a "variable with automatic 8781 // storage duration", not a "local variable". 8782 // C++11 [stmt.dcl]p3 8783 // A program that jumps from a point where a variable with automatic 8784 // storage duration is not in scope to a point where it is in scope is 8785 // ill-formed unless the variable has scalar type, class type with a 8786 // trivial default constructor and a trivial destructor, a cv-qualified 8787 // version of one of these types, or an array of one of the preceding 8788 // types and is declared without an initializer. 8789 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8790 if (const RecordType *Record 8791 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8792 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8793 // Mark the function for further checking even if the looser rules of 8794 // C++11 do not require such checks, so that we can diagnose 8795 // incompatibilities with C++98. 8796 if (!CXXRecord->isPOD()) 8797 getCurFunction()->setHasBranchProtectedScope(); 8798 } 8799 } 8800 8801 // C++03 [dcl.init]p9: 8802 // If no initializer is specified for an object, and the 8803 // object is of (possibly cv-qualified) non-POD class type (or 8804 // array thereof), the object shall be default-initialized; if 8805 // the object is of const-qualified type, the underlying class 8806 // type shall have a user-declared default 8807 // constructor. Otherwise, if no initializer is specified for 8808 // a non- static object, the object and its subobjects, if 8809 // any, have an indeterminate initial value); if the object 8810 // or any of its subobjects are of const-qualified type, the 8811 // program is ill-formed. 8812 // C++0x [dcl.init]p11: 8813 // If no initializer is specified for an object, the object is 8814 // default-initialized; [...]. 8815 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8816 InitializationKind Kind 8817 = InitializationKind::CreateDefault(Var->getLocation()); 8818 8819 InitializationSequence InitSeq(*this, Entity, Kind, None); 8820 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8821 if (Init.isInvalid()) 8822 Var->setInvalidDecl(); 8823 else if (Init.get()) { 8824 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8825 // This is important for template substitution. 8826 Var->setInitStyle(VarDecl::CallInit); 8827 } 8828 8829 CheckCompleteVariableDeclaration(Var); 8830 } 8831 } 8832 8833 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8834 VarDecl *VD = dyn_cast<VarDecl>(D); 8835 if (!VD) { 8836 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8837 D->setInvalidDecl(); 8838 return; 8839 } 8840 8841 VD->setCXXForRangeDecl(true); 8842 8843 // for-range-declaration cannot be given a storage class specifier. 8844 int Error = -1; 8845 switch (VD->getStorageClass()) { 8846 case SC_None: 8847 break; 8848 case SC_Extern: 8849 Error = 0; 8850 break; 8851 case SC_Static: 8852 Error = 1; 8853 break; 8854 case SC_PrivateExtern: 8855 Error = 2; 8856 break; 8857 case SC_Auto: 8858 Error = 3; 8859 break; 8860 case SC_Register: 8861 Error = 4; 8862 break; 8863 case SC_OpenCLWorkGroupLocal: 8864 llvm_unreachable("Unexpected storage class"); 8865 } 8866 if (VD->isConstexpr()) 8867 Error = 5; 8868 if (Error != -1) { 8869 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8870 << VD->getDeclName() << Error; 8871 D->setInvalidDecl(); 8872 } 8873 } 8874 8875 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8876 if (var->isInvalidDecl()) return; 8877 8878 // In ARC, don't allow jumps past the implicit initialization of a 8879 // local retaining variable. 8880 if (getLangOpts().ObjCAutoRefCount && 8881 var->hasLocalStorage()) { 8882 switch (var->getType().getObjCLifetime()) { 8883 case Qualifiers::OCL_None: 8884 case Qualifiers::OCL_ExplicitNone: 8885 case Qualifiers::OCL_Autoreleasing: 8886 break; 8887 8888 case Qualifiers::OCL_Weak: 8889 case Qualifiers::OCL_Strong: 8890 getCurFunction()->setHasBranchProtectedScope(); 8891 break; 8892 } 8893 } 8894 8895 // Warn about externally-visible variables being defined without a 8896 // prior declaration. We only want to do this for global 8897 // declarations, but we also specifically need to avoid doing it for 8898 // class members because the linkage of an anonymous class can 8899 // change if it's later given a typedef name. 8900 if (var->isThisDeclarationADefinition() && 8901 var->getDeclContext()->getRedeclContext()->isFileContext() && 8902 var->isExternallyVisible() && var->hasLinkage() && 8903 getDiagnostics().getDiagnosticLevel( 8904 diag::warn_missing_variable_declarations, 8905 var->getLocation())) { 8906 // Find a previous declaration that's not a definition. 8907 VarDecl *prev = var->getPreviousDecl(); 8908 while (prev && prev->isThisDeclarationADefinition()) 8909 prev = prev->getPreviousDecl(); 8910 8911 if (!prev) 8912 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8913 } 8914 8915 if (var->getTLSKind() == VarDecl::TLS_Static && 8916 var->getType().isDestructedType()) { 8917 // GNU C++98 edits for __thread, [basic.start.term]p3: 8918 // The type of an object with thread storage duration shall not 8919 // have a non-trivial destructor. 8920 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8921 if (getLangOpts().CPlusPlus11) 8922 Diag(var->getLocation(), diag::note_use_thread_local); 8923 } 8924 8925 if (var->isThisDeclarationADefinition() && 8926 ActiveTemplateInstantiations.empty()) { 8927 PragmaStack<StringLiteral *> *Stack = nullptr; 8928 int SectionFlags = PSF_Implicit | PSF_Read; 8929 if (var->getType().isConstQualified()) 8930 Stack = &ConstSegStack; 8931 else if (!var->getInit()) { 8932 Stack = &BSSSegStack; 8933 SectionFlags |= PSF_Write; 8934 } else { 8935 Stack = &DataSegStack; 8936 SectionFlags |= PSF_Write; 8937 } 8938 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 8939 var->addAttr( 8940 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8941 Stack->CurrentValue->getString(), 8942 Stack->CurrentPragmaLocation)); 8943 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 8944 if (UnifySection(SA->getName(), SectionFlags, var)) 8945 var->dropAttr<SectionAttr>(); 8946 } 8947 8948 // All the following checks are C++ only. 8949 if (!getLangOpts().CPlusPlus) return; 8950 8951 QualType type = var->getType(); 8952 if (type->isDependentType()) return; 8953 8954 // __block variables might require us to capture a copy-initializer. 8955 if (var->hasAttr<BlocksAttr>()) { 8956 // It's currently invalid to ever have a __block variable with an 8957 // array type; should we diagnose that here? 8958 8959 // Regardless, we don't want to ignore array nesting when 8960 // constructing this copy. 8961 if (type->isStructureOrClassType()) { 8962 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8963 SourceLocation poi = var->getLocation(); 8964 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8965 ExprResult result 8966 = PerformMoveOrCopyInitialization( 8967 InitializedEntity::InitializeBlock(poi, type, false), 8968 var, var->getType(), varRef, /*AllowNRVO=*/true); 8969 if (!result.isInvalid()) { 8970 result = MaybeCreateExprWithCleanups(result); 8971 Expr *init = result.takeAs<Expr>(); 8972 Context.setBlockVarCopyInits(var, init); 8973 } 8974 } 8975 } 8976 8977 Expr *Init = var->getInit(); 8978 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8979 QualType baseType = Context.getBaseElementType(type); 8980 8981 if (!var->getDeclContext()->isDependentContext() && 8982 Init && !Init->isValueDependent()) { 8983 if (IsGlobal && !var->isConstexpr() && 8984 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8985 var->getLocation()) 8986 != DiagnosticsEngine::Ignored) { 8987 // Warn about globals which don't have a constant initializer. Don't 8988 // warn about globals with a non-trivial destructor because we already 8989 // warned about them. 8990 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8991 if (!(RD && !RD->hasTrivialDestructor()) && 8992 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8993 Diag(var->getLocation(), diag::warn_global_constructor) 8994 << Init->getSourceRange(); 8995 } 8996 8997 if (var->isConstexpr()) { 8998 SmallVector<PartialDiagnosticAt, 8> Notes; 8999 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9000 SourceLocation DiagLoc = var->getLocation(); 9001 // If the note doesn't add any useful information other than a source 9002 // location, fold it into the primary diagnostic. 9003 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9004 diag::note_invalid_subexpr_in_const_expr) { 9005 DiagLoc = Notes[0].first; 9006 Notes.clear(); 9007 } 9008 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9009 << var << Init->getSourceRange(); 9010 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9011 Diag(Notes[I].first, Notes[I].second); 9012 } 9013 } else if (var->isUsableInConstantExpressions(Context)) { 9014 // Check whether the initializer of a const variable of integral or 9015 // enumeration type is an ICE now, since we can't tell whether it was 9016 // initialized by a constant expression if we check later. 9017 var->checkInitIsICE(); 9018 } 9019 } 9020 9021 // Require the destructor. 9022 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9023 FinalizeVarWithDestructor(var, recordType); 9024 } 9025 9026 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9027 /// any semantic actions necessary after any initializer has been attached. 9028 void 9029 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9030 // Note that we are no longer parsing the initializer for this declaration. 9031 ParsingInitForAutoVars.erase(ThisDecl); 9032 9033 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9034 if (!VD) 9035 return; 9036 9037 checkAttributesAfterMerging(*this, *VD); 9038 9039 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9040 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9041 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9042 VD->dropAttr<UsedAttr>(); 9043 } 9044 } 9045 9046 if (!VD->isInvalidDecl() && 9047 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 9048 if (const VarDecl *Def = VD->getDefinition()) { 9049 if (Def->hasAttr<AliasAttr>()) { 9050 Diag(VD->getLocation(), diag::err_tentative_after_alias) 9051 << VD->getDeclName(); 9052 Diag(Def->getLocation(), diag::note_previous_definition); 9053 VD->setInvalidDecl(); 9054 } 9055 } 9056 } 9057 9058 const DeclContext *DC = VD->getDeclContext(); 9059 // If there's a #pragma GCC visibility in scope, and this isn't a class 9060 // member, set the visibility of this variable. 9061 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9062 AddPushedVisibilityAttribute(VD); 9063 9064 // FIXME: Warn on unused templates. 9065 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate()) 9066 MarkUnusedFileScopedDecl(VD); 9067 9068 // Now we have parsed the initializer and can update the table of magic 9069 // tag values. 9070 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9071 !VD->getType()->isIntegralOrEnumerationType()) 9072 return; 9073 9074 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9075 const Expr *MagicValueExpr = VD->getInit(); 9076 if (!MagicValueExpr) { 9077 continue; 9078 } 9079 llvm::APSInt MagicValueInt; 9080 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9081 Diag(I->getRange().getBegin(), 9082 diag::err_type_tag_for_datatype_not_ice) 9083 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9084 continue; 9085 } 9086 if (MagicValueInt.getActiveBits() > 64) { 9087 Diag(I->getRange().getBegin(), 9088 diag::err_type_tag_for_datatype_too_large) 9089 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9090 continue; 9091 } 9092 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9093 RegisterTypeTagForDatatype(I->getArgumentKind(), 9094 MagicValue, 9095 I->getMatchingCType(), 9096 I->getLayoutCompatible(), 9097 I->getMustBeNull()); 9098 } 9099 } 9100 9101 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9102 ArrayRef<Decl *> Group) { 9103 SmallVector<Decl*, 8> Decls; 9104 9105 if (DS.isTypeSpecOwned()) 9106 Decls.push_back(DS.getRepAsDecl()); 9107 9108 DeclaratorDecl *FirstDeclaratorInGroup = 0; 9109 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9110 if (Decl *D = Group[i]) { 9111 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9112 if (!FirstDeclaratorInGroup) 9113 FirstDeclaratorInGroup = DD; 9114 Decls.push_back(D); 9115 } 9116 9117 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9118 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9119 HandleTagNumbering(*this, Tag, S); 9120 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9121 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9122 } 9123 } 9124 9125 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9126 } 9127 9128 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9129 /// group, performing any necessary semantic checking. 9130 Sema::DeclGroupPtrTy 9131 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 9132 bool TypeMayContainAuto) { 9133 // C++0x [dcl.spec.auto]p7: 9134 // If the type deduced for the template parameter U is not the same in each 9135 // deduction, the program is ill-formed. 9136 // FIXME: When initializer-list support is added, a distinction is needed 9137 // between the deduced type U and the deduced type which 'auto' stands for. 9138 // auto a = 0, b = { 1, 2, 3 }; 9139 // is legal because the deduced type U is 'int' in both cases. 9140 if (TypeMayContainAuto && Group.size() > 1) { 9141 QualType Deduced; 9142 CanQualType DeducedCanon; 9143 VarDecl *DeducedDecl = 0; 9144 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9145 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9146 AutoType *AT = D->getType()->getContainedAutoType(); 9147 // Don't reissue diagnostics when instantiating a template. 9148 if (AT && D->isInvalidDecl()) 9149 break; 9150 QualType U = AT ? AT->getDeducedType() : QualType(); 9151 if (!U.isNull()) { 9152 CanQualType UCanon = Context.getCanonicalType(U); 9153 if (Deduced.isNull()) { 9154 Deduced = U; 9155 DeducedCanon = UCanon; 9156 DeducedDecl = D; 9157 } else if (DeducedCanon != UCanon) { 9158 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9159 diag::err_auto_different_deductions) 9160 << (AT->isDecltypeAuto() ? 1 : 0) 9161 << Deduced << DeducedDecl->getDeclName() 9162 << U << D->getDeclName() 9163 << DeducedDecl->getInit()->getSourceRange() 9164 << D->getInit()->getSourceRange(); 9165 D->setInvalidDecl(); 9166 break; 9167 } 9168 } 9169 } 9170 } 9171 } 9172 9173 ActOnDocumentableDecls(Group); 9174 9175 return DeclGroupPtrTy::make( 9176 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9177 } 9178 9179 void Sema::ActOnDocumentableDecl(Decl *D) { 9180 ActOnDocumentableDecls(D); 9181 } 9182 9183 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9184 // Don't parse the comment if Doxygen diagnostics are ignored. 9185 if (Group.empty() || !Group[0]) 9186 return; 9187 9188 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9189 Group[0]->getLocation()) 9190 == DiagnosticsEngine::Ignored) 9191 return; 9192 9193 if (Group.size() >= 2) { 9194 // This is a decl group. Normally it will contain only declarations 9195 // produced from declarator list. But in case we have any definitions or 9196 // additional declaration references: 9197 // 'typedef struct S {} S;' 9198 // 'typedef struct S *S;' 9199 // 'struct S *pS;' 9200 // FinalizeDeclaratorGroup adds these as separate declarations. 9201 Decl *MaybeTagDecl = Group[0]; 9202 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9203 Group = Group.slice(1); 9204 } 9205 } 9206 9207 // See if there are any new comments that are not attached to a decl. 9208 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9209 if (!Comments.empty() && 9210 !Comments.back()->isAttached()) { 9211 // There is at least one comment that not attached to a decl. 9212 // Maybe it should be attached to one of these decls? 9213 // 9214 // Note that this way we pick up not only comments that precede the 9215 // declaration, but also comments that *follow* the declaration -- thanks to 9216 // the lookahead in the lexer: we've consumed the semicolon and looked 9217 // ahead through comments. 9218 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9219 Context.getCommentForDecl(Group[i], &PP); 9220 } 9221 } 9222 9223 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9224 /// to introduce parameters into function prototype scope. 9225 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9226 const DeclSpec &DS = D.getDeclSpec(); 9227 9228 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9229 9230 // C++03 [dcl.stc]p2 also permits 'auto'. 9231 VarDecl::StorageClass StorageClass = SC_None; 9232 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9233 StorageClass = SC_Register; 9234 } else if (getLangOpts().CPlusPlus && 9235 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9236 StorageClass = SC_Auto; 9237 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9238 Diag(DS.getStorageClassSpecLoc(), 9239 diag::err_invalid_storage_class_in_func_decl); 9240 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9241 } 9242 9243 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9244 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9245 << DeclSpec::getSpecifierName(TSCS); 9246 if (DS.isConstexprSpecified()) 9247 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9248 << 0; 9249 9250 DiagnoseFunctionSpecifiers(DS); 9251 9252 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9253 QualType parmDeclType = TInfo->getType(); 9254 9255 if (getLangOpts().CPlusPlus) { 9256 // Check that there are no default arguments inside the type of this 9257 // parameter. 9258 CheckExtraCXXDefaultArguments(D); 9259 9260 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9261 if (D.getCXXScopeSpec().isSet()) { 9262 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9263 << D.getCXXScopeSpec().getRange(); 9264 D.getCXXScopeSpec().clear(); 9265 } 9266 } 9267 9268 // Ensure we have a valid name 9269 IdentifierInfo *II = 0; 9270 if (D.hasName()) { 9271 II = D.getIdentifier(); 9272 if (!II) { 9273 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9274 << GetNameForDeclarator(D).getName(); 9275 D.setInvalidType(true); 9276 } 9277 } 9278 9279 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9280 if (II) { 9281 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9282 ForRedeclaration); 9283 LookupName(R, S); 9284 if (R.isSingleResult()) { 9285 NamedDecl *PrevDecl = R.getFoundDecl(); 9286 if (PrevDecl->isTemplateParameter()) { 9287 // Maybe we will complain about the shadowed template parameter. 9288 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9289 // Just pretend that we didn't see the previous declaration. 9290 PrevDecl = 0; 9291 } else if (S->isDeclScope(PrevDecl)) { 9292 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9293 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9294 9295 // Recover by removing the name 9296 II = 0; 9297 D.SetIdentifier(0, D.getIdentifierLoc()); 9298 D.setInvalidType(true); 9299 } 9300 } 9301 } 9302 9303 // Temporarily put parameter variables in the translation unit, not 9304 // the enclosing context. This prevents them from accidentally 9305 // looking like class members in C++. 9306 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9307 D.getLocStart(), 9308 D.getIdentifierLoc(), II, 9309 parmDeclType, TInfo, 9310 StorageClass); 9311 9312 if (D.isInvalidType()) 9313 New->setInvalidDecl(); 9314 9315 assert(S->isFunctionPrototypeScope()); 9316 assert(S->getFunctionPrototypeDepth() >= 1); 9317 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9318 S->getNextFunctionPrototypeIndex()); 9319 9320 // Add the parameter declaration into this scope. 9321 S->AddDecl(New); 9322 if (II) 9323 IdResolver.AddDecl(New); 9324 9325 ProcessDeclAttributes(S, New, D); 9326 9327 if (D.getDeclSpec().isModulePrivateSpecified()) 9328 Diag(New->getLocation(), diag::err_module_private_local) 9329 << 1 << New->getDeclName() 9330 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9331 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9332 9333 if (New->hasAttr<BlocksAttr>()) { 9334 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9335 } 9336 return New; 9337 } 9338 9339 /// \brief Synthesizes a variable for a parameter arising from a 9340 /// typedef. 9341 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9342 SourceLocation Loc, 9343 QualType T) { 9344 /* FIXME: setting StartLoc == Loc. 9345 Would it be worth to modify callers so as to provide proper source 9346 location for the unnamed parameters, embedding the parameter's type? */ 9347 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9348 T, Context.getTrivialTypeSourceInfo(T, Loc), 9349 SC_None, 0); 9350 Param->setImplicit(); 9351 return Param; 9352 } 9353 9354 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9355 ParmVarDecl * const *ParamEnd) { 9356 // Don't diagnose unused-parameter errors in template instantiations; we 9357 // will already have done so in the template itself. 9358 if (!ActiveTemplateInstantiations.empty()) 9359 return; 9360 9361 for (; Param != ParamEnd; ++Param) { 9362 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9363 !(*Param)->hasAttr<UnusedAttr>()) { 9364 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9365 << (*Param)->getDeclName(); 9366 } 9367 } 9368 } 9369 9370 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9371 ParmVarDecl * const *ParamEnd, 9372 QualType ReturnTy, 9373 NamedDecl *D) { 9374 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9375 return; 9376 9377 // Warn if the return value is pass-by-value and larger than the specified 9378 // threshold. 9379 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9380 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9381 if (Size > LangOpts.NumLargeByValueCopy) 9382 Diag(D->getLocation(), diag::warn_return_value_size) 9383 << D->getDeclName() << Size; 9384 } 9385 9386 // Warn if any parameter is pass-by-value and larger than the specified 9387 // threshold. 9388 for (; Param != ParamEnd; ++Param) { 9389 QualType T = (*Param)->getType(); 9390 if (T->isDependentType() || !T.isPODType(Context)) 9391 continue; 9392 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9393 if (Size > LangOpts.NumLargeByValueCopy) 9394 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9395 << (*Param)->getDeclName() << Size; 9396 } 9397 } 9398 9399 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9400 SourceLocation NameLoc, IdentifierInfo *Name, 9401 QualType T, TypeSourceInfo *TSInfo, 9402 VarDecl::StorageClass StorageClass) { 9403 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9404 if (getLangOpts().ObjCAutoRefCount && 9405 T.getObjCLifetime() == Qualifiers::OCL_None && 9406 T->isObjCLifetimeType()) { 9407 9408 Qualifiers::ObjCLifetime lifetime; 9409 9410 // Special cases for arrays: 9411 // - if it's const, use __unsafe_unretained 9412 // - otherwise, it's an error 9413 if (T->isArrayType()) { 9414 if (!T.isConstQualified()) { 9415 DelayedDiagnostics.add( 9416 sema::DelayedDiagnostic::makeForbiddenType( 9417 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9418 } 9419 lifetime = Qualifiers::OCL_ExplicitNone; 9420 } else { 9421 lifetime = T->getObjCARCImplicitLifetime(); 9422 } 9423 T = Context.getLifetimeQualifiedType(T, lifetime); 9424 } 9425 9426 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9427 Context.getAdjustedParameterType(T), 9428 TSInfo, 9429 StorageClass, 0); 9430 9431 // Parameters can not be abstract class types. 9432 // For record types, this is done by the AbstractClassUsageDiagnoser once 9433 // the class has been completely parsed. 9434 if (!CurContext->isRecord() && 9435 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9436 AbstractParamType)) 9437 New->setInvalidDecl(); 9438 9439 // Parameter declarators cannot be interface types. All ObjC objects are 9440 // passed by reference. 9441 if (T->isObjCObjectType()) { 9442 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9443 Diag(NameLoc, 9444 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9445 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9446 T = Context.getObjCObjectPointerType(T); 9447 New->setType(T); 9448 } 9449 9450 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9451 // duration shall not be qualified by an address-space qualifier." 9452 // Since all parameters have automatic store duration, they can not have 9453 // an address space. 9454 if (T.getAddressSpace() != 0) { 9455 // OpenCL allows function arguments declared to be an array of a type 9456 // to be qualified with an address space. 9457 if (!(getLangOpts().OpenCL && T->isArrayType())) { 9458 Diag(NameLoc, diag::err_arg_with_address_space); 9459 New->setInvalidDecl(); 9460 } 9461 } 9462 9463 return New; 9464 } 9465 9466 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9467 SourceLocation LocAfterDecls) { 9468 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9469 9470 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9471 // for a K&R function. 9472 if (!FTI.hasPrototype) { 9473 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 9474 --i; 9475 if (FTI.Params[i].Param == 0) { 9476 SmallString<256> Code; 9477 llvm::raw_svector_ostream(Code) 9478 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 9479 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 9480 << FTI.Params[i].Ident 9481 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9482 9483 // Implicitly declare the argument as type 'int' for lack of a better 9484 // type. 9485 AttributeFactory attrs; 9486 DeclSpec DS(attrs); 9487 const char* PrevSpec; // unused 9488 unsigned DiagID; // unused 9489 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 9490 DiagID, Context.getPrintingPolicy()); 9491 // Use the identifier location for the type source range. 9492 DS.SetRangeStart(FTI.Params[i].IdentLoc); 9493 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 9494 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9495 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 9496 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 9497 } 9498 } 9499 } 9500 } 9501 9502 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9503 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9504 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9505 Scope *ParentScope = FnBodyScope->getParent(); 9506 9507 D.setFunctionDefinitionKind(FDK_Definition); 9508 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9509 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9510 } 9511 9512 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9513 const FunctionDecl*& PossibleZeroParamPrototype) { 9514 // Don't warn about invalid declarations. 9515 if (FD->isInvalidDecl()) 9516 return false; 9517 9518 // Or declarations that aren't global. 9519 if (!FD->isGlobal()) 9520 return false; 9521 9522 // Don't warn about C++ member functions. 9523 if (isa<CXXMethodDecl>(FD)) 9524 return false; 9525 9526 // Don't warn about 'main'. 9527 if (FD->isMain()) 9528 return false; 9529 9530 // Don't warn about inline functions. 9531 if (FD->isInlined()) 9532 return false; 9533 9534 // Don't warn about function templates. 9535 if (FD->getDescribedFunctionTemplate()) 9536 return false; 9537 9538 // Don't warn about function template specializations. 9539 if (FD->isFunctionTemplateSpecialization()) 9540 return false; 9541 9542 // Don't warn for OpenCL kernels. 9543 if (FD->hasAttr<OpenCLKernelAttr>()) 9544 return false; 9545 9546 bool MissingPrototype = true; 9547 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9548 Prev; Prev = Prev->getPreviousDecl()) { 9549 // Ignore any declarations that occur in function or method 9550 // scope, because they aren't visible from the header. 9551 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9552 continue; 9553 9554 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9555 if (FD->getNumParams() == 0) 9556 PossibleZeroParamPrototype = Prev; 9557 break; 9558 } 9559 9560 return MissingPrototype; 9561 } 9562 9563 void 9564 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9565 const FunctionDecl *EffectiveDefinition) { 9566 // Don't complain if we're in GNU89 mode and the previous definition 9567 // was an extern inline function. 9568 const FunctionDecl *Definition = EffectiveDefinition; 9569 if (!Definition) 9570 if (!FD->isDefined(Definition)) 9571 return; 9572 9573 if (canRedefineFunction(Definition, getLangOpts())) 9574 return; 9575 9576 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9577 Definition->getStorageClass() == SC_Extern) 9578 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9579 << FD->getDeclName() << getLangOpts().CPlusPlus; 9580 else 9581 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9582 9583 Diag(Definition->getLocation(), diag::note_previous_definition); 9584 FD->setInvalidDecl(); 9585 } 9586 9587 9588 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9589 Sema &S) { 9590 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9591 9592 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9593 LSI->CallOperator = CallOperator; 9594 LSI->Lambda = LambdaClass; 9595 LSI->ReturnType = CallOperator->getReturnType(); 9596 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9597 9598 if (LCD == LCD_None) 9599 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9600 else if (LCD == LCD_ByCopy) 9601 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9602 else if (LCD == LCD_ByRef) 9603 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9604 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9605 9606 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9607 LSI->Mutable = !CallOperator->isConst(); 9608 9609 // Add the captures to the LSI so they can be noted as already 9610 // captured within tryCaptureVar. 9611 for (const auto &C : LambdaClass->captures()) { 9612 if (C.capturesVariable()) { 9613 VarDecl *VD = C.getCapturedVar(); 9614 if (VD->isInitCapture()) 9615 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9616 QualType CaptureType = VD->getType(); 9617 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 9618 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9619 /*RefersToEnclosingLocal*/true, C.getLocation(), 9620 /*EllipsisLoc*/C.isPackExpansion() 9621 ? C.getEllipsisLoc() : SourceLocation(), 9622 CaptureType, /*Expr*/ 0); 9623 9624 } else if (C.capturesThis()) { 9625 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 9626 S.getCurrentThisType(), /*Expr*/ 0); 9627 } 9628 } 9629 } 9630 9631 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9632 // Clear the last template instantiation error context. 9633 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9634 9635 if (!D) 9636 return D; 9637 FunctionDecl *FD = 0; 9638 9639 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9640 FD = FunTmpl->getTemplatedDecl(); 9641 else 9642 FD = cast<FunctionDecl>(D); 9643 // If we are instantiating a generic lambda call operator, push 9644 // a LambdaScopeInfo onto the function stack. But use the information 9645 // that's already been calculated (ActOnLambdaExpr) to prime the current 9646 // LambdaScopeInfo. 9647 // When the template operator is being specialized, the LambdaScopeInfo, 9648 // has to be properly restored so that tryCaptureVariable doesn't try 9649 // and capture any new variables. In addition when calculating potential 9650 // captures during transformation of nested lambdas, it is necessary to 9651 // have the LSI properly restored. 9652 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9653 assert(ActiveTemplateInstantiations.size() && 9654 "There should be an active template instantiation on the stack " 9655 "when instantiating a generic lambda!"); 9656 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9657 } 9658 else 9659 // Enter a new function scope 9660 PushFunctionScope(); 9661 9662 // See if this is a redefinition. 9663 if (!FD->isLateTemplateParsed()) 9664 CheckForFunctionRedefinition(FD); 9665 9666 // Builtin functions cannot be defined. 9667 if (unsigned BuiltinID = FD->getBuiltinID()) { 9668 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9669 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9670 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9671 FD->setInvalidDecl(); 9672 } 9673 } 9674 9675 // The return type of a function definition must be complete 9676 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9677 QualType ResultType = FD->getReturnType(); 9678 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9679 !FD->isInvalidDecl() && 9680 RequireCompleteType(FD->getLocation(), ResultType, 9681 diag::err_func_def_incomplete_result)) 9682 FD->setInvalidDecl(); 9683 9684 // GNU warning -Wmissing-prototypes: 9685 // Warn if a global function is defined without a previous 9686 // prototype declaration. This warning is issued even if the 9687 // definition itself provides a prototype. The aim is to detect 9688 // global functions that fail to be declared in header files. 9689 const FunctionDecl *PossibleZeroParamPrototype = 0; 9690 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9691 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9692 9693 if (PossibleZeroParamPrototype) { 9694 // We found a declaration that is not a prototype, 9695 // but that could be a zero-parameter prototype 9696 if (TypeSourceInfo *TI = 9697 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9698 TypeLoc TL = TI->getTypeLoc(); 9699 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9700 Diag(PossibleZeroParamPrototype->getLocation(), 9701 diag::note_declaration_not_a_prototype) 9702 << PossibleZeroParamPrototype 9703 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9704 } 9705 } 9706 } 9707 9708 if (FnBodyScope) 9709 PushDeclContext(FnBodyScope, FD); 9710 9711 // Check the validity of our function parameters 9712 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9713 /*CheckParameterNames=*/true); 9714 9715 // Introduce our parameters into the function scope 9716 for (auto Param : FD->params()) { 9717 Param->setOwningFunction(FD); 9718 9719 // If this has an identifier, add it to the scope stack. 9720 if (Param->getIdentifier() && FnBodyScope) { 9721 CheckShadow(FnBodyScope, Param); 9722 9723 PushOnScopeChains(Param, FnBodyScope); 9724 } 9725 } 9726 9727 // If we had any tags defined in the function prototype, 9728 // introduce them into the function scope. 9729 if (FnBodyScope) { 9730 for (ArrayRef<NamedDecl *>::iterator 9731 I = FD->getDeclsInPrototypeScope().begin(), 9732 E = FD->getDeclsInPrototypeScope().end(); 9733 I != E; ++I) { 9734 NamedDecl *D = *I; 9735 9736 // Some of these decls (like enums) may have been pinned to the translation unit 9737 // for lack of a real context earlier. If so, remove from the translation unit 9738 // and reattach to the current context. 9739 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9740 // Is the decl actually in the context? 9741 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 9742 if (DI == D) { 9743 Context.getTranslationUnitDecl()->removeDecl(D); 9744 break; 9745 } 9746 } 9747 // Either way, reassign the lexical decl context to our FunctionDecl. 9748 D->setLexicalDeclContext(CurContext); 9749 } 9750 9751 // If the decl has a non-null name, make accessible in the current scope. 9752 if (!D->getName().empty()) 9753 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9754 9755 // Similarly, dive into enums and fish their constants out, making them 9756 // accessible in this scope. 9757 if (auto *ED = dyn_cast<EnumDecl>(D)) { 9758 for (auto *EI : ED->enumerators()) 9759 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 9760 } 9761 } 9762 } 9763 9764 // Ensure that the function's exception specification is instantiated. 9765 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9766 ResolveExceptionSpec(D->getLocation(), FPT); 9767 9768 // Checking attributes of current function definition 9769 // dllimport attribute. 9770 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9771 if (DA && (!FD->hasAttr<DLLExportAttr>())) { 9772 // dllimport attribute cannot be directly applied to definition. 9773 // Microsoft accepts dllimport for functions defined within class scope. 9774 if (!DA->isInherited() && 9775 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9776 Diag(FD->getLocation(), 9777 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9778 << DA; 9779 FD->setInvalidDecl(); 9780 return D; 9781 } 9782 } 9783 // We want to attach documentation to original Decl (which might be 9784 // a function template). 9785 ActOnDocumentableDecl(D); 9786 return D; 9787 } 9788 9789 /// \brief Given the set of return statements within a function body, 9790 /// compute the variables that are subject to the named return value 9791 /// optimization. 9792 /// 9793 /// Each of the variables that is subject to the named return value 9794 /// optimization will be marked as NRVO variables in the AST, and any 9795 /// return statement that has a marked NRVO variable as its NRVO candidate can 9796 /// use the named return value optimization. 9797 /// 9798 /// This function applies a very simplistic algorithm for NRVO: if every return 9799 /// statement in the function has the same NRVO candidate, that candidate is 9800 /// the NRVO variable. 9801 /// 9802 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9803 /// statements and the lifetimes of the NRVO candidates. We should be able to 9804 /// find a maximal set of NRVO variables. 9805 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9806 ReturnStmt **Returns = Scope->Returns.data(); 9807 9808 const VarDecl *NRVOCandidate = 0; 9809 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9810 if (!Returns[I]->getNRVOCandidate()) 9811 return; 9812 9813 if (!NRVOCandidate) 9814 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9815 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9816 return; 9817 } 9818 9819 if (NRVOCandidate) 9820 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9821 } 9822 9823 bool Sema::canDelayFunctionBody(const Declarator &D) { 9824 // We can't delay parsing the body of a constexpr function template (yet). 9825 if (D.getDeclSpec().isConstexprSpecified()) 9826 return false; 9827 9828 // We can't delay parsing the body of a function template with a deduced 9829 // return type (yet). 9830 if (D.getDeclSpec().containsPlaceholderType()) { 9831 // If the placeholder introduces a non-deduced trailing return type, 9832 // we can still delay parsing it. 9833 if (D.getNumTypeObjects()) { 9834 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 9835 if (Outer.Kind == DeclaratorChunk::Function && 9836 Outer.Fun.hasTrailingReturnType()) { 9837 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 9838 return Ty.isNull() || !Ty->isUndeducedType(); 9839 } 9840 } 9841 return false; 9842 } 9843 9844 return true; 9845 } 9846 9847 bool Sema::canSkipFunctionBody(Decl *D) { 9848 // We cannot skip the body of a function (or function template) which is 9849 // constexpr, since we may need to evaluate its body in order to parse the 9850 // rest of the file. 9851 // We cannot skip the body of a function with an undeduced return type, 9852 // because any callers of that function need to know the type. 9853 if (const FunctionDecl *FD = D->getAsFunction()) 9854 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9855 return false; 9856 return Consumer.shouldSkipFunctionBody(D); 9857 } 9858 9859 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9860 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9861 FD->setHasSkippedBody(); 9862 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9863 MD->setHasSkippedBody(); 9864 return ActOnFinishFunctionBody(Decl, 0); 9865 } 9866 9867 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9868 return ActOnFinishFunctionBody(D, BodyArg, false); 9869 } 9870 9871 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9872 bool IsInstantiation) { 9873 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0; 9874 9875 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9876 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9877 9878 if (FD) { 9879 FD->setBody(Body); 9880 9881 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9882 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 9883 // If the function has a deduced result type but contains no 'return' 9884 // statements, the result type as written must be exactly 'auto', and 9885 // the deduced result type is 'void'. 9886 if (!FD->getReturnType()->getAs<AutoType>()) { 9887 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9888 << FD->getReturnType(); 9889 FD->setInvalidDecl(); 9890 } else { 9891 // Substitute 'void' for the 'auto' in the type. 9892 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9893 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 9894 Context.adjustDeducedFunctionResultType( 9895 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9896 } 9897 } 9898 9899 // The only way to be included in UndefinedButUsed is if there is an 9900 // ODR use before the definition. Avoid the expensive map lookup if this 9901 // is the first declaration. 9902 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9903 if (!FD->isExternallyVisible()) 9904 UndefinedButUsed.erase(FD); 9905 else if (FD->isInlined() && 9906 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9907 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9908 UndefinedButUsed.erase(FD); 9909 } 9910 9911 // If the function implicitly returns zero (like 'main') or is naked, 9912 // don't complain about missing return statements. 9913 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9914 WP.disableCheckFallThrough(); 9915 9916 // MSVC permits the use of pure specifier (=0) on function definition, 9917 // defined at class scope, warn about this non-standard construct. 9918 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9919 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9920 9921 if (!FD->isInvalidDecl()) { 9922 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9923 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9924 FD->getReturnType(), FD); 9925 9926 // If this is a constructor, we need a vtable. 9927 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9928 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9929 9930 // Try to apply the named return value optimization. We have to check 9931 // if we can do this here because lambdas keep return statements around 9932 // to deduce an implicit return type. 9933 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 9934 !FD->isDependentContext()) 9935 computeNRVO(Body, getCurFunction()); 9936 } 9937 9938 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9939 "Function parsing confused"); 9940 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9941 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9942 MD->setBody(Body); 9943 if (!MD->isInvalidDecl()) { 9944 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9945 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9946 MD->getReturnType(), MD); 9947 9948 if (Body) 9949 computeNRVO(Body, getCurFunction()); 9950 } 9951 if (getCurFunction()->ObjCShouldCallSuper) { 9952 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9953 << MD->getSelector().getAsString(); 9954 getCurFunction()->ObjCShouldCallSuper = false; 9955 } 9956 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 9957 const ObjCMethodDecl *InitMethod = 0; 9958 bool isDesignated = 9959 MD->isDesignatedInitializerForTheInterface(&InitMethod); 9960 assert(isDesignated && InitMethod); 9961 (void)isDesignated; 9962 9963 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 9964 auto IFace = MD->getClassInterface(); 9965 if (!IFace) 9966 return false; 9967 auto SuperD = IFace->getSuperClass(); 9968 if (!SuperD) 9969 return false; 9970 return SuperD->getIdentifier() == 9971 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 9972 }; 9973 // Don't issue this warning for unavailable inits or direct subclasses 9974 // of NSObject. 9975 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 9976 Diag(MD->getLocation(), 9977 diag::warn_objc_designated_init_missing_super_call); 9978 Diag(InitMethod->getLocation(), 9979 diag::note_objc_designated_init_marked_here); 9980 } 9981 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 9982 } 9983 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 9984 // Don't issue this warning for unavaialable inits. 9985 if (!MD->isUnavailable()) 9986 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 9987 getCurFunction()->ObjCWarnForNoInitDelegation = false; 9988 } 9989 } else { 9990 return 0; 9991 } 9992 9993 assert(!getCurFunction()->ObjCShouldCallSuper && 9994 "This should only be set for ObjC methods, which should have been " 9995 "handled in the block above."); 9996 9997 // Verify and clean out per-function state. 9998 if (Body) { 9999 // C++ constructors that have function-try-blocks can't have return 10000 // statements in the handlers of that block. (C++ [except.handle]p14) 10001 // Verify this. 10002 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10003 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10004 10005 // Verify that gotos and switch cases don't jump into scopes illegally. 10006 if (getCurFunction()->NeedsScopeChecking() && 10007 !dcl->isInvalidDecl() && 10008 !hasAnyUnrecoverableErrorsInThisFunction() && 10009 !PP.isCodeCompletionEnabled()) 10010 DiagnoseInvalidJumps(Body); 10011 10012 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10013 if (!Destructor->getParent()->isDependentType()) 10014 CheckDestructor(Destructor); 10015 10016 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10017 Destructor->getParent()); 10018 } 10019 10020 // If any errors have occurred, clear out any temporaries that may have 10021 // been leftover. This ensures that these temporaries won't be picked up for 10022 // deletion in some later function. 10023 if (PP.getDiagnostics().hasErrorOccurred() || 10024 PP.getDiagnostics().getSuppressAllDiagnostics()) { 10025 DiscardCleanupsInEvaluationContext(); 10026 } 10027 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 10028 !isa<FunctionTemplateDecl>(dcl)) { 10029 // Since the body is valid, issue any analysis-based warnings that are 10030 // enabled. 10031 ActivePolicy = &WP; 10032 } 10033 10034 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10035 (!CheckConstexprFunctionDecl(FD) || 10036 !CheckConstexprFunctionBody(FD, Body))) 10037 FD->setInvalidDecl(); 10038 10039 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 10040 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10041 assert(MaybeODRUseExprs.empty() && 10042 "Leftover expressions for odr-use checking"); 10043 } 10044 10045 if (!IsInstantiation) 10046 PopDeclContext(); 10047 10048 PopFunctionScopeInfo(ActivePolicy, dcl); 10049 // If any errors have occurred, clear out any temporaries that may have 10050 // been leftover. This ensures that these temporaries won't be picked up for 10051 // deletion in some later function. 10052 if (getDiagnostics().hasErrorOccurred()) { 10053 DiscardCleanupsInEvaluationContext(); 10054 } 10055 10056 return dcl; 10057 } 10058 10059 10060 /// When we finish delayed parsing of an attribute, we must attach it to the 10061 /// relevant Decl. 10062 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10063 ParsedAttributes &Attrs) { 10064 // Always attach attributes to the underlying decl. 10065 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10066 D = TD->getTemplatedDecl(); 10067 ProcessDeclAttributeList(S, D, Attrs.getList()); 10068 10069 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10070 if (Method->isStatic()) 10071 checkThisInStaticMemberFunctionAttributes(Method); 10072 } 10073 10074 10075 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10076 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10077 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10078 IdentifierInfo &II, Scope *S) { 10079 // Before we produce a declaration for an implicitly defined 10080 // function, see whether there was a locally-scoped declaration of 10081 // this name as a function or variable. If so, use that 10082 // (non-visible) declaration, and complain about it. 10083 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10084 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10085 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10086 return ExternCPrev; 10087 } 10088 10089 // Extension in C99. Legal in C90, but warn about it. 10090 unsigned diag_id; 10091 if (II.getName().startswith("__builtin_")) 10092 diag_id = diag::warn_builtin_unknown; 10093 else if (getLangOpts().C99) 10094 diag_id = diag::ext_implicit_function_decl; 10095 else 10096 diag_id = diag::warn_implicit_function_decl; 10097 Diag(Loc, diag_id) << &II; 10098 10099 // Because typo correction is expensive, only do it if the implicit 10100 // function declaration is going to be treated as an error. 10101 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10102 TypoCorrection Corrected; 10103 DeclFilterCCC<FunctionDecl> Validator; 10104 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 10105 LookupOrdinaryName, S, 0, Validator, 10106 CTK_NonError))) 10107 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10108 /*ErrorRecovery*/false); 10109 } 10110 10111 // Set a Declarator for the implicit definition: int foo(); 10112 const char *Dummy; 10113 AttributeFactory attrFactory; 10114 DeclSpec DS(attrFactory); 10115 unsigned DiagID; 10116 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10117 Context.getPrintingPolicy()); 10118 (void)Error; // Silence warning. 10119 assert(!Error && "Error setting up implicit decl!"); 10120 SourceLocation NoLoc; 10121 Declarator D(DS, Declarator::BlockContext); 10122 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10123 /*IsAmbiguous=*/false, 10124 /*LParenLoc=*/NoLoc, 10125 /*Params=*/0, 10126 /*NumParams=*/0, 10127 /*EllipsisLoc=*/NoLoc, 10128 /*RParenLoc=*/NoLoc, 10129 /*TypeQuals=*/0, 10130 /*RefQualifierIsLvalueRef=*/true, 10131 /*RefQualifierLoc=*/NoLoc, 10132 /*ConstQualifierLoc=*/NoLoc, 10133 /*VolatileQualifierLoc=*/NoLoc, 10134 /*MutableLoc=*/NoLoc, 10135 EST_None, 10136 /*ESpecLoc=*/NoLoc, 10137 /*Exceptions=*/0, 10138 /*ExceptionRanges=*/0, 10139 /*NumExceptions=*/0, 10140 /*NoexceptExpr=*/0, 10141 Loc, Loc, D), 10142 DS.getAttributes(), 10143 SourceLocation()); 10144 D.SetIdentifier(&II, Loc); 10145 10146 // Insert this function into translation-unit scope. 10147 10148 DeclContext *PrevDC = CurContext; 10149 CurContext = Context.getTranslationUnitDecl(); 10150 10151 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10152 FD->setImplicit(); 10153 10154 CurContext = PrevDC; 10155 10156 AddKnownFunctionAttributes(FD); 10157 10158 return FD; 10159 } 10160 10161 /// \brief Adds any function attributes that we know a priori based on 10162 /// the declaration of this function. 10163 /// 10164 /// These attributes can apply both to implicitly-declared builtins 10165 /// (like __builtin___printf_chk) or to library-declared functions 10166 /// like NSLog or printf. 10167 /// 10168 /// We need to check for duplicate attributes both here and where user-written 10169 /// attributes are applied to declarations. 10170 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10171 if (FD->isInvalidDecl()) 10172 return; 10173 10174 // If this is a built-in function, map its builtin attributes to 10175 // actual attributes. 10176 if (unsigned BuiltinID = FD->getBuiltinID()) { 10177 // Handle printf-formatting attributes. 10178 unsigned FormatIdx; 10179 bool HasVAListArg; 10180 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10181 if (!FD->hasAttr<FormatAttr>()) { 10182 const char *fmt = "printf"; 10183 unsigned int NumParams = FD->getNumParams(); 10184 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10185 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10186 fmt = "NSString"; 10187 FD->addAttr(FormatAttr::CreateImplicit(Context, 10188 &Context.Idents.get(fmt), 10189 FormatIdx+1, 10190 HasVAListArg ? 0 : FormatIdx+2, 10191 FD->getLocation())); 10192 } 10193 } 10194 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10195 HasVAListArg)) { 10196 if (!FD->hasAttr<FormatAttr>()) 10197 FD->addAttr(FormatAttr::CreateImplicit(Context, 10198 &Context.Idents.get("scanf"), 10199 FormatIdx+1, 10200 HasVAListArg ? 0 : FormatIdx+2, 10201 FD->getLocation())); 10202 } 10203 10204 // Mark const if we don't care about errno and that is the only 10205 // thing preventing the function from being const. This allows 10206 // IRgen to use LLVM intrinsics for such functions. 10207 if (!getLangOpts().MathErrno && 10208 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10209 if (!FD->hasAttr<ConstAttr>()) 10210 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10211 } 10212 10213 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10214 !FD->hasAttr<ReturnsTwiceAttr>()) 10215 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10216 FD->getLocation())); 10217 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10218 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10219 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10220 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10221 } 10222 10223 IdentifierInfo *Name = FD->getIdentifier(); 10224 if (!Name) 10225 return; 10226 if ((!getLangOpts().CPlusPlus && 10227 FD->getDeclContext()->isTranslationUnit()) || 10228 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10229 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10230 LinkageSpecDecl::lang_c)) { 10231 // Okay: this could be a libc/libm/Objective-C function we know 10232 // about. 10233 } else 10234 return; 10235 10236 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10237 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10238 // target-specific builtins, perhaps? 10239 if (!FD->hasAttr<FormatAttr>()) 10240 FD->addAttr(FormatAttr::CreateImplicit(Context, 10241 &Context.Idents.get("printf"), 2, 10242 Name->isStr("vasprintf") ? 0 : 3, 10243 FD->getLocation())); 10244 } 10245 10246 if (Name->isStr("__CFStringMakeConstantString")) { 10247 // We already have a __builtin___CFStringMakeConstantString, 10248 // but builds that use -fno-constant-cfstrings don't go through that. 10249 if (!FD->hasAttr<FormatArgAttr>()) 10250 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10251 FD->getLocation())); 10252 } 10253 } 10254 10255 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10256 TypeSourceInfo *TInfo) { 10257 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10258 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10259 10260 if (!TInfo) { 10261 assert(D.isInvalidType() && "no declarator info for valid type"); 10262 TInfo = Context.getTrivialTypeSourceInfo(T); 10263 } 10264 10265 // Scope manipulation handled by caller. 10266 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10267 D.getLocStart(), 10268 D.getIdentifierLoc(), 10269 D.getIdentifier(), 10270 TInfo); 10271 10272 // Bail out immediately if we have an invalid declaration. 10273 if (D.isInvalidType()) { 10274 NewTD->setInvalidDecl(); 10275 return NewTD; 10276 } 10277 10278 if (D.getDeclSpec().isModulePrivateSpecified()) { 10279 if (CurContext->isFunctionOrMethod()) 10280 Diag(NewTD->getLocation(), diag::err_module_private_local) 10281 << 2 << NewTD->getDeclName() 10282 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10283 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10284 else 10285 NewTD->setModulePrivate(); 10286 } 10287 10288 // C++ [dcl.typedef]p8: 10289 // If the typedef declaration defines an unnamed class (or 10290 // enum), the first typedef-name declared by the declaration 10291 // to be that class type (or enum type) is used to denote the 10292 // class type (or enum type) for linkage purposes only. 10293 // We need to check whether the type was declared in the declaration. 10294 switch (D.getDeclSpec().getTypeSpecType()) { 10295 case TST_enum: 10296 case TST_struct: 10297 case TST_interface: 10298 case TST_union: 10299 case TST_class: { 10300 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10301 10302 // Do nothing if the tag is not anonymous or already has an 10303 // associated typedef (from an earlier typedef in this decl group). 10304 if (tagFromDeclSpec->getIdentifier()) break; 10305 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10306 10307 // A well-formed anonymous tag must always be a TUK_Definition. 10308 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10309 10310 // The type must match the tag exactly; no qualifiers allowed. 10311 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10312 break; 10313 10314 // If we've already computed linkage for the anonymous tag, then 10315 // adding a typedef name for the anonymous decl can change that 10316 // linkage, which might be a serious problem. Diagnose this as 10317 // unsupported and ignore the typedef name. TODO: we should 10318 // pursue this as a language defect and establish a formal rule 10319 // for how to handle it. 10320 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10321 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10322 10323 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10324 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(), 10325 getLangOpts()); 10326 10327 llvm::SmallString<40> textToInsert; 10328 textToInsert += ' '; 10329 textToInsert += D.getIdentifier()->getName(); 10330 Diag(tagLoc, diag::note_typedef_changes_linkage) 10331 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10332 break; 10333 } 10334 10335 // Otherwise, set this is the anon-decl typedef for the tag. 10336 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10337 break; 10338 } 10339 10340 default: 10341 break; 10342 } 10343 10344 return NewTD; 10345 } 10346 10347 10348 /// \brief Check that this is a valid underlying type for an enum declaration. 10349 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10350 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10351 QualType T = TI->getType(); 10352 10353 if (T->isDependentType()) 10354 return false; 10355 10356 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10357 if (BT->isInteger()) 10358 return false; 10359 10360 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10361 return true; 10362 } 10363 10364 /// Check whether this is a valid redeclaration of a previous enumeration. 10365 /// \return true if the redeclaration was invalid. 10366 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10367 QualType EnumUnderlyingTy, 10368 const EnumDecl *Prev) { 10369 bool IsFixed = !EnumUnderlyingTy.isNull(); 10370 10371 if (IsScoped != Prev->isScoped()) { 10372 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10373 << Prev->isScoped(); 10374 Diag(Prev->getLocation(), diag::note_previous_declaration); 10375 return true; 10376 } 10377 10378 if (IsFixed && Prev->isFixed()) { 10379 if (!EnumUnderlyingTy->isDependentType() && 10380 !Prev->getIntegerType()->isDependentType() && 10381 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10382 Prev->getIntegerType())) { 10383 // TODO: Highlight the underlying type of the redeclaration. 10384 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10385 << EnumUnderlyingTy << Prev->getIntegerType(); 10386 Diag(Prev->getLocation(), diag::note_previous_declaration) 10387 << Prev->getIntegerTypeRange(); 10388 return true; 10389 } 10390 } else if (IsFixed != Prev->isFixed()) { 10391 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10392 << Prev->isFixed(); 10393 Diag(Prev->getLocation(), diag::note_previous_declaration); 10394 return true; 10395 } 10396 10397 return false; 10398 } 10399 10400 /// \brief Get diagnostic %select index for tag kind for 10401 /// redeclaration diagnostic message. 10402 /// WARNING: Indexes apply to particular diagnostics only! 10403 /// 10404 /// \returns diagnostic %select index. 10405 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10406 switch (Tag) { 10407 case TTK_Struct: return 0; 10408 case TTK_Interface: return 1; 10409 case TTK_Class: return 2; 10410 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10411 } 10412 } 10413 10414 /// \brief Determine if tag kind is a class-key compatible with 10415 /// class for redeclaration (class, struct, or __interface). 10416 /// 10417 /// \returns true iff the tag kind is compatible. 10418 static bool isClassCompatTagKind(TagTypeKind Tag) 10419 { 10420 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10421 } 10422 10423 /// \brief Determine whether a tag with a given kind is acceptable 10424 /// as a redeclaration of the given tag declaration. 10425 /// 10426 /// \returns true if the new tag kind is acceptable, false otherwise. 10427 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10428 TagTypeKind NewTag, bool isDefinition, 10429 SourceLocation NewTagLoc, 10430 const IdentifierInfo &Name) { 10431 // C++ [dcl.type.elab]p3: 10432 // The class-key or enum keyword present in the 10433 // elaborated-type-specifier shall agree in kind with the 10434 // declaration to which the name in the elaborated-type-specifier 10435 // refers. This rule also applies to the form of 10436 // elaborated-type-specifier that declares a class-name or 10437 // friend class since it can be construed as referring to the 10438 // definition of the class. Thus, in any 10439 // elaborated-type-specifier, the enum keyword shall be used to 10440 // refer to an enumeration (7.2), the union class-key shall be 10441 // used to refer to a union (clause 9), and either the class or 10442 // struct class-key shall be used to refer to a class (clause 9) 10443 // declared using the class or struct class-key. 10444 TagTypeKind OldTag = Previous->getTagKind(); 10445 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10446 if (OldTag == NewTag) 10447 return true; 10448 10449 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10450 // Warn about the struct/class tag mismatch. 10451 bool isTemplate = false; 10452 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10453 isTemplate = Record->getDescribedClassTemplate(); 10454 10455 if (!ActiveTemplateInstantiations.empty()) { 10456 // In a template instantiation, do not offer fix-its for tag mismatches 10457 // since they usually mess up the template instead of fixing the problem. 10458 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10459 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10460 << getRedeclDiagFromTagKind(OldTag); 10461 return true; 10462 } 10463 10464 if (isDefinition) { 10465 // On definitions, check previous tags and issue a fix-it for each 10466 // one that doesn't match the current tag. 10467 if (Previous->getDefinition()) { 10468 // Don't suggest fix-its for redefinitions. 10469 return true; 10470 } 10471 10472 bool previousMismatch = false; 10473 for (auto I : Previous->redecls()) { 10474 if (I->getTagKind() != NewTag) { 10475 if (!previousMismatch) { 10476 previousMismatch = true; 10477 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10478 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10479 << getRedeclDiagFromTagKind(I->getTagKind()); 10480 } 10481 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10482 << getRedeclDiagFromTagKind(NewTag) 10483 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10484 TypeWithKeyword::getTagTypeKindName(NewTag)); 10485 } 10486 } 10487 return true; 10488 } 10489 10490 // Check for a previous definition. If current tag and definition 10491 // are same type, do nothing. If no definition, but disagree with 10492 // with previous tag type, give a warning, but no fix-it. 10493 const TagDecl *Redecl = Previous->getDefinition() ? 10494 Previous->getDefinition() : Previous; 10495 if (Redecl->getTagKind() == NewTag) { 10496 return true; 10497 } 10498 10499 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10500 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10501 << getRedeclDiagFromTagKind(OldTag); 10502 Diag(Redecl->getLocation(), diag::note_previous_use); 10503 10504 // If there is a previous definition, suggest a fix-it. 10505 if (Previous->getDefinition()) { 10506 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10507 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10508 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10509 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10510 } 10511 10512 return true; 10513 } 10514 return false; 10515 } 10516 10517 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10518 /// former case, Name will be non-null. In the later case, Name will be null. 10519 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10520 /// reference/declaration/definition of a tag. 10521 /// 10522 /// IsTypeSpecifier is true if this is a type-specifier (or 10523 /// trailing-type-specifier) other than one in an alias-declaration. 10524 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10525 SourceLocation KWLoc, CXXScopeSpec &SS, 10526 IdentifierInfo *Name, SourceLocation NameLoc, 10527 AttributeList *Attr, AccessSpecifier AS, 10528 SourceLocation ModulePrivateLoc, 10529 MultiTemplateParamsArg TemplateParameterLists, 10530 bool &OwnedDecl, bool &IsDependent, 10531 SourceLocation ScopedEnumKWLoc, 10532 bool ScopedEnumUsesClassTag, 10533 TypeResult UnderlyingType, 10534 bool IsTypeSpecifier) { 10535 // If this is not a definition, it must have a name. 10536 IdentifierInfo *OrigName = Name; 10537 assert((Name != 0 || TUK == TUK_Definition) && 10538 "Nameless record must be a definition!"); 10539 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10540 10541 OwnedDecl = false; 10542 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10543 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10544 10545 // FIXME: Check explicit specializations more carefully. 10546 bool isExplicitSpecialization = false; 10547 bool Invalid = false; 10548 10549 // We only need to do this matching if we have template parameters 10550 // or a scope specifier, which also conveniently avoids this work 10551 // for non-C++ cases. 10552 if (TemplateParameterLists.size() > 0 || 10553 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10554 if (TemplateParameterList *TemplateParams = 10555 MatchTemplateParametersToScopeSpecifier( 10556 KWLoc, NameLoc, SS, 0, TemplateParameterLists, 10557 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 10558 if (Kind == TTK_Enum) { 10559 Diag(KWLoc, diag::err_enum_template); 10560 return 0; 10561 } 10562 10563 if (TemplateParams->size() > 0) { 10564 // This is a declaration or definition of a class template (which may 10565 // be a member of another template). 10566 10567 if (Invalid) 10568 return 0; 10569 10570 OwnedDecl = false; 10571 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10572 SS, Name, NameLoc, Attr, 10573 TemplateParams, AS, 10574 ModulePrivateLoc, 10575 TemplateParameterLists.size()-1, 10576 TemplateParameterLists.data()); 10577 return Result.get(); 10578 } else { 10579 // The "template<>" header is extraneous. 10580 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10581 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10582 isExplicitSpecialization = true; 10583 } 10584 } 10585 } 10586 10587 // Figure out the underlying type if this a enum declaration. We need to do 10588 // this early, because it's needed to detect if this is an incompatible 10589 // redeclaration. 10590 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10591 10592 if (Kind == TTK_Enum) { 10593 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10594 // No underlying type explicitly specified, or we failed to parse the 10595 // type, default to int. 10596 EnumUnderlying = Context.IntTy.getTypePtr(); 10597 else if (UnderlyingType.get()) { 10598 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10599 // integral type; any cv-qualification is ignored. 10600 TypeSourceInfo *TI = 0; 10601 GetTypeFromParser(UnderlyingType.get(), &TI); 10602 EnumUnderlying = TI; 10603 10604 if (CheckEnumUnderlyingType(TI)) 10605 // Recover by falling back to int. 10606 EnumUnderlying = Context.IntTy.getTypePtr(); 10607 10608 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10609 UPPC_FixedUnderlyingType)) 10610 EnumUnderlying = Context.IntTy.getTypePtr(); 10611 10612 } else if (getLangOpts().MSVCCompat) 10613 // Microsoft enums are always of int type. 10614 EnumUnderlying = Context.IntTy.getTypePtr(); 10615 } 10616 10617 DeclContext *SearchDC = CurContext; 10618 DeclContext *DC = CurContext; 10619 bool isStdBadAlloc = false; 10620 10621 RedeclarationKind Redecl = ForRedeclaration; 10622 if (TUK == TUK_Friend || TUK == TUK_Reference) 10623 Redecl = NotForRedeclaration; 10624 10625 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10626 bool FriendSawTagOutsideEnclosingNamespace = false; 10627 if (Name && SS.isNotEmpty()) { 10628 // We have a nested-name tag ('struct foo::bar'). 10629 10630 // Check for invalid 'foo::'. 10631 if (SS.isInvalid()) { 10632 Name = 0; 10633 goto CreateNewDecl; 10634 } 10635 10636 // If this is a friend or a reference to a class in a dependent 10637 // context, don't try to make a decl for it. 10638 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10639 DC = computeDeclContext(SS, false); 10640 if (!DC) { 10641 IsDependent = true; 10642 return 0; 10643 } 10644 } else { 10645 DC = computeDeclContext(SS, true); 10646 if (!DC) { 10647 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10648 << SS.getRange(); 10649 return 0; 10650 } 10651 } 10652 10653 if (RequireCompleteDeclContext(SS, DC)) 10654 return 0; 10655 10656 SearchDC = DC; 10657 // Look-up name inside 'foo::'. 10658 LookupQualifiedName(Previous, DC); 10659 10660 if (Previous.isAmbiguous()) 10661 return 0; 10662 10663 if (Previous.empty()) { 10664 // Name lookup did not find anything. However, if the 10665 // nested-name-specifier refers to the current instantiation, 10666 // and that current instantiation has any dependent base 10667 // classes, we might find something at instantiation time: treat 10668 // this as a dependent elaborated-type-specifier. 10669 // But this only makes any sense for reference-like lookups. 10670 if (Previous.wasNotFoundInCurrentInstantiation() && 10671 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10672 IsDependent = true; 10673 return 0; 10674 } 10675 10676 // A tag 'foo::bar' must already exist. 10677 Diag(NameLoc, diag::err_not_tag_in_scope) 10678 << Kind << Name << DC << SS.getRange(); 10679 Name = 0; 10680 Invalid = true; 10681 goto CreateNewDecl; 10682 } 10683 } else if (Name) { 10684 // If this is a named struct, check to see if there was a previous forward 10685 // declaration or definition. 10686 // FIXME: We're looking into outer scopes here, even when we 10687 // shouldn't be. Doing so can result in ambiguities that we 10688 // shouldn't be diagnosing. 10689 LookupName(Previous, S); 10690 10691 // When declaring or defining a tag, ignore ambiguities introduced 10692 // by types using'ed into this scope. 10693 if (Previous.isAmbiguous() && 10694 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10695 LookupResult::Filter F = Previous.makeFilter(); 10696 while (F.hasNext()) { 10697 NamedDecl *ND = F.next(); 10698 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10699 F.erase(); 10700 } 10701 F.done(); 10702 } 10703 10704 // C++11 [namespace.memdef]p3: 10705 // If the name in a friend declaration is neither qualified nor 10706 // a template-id and the declaration is a function or an 10707 // elaborated-type-specifier, the lookup to determine whether 10708 // the entity has been previously declared shall not consider 10709 // any scopes outside the innermost enclosing namespace. 10710 // 10711 // Does it matter that this should be by scope instead of by 10712 // semantic context? 10713 if (!Previous.empty() && TUK == TUK_Friend) { 10714 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10715 LookupResult::Filter F = Previous.makeFilter(); 10716 while (F.hasNext()) { 10717 NamedDecl *ND = F.next(); 10718 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10719 if (DC->isFileContext() && 10720 !EnclosingNS->Encloses(ND->getDeclContext())) { 10721 F.erase(); 10722 FriendSawTagOutsideEnclosingNamespace = true; 10723 } 10724 } 10725 F.done(); 10726 } 10727 10728 // Note: there used to be some attempt at recovery here. 10729 if (Previous.isAmbiguous()) 10730 return 0; 10731 10732 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10733 // FIXME: This makes sure that we ignore the contexts associated 10734 // with C structs, unions, and enums when looking for a matching 10735 // tag declaration or definition. See the similar lookup tweak 10736 // in Sema::LookupName; is there a better way to deal with this? 10737 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10738 SearchDC = SearchDC->getParent(); 10739 } 10740 } else if (S->isFunctionPrototypeScope()) { 10741 // If this is an enum declaration in function prototype scope, set its 10742 // initial context to the translation unit. 10743 // FIXME: [citation needed] 10744 SearchDC = Context.getTranslationUnitDecl(); 10745 } 10746 10747 if (Previous.isSingleResult() && 10748 Previous.getFoundDecl()->isTemplateParameter()) { 10749 // Maybe we will complain about the shadowed template parameter. 10750 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10751 // Just pretend that we didn't see the previous declaration. 10752 Previous.clear(); 10753 } 10754 10755 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10756 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10757 // This is a declaration of or a reference to "std::bad_alloc". 10758 isStdBadAlloc = true; 10759 10760 if (Previous.empty() && StdBadAlloc) { 10761 // std::bad_alloc has been implicitly declared (but made invisible to 10762 // name lookup). Fill in this implicit declaration as the previous 10763 // declaration, so that the declarations get chained appropriately. 10764 Previous.addDecl(getStdBadAlloc()); 10765 } 10766 } 10767 10768 // If we didn't find a previous declaration, and this is a reference 10769 // (or friend reference), move to the correct scope. In C++, we 10770 // also need to do a redeclaration lookup there, just in case 10771 // there's a shadow friend decl. 10772 if (Name && Previous.empty() && 10773 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10774 if (Invalid) goto CreateNewDecl; 10775 assert(SS.isEmpty()); 10776 10777 if (TUK == TUK_Reference) { 10778 // C++ [basic.scope.pdecl]p5: 10779 // -- for an elaborated-type-specifier of the form 10780 // 10781 // class-key identifier 10782 // 10783 // if the elaborated-type-specifier is used in the 10784 // decl-specifier-seq or parameter-declaration-clause of a 10785 // function defined in namespace scope, the identifier is 10786 // declared as a class-name in the namespace that contains 10787 // the declaration; otherwise, except as a friend 10788 // declaration, the identifier is declared in the smallest 10789 // non-class, non-function-prototype scope that contains the 10790 // declaration. 10791 // 10792 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10793 // C structs and unions. 10794 // 10795 // It is an error in C++ to declare (rather than define) an enum 10796 // type, including via an elaborated type specifier. We'll 10797 // diagnose that later; for now, declare the enum in the same 10798 // scope as we would have picked for any other tag type. 10799 // 10800 // GNU C also supports this behavior as part of its incomplete 10801 // enum types extension, while GNU C++ does not. 10802 // 10803 // Find the context where we'll be declaring the tag. 10804 // FIXME: We would like to maintain the current DeclContext as the 10805 // lexical context, 10806 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10807 SearchDC = SearchDC->getParent(); 10808 10809 // Find the scope where we'll be declaring the tag. 10810 while (S->isClassScope() || 10811 (getLangOpts().CPlusPlus && 10812 S->isFunctionPrototypeScope()) || 10813 ((S->getFlags() & Scope::DeclScope) == 0) || 10814 (S->getEntity() && S->getEntity()->isTransparentContext())) 10815 S = S->getParent(); 10816 } else { 10817 assert(TUK == TUK_Friend); 10818 // C++ [namespace.memdef]p3: 10819 // If a friend declaration in a non-local class first declares a 10820 // class or function, the friend class or function is a member of 10821 // the innermost enclosing namespace. 10822 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10823 } 10824 10825 // In C++, we need to do a redeclaration lookup to properly 10826 // diagnose some problems. 10827 if (getLangOpts().CPlusPlus) { 10828 Previous.setRedeclarationKind(ForRedeclaration); 10829 LookupQualifiedName(Previous, SearchDC); 10830 } 10831 } 10832 10833 if (!Previous.empty()) { 10834 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10835 NamedDecl *DirectPrevDecl = 10836 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10837 10838 // It's okay to have a tag decl in the same scope as a typedef 10839 // which hides a tag decl in the same scope. Finding this 10840 // insanity with a redeclaration lookup can only actually happen 10841 // in C++. 10842 // 10843 // This is also okay for elaborated-type-specifiers, which is 10844 // technically forbidden by the current standard but which is 10845 // okay according to the likely resolution of an open issue; 10846 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10847 if (getLangOpts().CPlusPlus) { 10848 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10849 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10850 TagDecl *Tag = TT->getDecl(); 10851 if (Tag->getDeclName() == Name && 10852 Tag->getDeclContext()->getRedeclContext() 10853 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10854 PrevDecl = Tag; 10855 Previous.clear(); 10856 Previous.addDecl(Tag); 10857 Previous.resolveKind(); 10858 } 10859 } 10860 } 10861 } 10862 10863 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10864 // If this is a use of a previous tag, or if the tag is already declared 10865 // in the same scope (so that the definition/declaration completes or 10866 // rementions the tag), reuse the decl. 10867 if (TUK == TUK_Reference || TUK == TUK_Friend || 10868 isDeclInScope(DirectPrevDecl, SearchDC, S, 10869 SS.isNotEmpty() || isExplicitSpecialization)) { 10870 // Make sure that this wasn't declared as an enum and now used as a 10871 // struct or something similar. 10872 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10873 TUK == TUK_Definition, KWLoc, 10874 *Name)) { 10875 bool SafeToContinue 10876 = (PrevTagDecl->getTagKind() != TTK_Enum && 10877 Kind != TTK_Enum); 10878 if (SafeToContinue) 10879 Diag(KWLoc, diag::err_use_with_wrong_tag) 10880 << Name 10881 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10882 PrevTagDecl->getKindName()); 10883 else 10884 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10885 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10886 10887 if (SafeToContinue) 10888 Kind = PrevTagDecl->getTagKind(); 10889 else { 10890 // Recover by making this an anonymous redefinition. 10891 Name = 0; 10892 Previous.clear(); 10893 Invalid = true; 10894 } 10895 } 10896 10897 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10898 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10899 10900 // If this is an elaborated-type-specifier for a scoped enumeration, 10901 // the 'class' keyword is not necessary and not permitted. 10902 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10903 if (ScopedEnum) 10904 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10905 << PrevEnum->isScoped() 10906 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10907 return PrevTagDecl; 10908 } 10909 10910 QualType EnumUnderlyingTy; 10911 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10912 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 10913 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10914 EnumUnderlyingTy = QualType(T, 0); 10915 10916 // All conflicts with previous declarations are recovered by 10917 // returning the previous declaration, unless this is a definition, 10918 // in which case we want the caller to bail out. 10919 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10920 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10921 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10922 } 10923 10924 // C++11 [class.mem]p1: 10925 // A member shall not be declared twice in the member-specification, 10926 // except that a nested class or member class template can be declared 10927 // and then later defined. 10928 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10929 S->isDeclScope(PrevDecl)) { 10930 Diag(NameLoc, diag::ext_member_redeclared); 10931 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10932 } 10933 10934 if (!Invalid) { 10935 // If this is a use, just return the declaration we found. 10936 10937 // FIXME: In the future, return a variant or some other clue 10938 // for the consumer of this Decl to know it doesn't own it. 10939 // For our current ASTs this shouldn't be a problem, but will 10940 // need to be changed with DeclGroups. 10941 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10942 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10943 return PrevTagDecl; 10944 10945 // Diagnose attempts to redefine a tag. 10946 if (TUK == TUK_Definition) { 10947 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10948 // If we're defining a specialization and the previous definition 10949 // is from an implicit instantiation, don't emit an error 10950 // here; we'll catch this in the general case below. 10951 bool IsExplicitSpecializationAfterInstantiation = false; 10952 if (isExplicitSpecialization) { 10953 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10954 IsExplicitSpecializationAfterInstantiation = 10955 RD->getTemplateSpecializationKind() != 10956 TSK_ExplicitSpecialization; 10957 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10958 IsExplicitSpecializationAfterInstantiation = 10959 ED->getTemplateSpecializationKind() != 10960 TSK_ExplicitSpecialization; 10961 } 10962 10963 if (!IsExplicitSpecializationAfterInstantiation) { 10964 // A redeclaration in function prototype scope in C isn't 10965 // visible elsewhere, so merely issue a warning. 10966 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10967 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10968 else 10969 Diag(NameLoc, diag::err_redefinition) << Name; 10970 Diag(Def->getLocation(), diag::note_previous_definition); 10971 // If this is a redefinition, recover by making this 10972 // struct be anonymous, which will make any later 10973 // references get the previous definition. 10974 Name = 0; 10975 Previous.clear(); 10976 Invalid = true; 10977 } 10978 } else { 10979 // If the type is currently being defined, complain 10980 // about a nested redefinition. 10981 const TagType *Tag 10982 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10983 if (Tag->isBeingDefined()) { 10984 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10985 Diag(PrevTagDecl->getLocation(), 10986 diag::note_previous_definition); 10987 Name = 0; 10988 Previous.clear(); 10989 Invalid = true; 10990 } 10991 } 10992 10993 // Okay, this is definition of a previously declared or referenced 10994 // tag PrevDecl. We're going to create a new Decl for it. 10995 } 10996 } 10997 // If we get here we have (another) forward declaration or we 10998 // have a definition. Just create a new decl. 10999 11000 } else { 11001 // If we get here, this is a definition of a new tag type in a nested 11002 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11003 // new decl/type. We set PrevDecl to NULL so that the entities 11004 // have distinct types. 11005 Previous.clear(); 11006 } 11007 // If we get here, we're going to create a new Decl. If PrevDecl 11008 // is non-NULL, it's a definition of the tag declared by 11009 // PrevDecl. If it's NULL, we have a new definition. 11010 11011 11012 // Otherwise, PrevDecl is not a tag, but was found with tag 11013 // lookup. This is only actually possible in C++, where a few 11014 // things like templates still live in the tag namespace. 11015 } else { 11016 // Use a better diagnostic if an elaborated-type-specifier 11017 // found the wrong kind of type on the first 11018 // (non-redeclaration) lookup. 11019 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11020 !Previous.isForRedeclaration()) { 11021 unsigned Kind = 0; 11022 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11023 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11024 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11025 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11026 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11027 Invalid = true; 11028 11029 // Otherwise, only diagnose if the declaration is in scope. 11030 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11031 SS.isNotEmpty() || isExplicitSpecialization)) { 11032 // do nothing 11033 11034 // Diagnose implicit declarations introduced by elaborated types. 11035 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11036 unsigned Kind = 0; 11037 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11038 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11039 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11040 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11041 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11042 Invalid = true; 11043 11044 // Otherwise it's a declaration. Call out a particularly common 11045 // case here. 11046 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11047 unsigned Kind = 0; 11048 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11049 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11050 << Name << Kind << TND->getUnderlyingType(); 11051 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11052 Invalid = true; 11053 11054 // Otherwise, diagnose. 11055 } else { 11056 // The tag name clashes with something else in the target scope, 11057 // issue an error and recover by making this tag be anonymous. 11058 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11059 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11060 Name = 0; 11061 Invalid = true; 11062 } 11063 11064 // The existing declaration isn't relevant to us; we're in a 11065 // new scope, so clear out the previous declaration. 11066 Previous.clear(); 11067 } 11068 } 11069 11070 CreateNewDecl: 11071 11072 TagDecl *PrevDecl = 0; 11073 if (Previous.isSingleResult()) 11074 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11075 11076 // If there is an identifier, use the location of the identifier as the 11077 // location of the decl, otherwise use the location of the struct/union 11078 // keyword. 11079 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11080 11081 // Otherwise, create a new declaration. If there is a previous 11082 // declaration of the same entity, the two will be linked via 11083 // PrevDecl. 11084 TagDecl *New; 11085 11086 bool IsForwardReference = false; 11087 if (Kind == TTK_Enum) { 11088 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11089 // enum X { A, B, C } D; D should chain to X. 11090 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11091 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11092 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11093 // If this is an undefined enum, warn. 11094 if (TUK != TUK_Definition && !Invalid) { 11095 TagDecl *Def; 11096 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11097 cast<EnumDecl>(New)->isFixed()) { 11098 // C++0x: 7.2p2: opaque-enum-declaration. 11099 // Conflicts are diagnosed above. Do nothing. 11100 } 11101 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11102 Diag(Loc, diag::ext_forward_ref_enum_def) 11103 << New; 11104 Diag(Def->getLocation(), diag::note_previous_definition); 11105 } else { 11106 unsigned DiagID = diag::ext_forward_ref_enum; 11107 if (getLangOpts().MSVCCompat) 11108 DiagID = diag::ext_ms_forward_ref_enum; 11109 else if (getLangOpts().CPlusPlus) 11110 DiagID = diag::err_forward_ref_enum; 11111 Diag(Loc, DiagID); 11112 11113 // If this is a forward-declared reference to an enumeration, make a 11114 // note of it; we won't actually be introducing the declaration into 11115 // the declaration context. 11116 if (TUK == TUK_Reference) 11117 IsForwardReference = true; 11118 } 11119 } 11120 11121 if (EnumUnderlying) { 11122 EnumDecl *ED = cast<EnumDecl>(New); 11123 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11124 ED->setIntegerTypeSourceInfo(TI); 11125 else 11126 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11127 ED->setPromotionType(ED->getIntegerType()); 11128 } 11129 11130 } else { 11131 // struct/union/class 11132 11133 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11134 // struct X { int A; } D; D should chain to X. 11135 if (getLangOpts().CPlusPlus) { 11136 // FIXME: Look for a way to use RecordDecl for simple structs. 11137 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11138 cast_or_null<CXXRecordDecl>(PrevDecl)); 11139 11140 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11141 StdBadAlloc = cast<CXXRecordDecl>(New); 11142 } else 11143 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11144 cast_or_null<RecordDecl>(PrevDecl)); 11145 } 11146 11147 // C++11 [dcl.type]p3: 11148 // A type-specifier-seq shall not define a class or enumeration [...]. 11149 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11150 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11151 << Context.getTagDeclType(New); 11152 Invalid = true; 11153 } 11154 11155 // Maybe add qualifier info. 11156 if (SS.isNotEmpty()) { 11157 if (SS.isSet()) { 11158 // If this is either a declaration or a definition, check the 11159 // nested-name-specifier against the current context. We don't do this 11160 // for explicit specializations, because they have similar checking 11161 // (with more specific diagnostics) in the call to 11162 // CheckMemberSpecialization, below. 11163 if (!isExplicitSpecialization && 11164 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11165 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11166 Invalid = true; 11167 11168 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11169 if (TemplateParameterLists.size() > 0) { 11170 New->setTemplateParameterListsInfo(Context, 11171 TemplateParameterLists.size(), 11172 TemplateParameterLists.data()); 11173 } 11174 } 11175 else 11176 Invalid = true; 11177 } 11178 11179 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11180 // Add alignment attributes if necessary; these attributes are checked when 11181 // the ASTContext lays out the structure. 11182 // 11183 // It is important for implementing the correct semantics that this 11184 // happen here (in act on tag decl). The #pragma pack stack is 11185 // maintained as a result of parser callbacks which can occur at 11186 // many points during the parsing of a struct declaration (because 11187 // the #pragma tokens are effectively skipped over during the 11188 // parsing of the struct). 11189 if (TUK == TUK_Definition) { 11190 AddAlignmentAttributesForRecord(RD); 11191 AddMsStructLayoutForRecord(RD); 11192 } 11193 } 11194 11195 if (ModulePrivateLoc.isValid()) { 11196 if (isExplicitSpecialization) 11197 Diag(New->getLocation(), diag::err_module_private_specialization) 11198 << 2 11199 << FixItHint::CreateRemoval(ModulePrivateLoc); 11200 // __module_private__ does not apply to local classes. However, we only 11201 // diagnose this as an error when the declaration specifiers are 11202 // freestanding. Here, we just ignore the __module_private__. 11203 else if (!SearchDC->isFunctionOrMethod()) 11204 New->setModulePrivate(); 11205 } 11206 11207 // If this is a specialization of a member class (of a class template), 11208 // check the specialization. 11209 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11210 Invalid = true; 11211 11212 if (Invalid) 11213 New->setInvalidDecl(); 11214 11215 if (Attr) 11216 ProcessDeclAttributeList(S, New, Attr); 11217 11218 // If we're declaring or defining a tag in function prototype scope in C, 11219 // note that this type can only be used within the function and add it to 11220 // the list of decls to inject into the function definition scope. 11221 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) && 11222 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11223 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11224 DeclsInPrototypeScope.push_back(New); 11225 } 11226 11227 // Set the lexical context. If the tag has a C++ scope specifier, the 11228 // lexical context will be different from the semantic context. 11229 New->setLexicalDeclContext(CurContext); 11230 11231 // Mark this as a friend decl if applicable. 11232 // In Microsoft mode, a friend declaration also acts as a forward 11233 // declaration so we always pass true to setObjectOfFriendDecl to make 11234 // the tag name visible. 11235 if (TUK == TUK_Friend) 11236 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11237 getLangOpts().MicrosoftExt); 11238 11239 // Set the access specifier. 11240 if (!Invalid && SearchDC->isRecord()) 11241 SetMemberAccessSpecifier(New, PrevDecl, AS); 11242 11243 if (TUK == TUK_Definition) 11244 New->startDefinition(); 11245 11246 // If this has an identifier, add it to the scope stack. 11247 if (TUK == TUK_Friend) { 11248 // We might be replacing an existing declaration in the lookup tables; 11249 // if so, borrow its access specifier. 11250 if (PrevDecl) 11251 New->setAccess(PrevDecl->getAccess()); 11252 11253 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11254 DC->makeDeclVisibleInContext(New); 11255 if (Name) // can be null along some error paths 11256 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11257 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11258 } else if (Name) { 11259 S = getNonFieldDeclScope(S); 11260 PushOnScopeChains(New, S, !IsForwardReference); 11261 if (IsForwardReference) 11262 SearchDC->makeDeclVisibleInContext(New); 11263 11264 } else { 11265 CurContext->addDecl(New); 11266 } 11267 11268 // If this is the C FILE type, notify the AST context. 11269 if (IdentifierInfo *II = New->getIdentifier()) 11270 if (!New->isInvalidDecl() && 11271 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11272 II->isStr("FILE")) 11273 Context.setFILEDecl(New); 11274 11275 if (PrevDecl) 11276 mergeDeclAttributes(New, PrevDecl); 11277 11278 // If there's a #pragma GCC visibility in scope, set the visibility of this 11279 // record. 11280 AddPushedVisibilityAttribute(New); 11281 11282 OwnedDecl = true; 11283 // In C++, don't return an invalid declaration. We can't recover well from 11284 // the cases where we make the type anonymous. 11285 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11286 } 11287 11288 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11289 AdjustDeclIfTemplate(TagD); 11290 TagDecl *Tag = cast<TagDecl>(TagD); 11291 11292 // Enter the tag context. 11293 PushDeclContext(S, Tag); 11294 11295 ActOnDocumentableDecl(TagD); 11296 11297 // If there's a #pragma GCC visibility in scope, set the visibility of this 11298 // record. 11299 AddPushedVisibilityAttribute(Tag); 11300 } 11301 11302 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11303 assert(isa<ObjCContainerDecl>(IDecl) && 11304 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11305 DeclContext *OCD = cast<DeclContext>(IDecl); 11306 assert(getContainingDC(OCD) == CurContext && 11307 "The next DeclContext should be lexically contained in the current one."); 11308 CurContext = OCD; 11309 return IDecl; 11310 } 11311 11312 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11313 SourceLocation FinalLoc, 11314 bool IsFinalSpelledSealed, 11315 SourceLocation LBraceLoc) { 11316 AdjustDeclIfTemplate(TagD); 11317 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11318 11319 FieldCollector->StartClass(); 11320 11321 if (!Record->getIdentifier()) 11322 return; 11323 11324 if (FinalLoc.isValid()) 11325 Record->addAttr(new (Context) 11326 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11327 11328 // C++ [class]p2: 11329 // [...] The class-name is also inserted into the scope of the 11330 // class itself; this is known as the injected-class-name. For 11331 // purposes of access checking, the injected-class-name is treated 11332 // as if it were a public member name. 11333 CXXRecordDecl *InjectedClassName 11334 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11335 Record->getLocStart(), Record->getLocation(), 11336 Record->getIdentifier(), 11337 /*PrevDecl=*/0, 11338 /*DelayTypeCreation=*/true); 11339 Context.getTypeDeclType(InjectedClassName, Record); 11340 InjectedClassName->setImplicit(); 11341 InjectedClassName->setAccess(AS_public); 11342 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11343 InjectedClassName->setDescribedClassTemplate(Template); 11344 PushOnScopeChains(InjectedClassName, S); 11345 assert(InjectedClassName->isInjectedClassName() && 11346 "Broken injected-class-name"); 11347 } 11348 11349 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11350 SourceLocation RBraceLoc) { 11351 AdjustDeclIfTemplate(TagD); 11352 TagDecl *Tag = cast<TagDecl>(TagD); 11353 Tag->setRBraceLoc(RBraceLoc); 11354 11355 // Make sure we "complete" the definition even it is invalid. 11356 if (Tag->isBeingDefined()) { 11357 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11358 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11359 RD->completeDefinition(); 11360 } 11361 11362 if (isa<CXXRecordDecl>(Tag)) 11363 FieldCollector->FinishClass(); 11364 11365 // Exit this scope of this tag's definition. 11366 PopDeclContext(); 11367 11368 if (getCurLexicalContext()->isObjCContainer() && 11369 Tag->getDeclContext()->isFileContext()) 11370 Tag->setTopLevelDeclInObjCContainer(); 11371 11372 // Notify the consumer that we've defined a tag. 11373 if (!Tag->isInvalidDecl()) 11374 Consumer.HandleTagDeclDefinition(Tag); 11375 } 11376 11377 void Sema::ActOnObjCContainerFinishDefinition() { 11378 // Exit this scope of this interface definition. 11379 PopDeclContext(); 11380 } 11381 11382 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11383 assert(DC == CurContext && "Mismatch of container contexts"); 11384 OriginalLexicalContext = DC; 11385 ActOnObjCContainerFinishDefinition(); 11386 } 11387 11388 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11389 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11390 OriginalLexicalContext = 0; 11391 } 11392 11393 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11394 AdjustDeclIfTemplate(TagD); 11395 TagDecl *Tag = cast<TagDecl>(TagD); 11396 Tag->setInvalidDecl(); 11397 11398 // Make sure we "complete" the definition even it is invalid. 11399 if (Tag->isBeingDefined()) { 11400 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11401 RD->completeDefinition(); 11402 } 11403 11404 // We're undoing ActOnTagStartDefinition here, not 11405 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11406 // the FieldCollector. 11407 11408 PopDeclContext(); 11409 } 11410 11411 // Note that FieldName may be null for anonymous bitfields. 11412 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11413 IdentifierInfo *FieldName, 11414 QualType FieldTy, bool IsMsStruct, 11415 Expr *BitWidth, bool *ZeroWidth) { 11416 // Default to true; that shouldn't confuse checks for emptiness 11417 if (ZeroWidth) 11418 *ZeroWidth = true; 11419 11420 // C99 6.7.2.1p4 - verify the field type. 11421 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11422 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11423 // Handle incomplete types with specific error. 11424 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11425 return ExprError(); 11426 if (FieldName) 11427 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11428 << FieldName << FieldTy << BitWidth->getSourceRange(); 11429 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11430 << FieldTy << BitWidth->getSourceRange(); 11431 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11432 UPPC_BitFieldWidth)) 11433 return ExprError(); 11434 11435 // If the bit-width is type- or value-dependent, don't try to check 11436 // it now. 11437 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11438 return Owned(BitWidth); 11439 11440 llvm::APSInt Value; 11441 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11442 if (ICE.isInvalid()) 11443 return ICE; 11444 BitWidth = ICE.take(); 11445 11446 if (Value != 0 && ZeroWidth) 11447 *ZeroWidth = false; 11448 11449 // Zero-width bitfield is ok for anonymous field. 11450 if (Value == 0 && FieldName) 11451 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11452 11453 if (Value.isSigned() && Value.isNegative()) { 11454 if (FieldName) 11455 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11456 << FieldName << Value.toString(10); 11457 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11458 << Value.toString(10); 11459 } 11460 11461 if (!FieldTy->isDependentType()) { 11462 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11463 if (Value.getZExtValue() > TypeSize) { 11464 if (!getLangOpts().CPlusPlus || IsMsStruct || 11465 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11466 if (FieldName) 11467 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11468 << FieldName << (unsigned)Value.getZExtValue() 11469 << (unsigned)TypeSize; 11470 11471 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11472 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11473 } 11474 11475 if (FieldName) 11476 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11477 << FieldName << (unsigned)Value.getZExtValue() 11478 << (unsigned)TypeSize; 11479 else 11480 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11481 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11482 } 11483 } 11484 11485 return Owned(BitWidth); 11486 } 11487 11488 /// ActOnField - Each field of a C struct/union is passed into this in order 11489 /// to create a FieldDecl object for it. 11490 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11491 Declarator &D, Expr *BitfieldWidth) { 11492 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11493 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11494 /*InitStyle=*/ICIS_NoInit, AS_public); 11495 return Res; 11496 } 11497 11498 /// HandleField - Analyze a field of a C struct or a C++ data member. 11499 /// 11500 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11501 SourceLocation DeclStart, 11502 Declarator &D, Expr *BitWidth, 11503 InClassInitStyle InitStyle, 11504 AccessSpecifier AS) { 11505 IdentifierInfo *II = D.getIdentifier(); 11506 SourceLocation Loc = DeclStart; 11507 if (II) Loc = D.getIdentifierLoc(); 11508 11509 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11510 QualType T = TInfo->getType(); 11511 if (getLangOpts().CPlusPlus) { 11512 CheckExtraCXXDefaultArguments(D); 11513 11514 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11515 UPPC_DataMemberType)) { 11516 D.setInvalidType(); 11517 T = Context.IntTy; 11518 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11519 } 11520 } 11521 11522 // TR 18037 does not allow fields to be declared with address spaces. 11523 if (T.getQualifiers().hasAddressSpace()) { 11524 Diag(Loc, diag::err_field_with_address_space); 11525 D.setInvalidType(); 11526 } 11527 11528 // OpenCL 1.2 spec, s6.9 r: 11529 // The event type cannot be used to declare a structure or union field. 11530 if (LangOpts.OpenCL && T->isEventT()) { 11531 Diag(Loc, diag::err_event_t_struct_field); 11532 D.setInvalidType(); 11533 } 11534 11535 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11536 11537 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11538 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11539 diag::err_invalid_thread) 11540 << DeclSpec::getSpecifierName(TSCS); 11541 11542 // Check to see if this name was declared as a member previously 11543 NamedDecl *PrevDecl = 0; 11544 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11545 LookupName(Previous, S); 11546 switch (Previous.getResultKind()) { 11547 case LookupResult::Found: 11548 case LookupResult::FoundUnresolvedValue: 11549 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11550 break; 11551 11552 case LookupResult::FoundOverloaded: 11553 PrevDecl = Previous.getRepresentativeDecl(); 11554 break; 11555 11556 case LookupResult::NotFound: 11557 case LookupResult::NotFoundInCurrentInstantiation: 11558 case LookupResult::Ambiguous: 11559 break; 11560 } 11561 Previous.suppressDiagnostics(); 11562 11563 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11564 // Maybe we will complain about the shadowed template parameter. 11565 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11566 // Just pretend that we didn't see the previous declaration. 11567 PrevDecl = 0; 11568 } 11569 11570 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11571 PrevDecl = 0; 11572 11573 bool Mutable 11574 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11575 SourceLocation TSSL = D.getLocStart(); 11576 FieldDecl *NewFD 11577 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11578 TSSL, AS, PrevDecl, &D); 11579 11580 if (NewFD->isInvalidDecl()) 11581 Record->setInvalidDecl(); 11582 11583 if (D.getDeclSpec().isModulePrivateSpecified()) 11584 NewFD->setModulePrivate(); 11585 11586 if (NewFD->isInvalidDecl() && PrevDecl) { 11587 // Don't introduce NewFD into scope; there's already something 11588 // with the same name in the same scope. 11589 } else if (II) { 11590 PushOnScopeChains(NewFD, S); 11591 } else 11592 Record->addDecl(NewFD); 11593 11594 return NewFD; 11595 } 11596 11597 /// \brief Build a new FieldDecl and check its well-formedness. 11598 /// 11599 /// This routine builds a new FieldDecl given the fields name, type, 11600 /// record, etc. \p PrevDecl should refer to any previous declaration 11601 /// with the same name and in the same scope as the field to be 11602 /// created. 11603 /// 11604 /// \returns a new FieldDecl. 11605 /// 11606 /// \todo The Declarator argument is a hack. It will be removed once 11607 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11608 TypeSourceInfo *TInfo, 11609 RecordDecl *Record, SourceLocation Loc, 11610 bool Mutable, Expr *BitWidth, 11611 InClassInitStyle InitStyle, 11612 SourceLocation TSSL, 11613 AccessSpecifier AS, NamedDecl *PrevDecl, 11614 Declarator *D) { 11615 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11616 bool InvalidDecl = false; 11617 if (D) InvalidDecl = D->isInvalidType(); 11618 11619 // If we receive a broken type, recover by assuming 'int' and 11620 // marking this declaration as invalid. 11621 if (T.isNull()) { 11622 InvalidDecl = true; 11623 T = Context.IntTy; 11624 } 11625 11626 QualType EltTy = Context.getBaseElementType(T); 11627 if (!EltTy->isDependentType()) { 11628 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11629 // Fields of incomplete type force their record to be invalid. 11630 Record->setInvalidDecl(); 11631 InvalidDecl = true; 11632 } else { 11633 NamedDecl *Def; 11634 EltTy->isIncompleteType(&Def); 11635 if (Def && Def->isInvalidDecl()) { 11636 Record->setInvalidDecl(); 11637 InvalidDecl = true; 11638 } 11639 } 11640 } 11641 11642 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11643 if (BitWidth && getLangOpts().OpenCL) { 11644 Diag(Loc, diag::err_opencl_bitfields); 11645 InvalidDecl = true; 11646 } 11647 11648 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11649 // than a variably modified type. 11650 if (!InvalidDecl && T->isVariablyModifiedType()) { 11651 bool SizeIsNegative; 11652 llvm::APSInt Oversized; 11653 11654 TypeSourceInfo *FixedTInfo = 11655 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11656 SizeIsNegative, 11657 Oversized); 11658 if (FixedTInfo) { 11659 Diag(Loc, diag::warn_illegal_constant_array_size); 11660 TInfo = FixedTInfo; 11661 T = FixedTInfo->getType(); 11662 } else { 11663 if (SizeIsNegative) 11664 Diag(Loc, diag::err_typecheck_negative_array_size); 11665 else if (Oversized.getBoolValue()) 11666 Diag(Loc, diag::err_array_too_large) 11667 << Oversized.toString(10); 11668 else 11669 Diag(Loc, diag::err_typecheck_field_variable_size); 11670 InvalidDecl = true; 11671 } 11672 } 11673 11674 // Fields can not have abstract class types 11675 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11676 diag::err_abstract_type_in_decl, 11677 AbstractFieldType)) 11678 InvalidDecl = true; 11679 11680 bool ZeroWidth = false; 11681 // If this is declared as a bit-field, check the bit-field. 11682 if (!InvalidDecl && BitWidth) { 11683 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11684 &ZeroWidth).take(); 11685 if (!BitWidth) { 11686 InvalidDecl = true; 11687 BitWidth = 0; 11688 ZeroWidth = false; 11689 } 11690 } 11691 11692 // Check that 'mutable' is consistent with the type of the declaration. 11693 if (!InvalidDecl && Mutable) { 11694 unsigned DiagID = 0; 11695 if (T->isReferenceType()) 11696 DiagID = diag::err_mutable_reference; 11697 else if (T.isConstQualified()) 11698 DiagID = diag::err_mutable_const; 11699 11700 if (DiagID) { 11701 SourceLocation ErrLoc = Loc; 11702 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11703 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11704 Diag(ErrLoc, DiagID); 11705 Mutable = false; 11706 InvalidDecl = true; 11707 } 11708 } 11709 11710 // C++11 [class.union]p8 (DR1460): 11711 // At most one variant member of a union may have a 11712 // brace-or-equal-initializer. 11713 if (InitStyle != ICIS_NoInit) 11714 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11715 11716 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11717 BitWidth, Mutable, InitStyle); 11718 if (InvalidDecl) 11719 NewFD->setInvalidDecl(); 11720 11721 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11722 Diag(Loc, diag::err_duplicate_member) << II; 11723 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11724 NewFD->setInvalidDecl(); 11725 } 11726 11727 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11728 if (Record->isUnion()) { 11729 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11730 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11731 if (RDecl->getDefinition()) { 11732 // C++ [class.union]p1: An object of a class with a non-trivial 11733 // constructor, a non-trivial copy constructor, a non-trivial 11734 // destructor, or a non-trivial copy assignment operator 11735 // cannot be a member of a union, nor can an array of such 11736 // objects. 11737 if (CheckNontrivialField(NewFD)) 11738 NewFD->setInvalidDecl(); 11739 } 11740 } 11741 11742 // C++ [class.union]p1: If a union contains a member of reference type, 11743 // the program is ill-formed, except when compiling with MSVC extensions 11744 // enabled. 11745 if (EltTy->isReferenceType()) { 11746 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11747 diag::ext_union_member_of_reference_type : 11748 diag::err_union_member_of_reference_type) 11749 << NewFD->getDeclName() << EltTy; 11750 if (!getLangOpts().MicrosoftExt) 11751 NewFD->setInvalidDecl(); 11752 } 11753 } 11754 } 11755 11756 // FIXME: We need to pass in the attributes given an AST 11757 // representation, not a parser representation. 11758 if (D) { 11759 // FIXME: The current scope is almost... but not entirely... correct here. 11760 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11761 11762 if (NewFD->hasAttrs()) 11763 CheckAlignasUnderalignment(NewFD); 11764 } 11765 11766 // In auto-retain/release, infer strong retension for fields of 11767 // retainable type. 11768 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11769 NewFD->setInvalidDecl(); 11770 11771 if (T.isObjCGCWeak()) 11772 Diag(Loc, diag::warn_attribute_weak_on_field); 11773 11774 NewFD->setAccess(AS); 11775 return NewFD; 11776 } 11777 11778 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11779 assert(FD); 11780 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11781 11782 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11783 return false; 11784 11785 QualType EltTy = Context.getBaseElementType(FD->getType()); 11786 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11787 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11788 if (RDecl->getDefinition()) { 11789 // We check for copy constructors before constructors 11790 // because otherwise we'll never get complaints about 11791 // copy constructors. 11792 11793 CXXSpecialMember member = CXXInvalid; 11794 // We're required to check for any non-trivial constructors. Since the 11795 // implicit default constructor is suppressed if there are any 11796 // user-declared constructors, we just need to check that there is a 11797 // trivial default constructor and a trivial copy constructor. (We don't 11798 // worry about move constructors here, since this is a C++98 check.) 11799 if (RDecl->hasNonTrivialCopyConstructor()) 11800 member = CXXCopyConstructor; 11801 else if (!RDecl->hasTrivialDefaultConstructor()) 11802 member = CXXDefaultConstructor; 11803 else if (RDecl->hasNonTrivialCopyAssignment()) 11804 member = CXXCopyAssignment; 11805 else if (RDecl->hasNonTrivialDestructor()) 11806 member = CXXDestructor; 11807 11808 if (member != CXXInvalid) { 11809 if (!getLangOpts().CPlusPlus11 && 11810 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11811 // Objective-C++ ARC: it is an error to have a non-trivial field of 11812 // a union. However, system headers in Objective-C programs 11813 // occasionally have Objective-C lifetime objects within unions, 11814 // and rather than cause the program to fail, we make those 11815 // members unavailable. 11816 SourceLocation Loc = FD->getLocation(); 11817 if (getSourceManager().isInSystemHeader(Loc)) { 11818 if (!FD->hasAttr<UnavailableAttr>()) 11819 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11820 "this system field has retaining ownership", 11821 Loc)); 11822 return false; 11823 } 11824 } 11825 11826 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11827 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11828 diag::err_illegal_union_or_anon_struct_member) 11829 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11830 DiagnoseNontrivial(RDecl, member); 11831 return !getLangOpts().CPlusPlus11; 11832 } 11833 } 11834 } 11835 11836 return false; 11837 } 11838 11839 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11840 /// AST enum value. 11841 static ObjCIvarDecl::AccessControl 11842 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11843 switch (ivarVisibility) { 11844 default: llvm_unreachable("Unknown visitibility kind"); 11845 case tok::objc_private: return ObjCIvarDecl::Private; 11846 case tok::objc_public: return ObjCIvarDecl::Public; 11847 case tok::objc_protected: return ObjCIvarDecl::Protected; 11848 case tok::objc_package: return ObjCIvarDecl::Package; 11849 } 11850 } 11851 11852 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11853 /// in order to create an IvarDecl object for it. 11854 Decl *Sema::ActOnIvar(Scope *S, 11855 SourceLocation DeclStart, 11856 Declarator &D, Expr *BitfieldWidth, 11857 tok::ObjCKeywordKind Visibility) { 11858 11859 IdentifierInfo *II = D.getIdentifier(); 11860 Expr *BitWidth = (Expr*)BitfieldWidth; 11861 SourceLocation Loc = DeclStart; 11862 if (II) Loc = D.getIdentifierLoc(); 11863 11864 // FIXME: Unnamed fields can be handled in various different ways, for 11865 // example, unnamed unions inject all members into the struct namespace! 11866 11867 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11868 QualType T = TInfo->getType(); 11869 11870 if (BitWidth) { 11871 // 6.7.2.1p3, 6.7.2.1p4 11872 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11873 if (!BitWidth) 11874 D.setInvalidType(); 11875 } else { 11876 // Not a bitfield. 11877 11878 // validate II. 11879 11880 } 11881 if (T->isReferenceType()) { 11882 Diag(Loc, diag::err_ivar_reference_type); 11883 D.setInvalidType(); 11884 } 11885 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11886 // than a variably modified type. 11887 else if (T->isVariablyModifiedType()) { 11888 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11889 D.setInvalidType(); 11890 } 11891 11892 // Get the visibility (access control) for this ivar. 11893 ObjCIvarDecl::AccessControl ac = 11894 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11895 : ObjCIvarDecl::None; 11896 // Must set ivar's DeclContext to its enclosing interface. 11897 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11898 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11899 return 0; 11900 ObjCContainerDecl *EnclosingContext; 11901 if (ObjCImplementationDecl *IMPDecl = 11902 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11903 if (LangOpts.ObjCRuntime.isFragile()) { 11904 // Case of ivar declared in an implementation. Context is that of its class. 11905 EnclosingContext = IMPDecl->getClassInterface(); 11906 assert(EnclosingContext && "Implementation has no class interface!"); 11907 } 11908 else 11909 EnclosingContext = EnclosingDecl; 11910 } else { 11911 if (ObjCCategoryDecl *CDecl = 11912 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11913 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11914 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11915 return 0; 11916 } 11917 } 11918 EnclosingContext = EnclosingDecl; 11919 } 11920 11921 // Construct the decl. 11922 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11923 DeclStart, Loc, II, T, 11924 TInfo, ac, (Expr *)BitfieldWidth); 11925 11926 if (II) { 11927 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11928 ForRedeclaration); 11929 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11930 && !isa<TagDecl>(PrevDecl)) { 11931 Diag(Loc, diag::err_duplicate_member) << II; 11932 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11933 NewID->setInvalidDecl(); 11934 } 11935 } 11936 11937 // Process attributes attached to the ivar. 11938 ProcessDeclAttributes(S, NewID, D); 11939 11940 if (D.isInvalidType()) 11941 NewID->setInvalidDecl(); 11942 11943 // In ARC, infer 'retaining' for ivars of retainable type. 11944 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11945 NewID->setInvalidDecl(); 11946 11947 if (D.getDeclSpec().isModulePrivateSpecified()) 11948 NewID->setModulePrivate(); 11949 11950 if (II) { 11951 // FIXME: When interfaces are DeclContexts, we'll need to add 11952 // these to the interface. 11953 S->AddDecl(NewID); 11954 IdResolver.AddDecl(NewID); 11955 } 11956 11957 if (LangOpts.ObjCRuntime.isNonFragile() && 11958 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11959 Diag(Loc, diag::warn_ivars_in_interface); 11960 11961 return NewID; 11962 } 11963 11964 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11965 /// class and class extensions. For every class \@interface and class 11966 /// extension \@interface, if the last ivar is a bitfield of any type, 11967 /// then add an implicit `char :0` ivar to the end of that interface. 11968 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11969 SmallVectorImpl<Decl *> &AllIvarDecls) { 11970 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11971 return; 11972 11973 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11974 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11975 11976 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11977 return; 11978 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11979 if (!ID) { 11980 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11981 if (!CD->IsClassExtension()) 11982 return; 11983 } 11984 // No need to add this to end of @implementation. 11985 else 11986 return; 11987 } 11988 // All conditions are met. Add a new bitfield to the tail end of ivars. 11989 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11990 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11991 11992 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11993 DeclLoc, DeclLoc, 0, 11994 Context.CharTy, 11995 Context.getTrivialTypeSourceInfo(Context.CharTy, 11996 DeclLoc), 11997 ObjCIvarDecl::Private, BW, 11998 true); 11999 AllIvarDecls.push_back(Ivar); 12000 } 12001 12002 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12003 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12004 SourceLocation RBrac, AttributeList *Attr) { 12005 assert(EnclosingDecl && "missing record or interface decl"); 12006 12007 // If this is an Objective-C @implementation or category and we have 12008 // new fields here we should reset the layout of the interface since 12009 // it will now change. 12010 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12011 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12012 switch (DC->getKind()) { 12013 default: break; 12014 case Decl::ObjCCategory: 12015 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12016 break; 12017 case Decl::ObjCImplementation: 12018 Context. 12019 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12020 break; 12021 } 12022 } 12023 12024 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12025 12026 // Start counting up the number of named members; make sure to include 12027 // members of anonymous structs and unions in the total. 12028 unsigned NumNamedMembers = 0; 12029 if (Record) { 12030 for (const auto *I : Record->decls()) { 12031 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12032 if (IFD->getDeclName()) 12033 ++NumNamedMembers; 12034 } 12035 } 12036 12037 // Verify that all the fields are okay. 12038 SmallVector<FieldDecl*, 32> RecFields; 12039 12040 bool ARCErrReported = false; 12041 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12042 i != end; ++i) { 12043 FieldDecl *FD = cast<FieldDecl>(*i); 12044 12045 // Get the type for the field. 12046 const Type *FDTy = FD->getType().getTypePtr(); 12047 12048 if (!FD->isAnonymousStructOrUnion()) { 12049 // Remember all fields written by the user. 12050 RecFields.push_back(FD); 12051 } 12052 12053 // If the field is already invalid for some reason, don't emit more 12054 // diagnostics about it. 12055 if (FD->isInvalidDecl()) { 12056 EnclosingDecl->setInvalidDecl(); 12057 continue; 12058 } 12059 12060 // C99 6.7.2.1p2: 12061 // A structure or union shall not contain a member with 12062 // incomplete or function type (hence, a structure shall not 12063 // contain an instance of itself, but may contain a pointer to 12064 // an instance of itself), except that the last member of a 12065 // structure with more than one named member may have incomplete 12066 // array type; such a structure (and any union containing, 12067 // possibly recursively, a member that is such a structure) 12068 // shall not be a member of a structure or an element of an 12069 // array. 12070 if (FDTy->isFunctionType()) { 12071 // Field declared as a function. 12072 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12073 << FD->getDeclName(); 12074 FD->setInvalidDecl(); 12075 EnclosingDecl->setInvalidDecl(); 12076 continue; 12077 } else if (FDTy->isIncompleteArrayType() && Record && 12078 ((i + 1 == Fields.end() && !Record->isUnion()) || 12079 ((getLangOpts().MicrosoftExt || 12080 getLangOpts().CPlusPlus) && 12081 (i + 1 == Fields.end() || Record->isUnion())))) { 12082 // Flexible array member. 12083 // Microsoft and g++ is more permissive regarding flexible array. 12084 // It will accept flexible array in union and also 12085 // as the sole element of a struct/class. 12086 unsigned DiagID = 0; 12087 if (Record->isUnion()) 12088 DiagID = getLangOpts().MicrosoftExt 12089 ? diag::ext_flexible_array_union_ms 12090 : getLangOpts().CPlusPlus 12091 ? diag::ext_flexible_array_union_gnu 12092 : diag::err_flexible_array_union; 12093 else if (Fields.size() == 1) 12094 DiagID = getLangOpts().MicrosoftExt 12095 ? diag::ext_flexible_array_empty_aggregate_ms 12096 : getLangOpts().CPlusPlus 12097 ? diag::ext_flexible_array_empty_aggregate_gnu 12098 : NumNamedMembers < 1 12099 ? diag::err_flexible_array_empty_aggregate 12100 : 0; 12101 12102 if (DiagID) 12103 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12104 << Record->getTagKind(); 12105 // While the layout of types that contain virtual bases is not specified 12106 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12107 // virtual bases after the derived members. This would make a flexible 12108 // array member declared at the end of an object not adjacent to the end 12109 // of the type. 12110 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12111 if (RD->getNumVBases() != 0) 12112 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12113 << FD->getDeclName() << Record->getTagKind(); 12114 if (!getLangOpts().C99) 12115 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12116 << FD->getDeclName() << Record->getTagKind(); 12117 12118 // If the element type has a non-trivial destructor, we would not 12119 // implicitly destroy the elements, so disallow it for now. 12120 // 12121 // FIXME: GCC allows this. We should probably either implicitly delete 12122 // the destructor of the containing class, or just allow this. 12123 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12124 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12125 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12126 << FD->getDeclName() << FD->getType(); 12127 FD->setInvalidDecl(); 12128 EnclosingDecl->setInvalidDecl(); 12129 continue; 12130 } 12131 // Okay, we have a legal flexible array member at the end of the struct. 12132 if (Record) 12133 Record->setHasFlexibleArrayMember(true); 12134 } else if (!FDTy->isDependentType() && 12135 RequireCompleteType(FD->getLocation(), FD->getType(), 12136 diag::err_field_incomplete)) { 12137 // Incomplete type 12138 FD->setInvalidDecl(); 12139 EnclosingDecl->setInvalidDecl(); 12140 continue; 12141 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12142 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 12143 // If this is a member of a union, then entire union becomes "flexible". 12144 if (Record && Record->isUnion()) { 12145 Record->setHasFlexibleArrayMember(true); 12146 } else { 12147 // If this is a struct/class and this is not the last element, reject 12148 // it. Note that GCC supports variable sized arrays in the middle of 12149 // structures. 12150 if (i + 1 != Fields.end()) 12151 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12152 << FD->getDeclName() << FD->getType(); 12153 else { 12154 // We support flexible arrays at the end of structs in 12155 // other structs as an extension. 12156 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12157 << FD->getDeclName(); 12158 if (Record) 12159 Record->setHasFlexibleArrayMember(true); 12160 } 12161 } 12162 } 12163 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12164 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12165 diag::err_abstract_type_in_decl, 12166 AbstractIvarType)) { 12167 // Ivars can not have abstract class types 12168 FD->setInvalidDecl(); 12169 } 12170 if (Record && FDTTy->getDecl()->hasObjectMember()) 12171 Record->setHasObjectMember(true); 12172 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12173 Record->setHasVolatileMember(true); 12174 } else if (FDTy->isObjCObjectType()) { 12175 /// A field cannot be an Objective-c object 12176 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12177 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12178 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12179 FD->setType(T); 12180 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12181 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12182 // It's an error in ARC if a field has lifetime. 12183 // We don't want to report this in a system header, though, 12184 // so we just make the field unavailable. 12185 // FIXME: that's really not sufficient; we need to make the type 12186 // itself invalid to, say, initialize or copy. 12187 QualType T = FD->getType(); 12188 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12189 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12190 SourceLocation loc = FD->getLocation(); 12191 if (getSourceManager().isInSystemHeader(loc)) { 12192 if (!FD->hasAttr<UnavailableAttr>()) { 12193 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12194 "this system field has retaining ownership", 12195 loc)); 12196 } 12197 } else { 12198 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12199 << T->isBlockPointerType() << Record->getTagKind(); 12200 } 12201 ARCErrReported = true; 12202 } 12203 } else if (getLangOpts().ObjC1 && 12204 getLangOpts().getGC() != LangOptions::NonGC && 12205 Record && !Record->hasObjectMember()) { 12206 if (FD->getType()->isObjCObjectPointerType() || 12207 FD->getType().isObjCGCStrong()) 12208 Record->setHasObjectMember(true); 12209 else if (Context.getAsArrayType(FD->getType())) { 12210 QualType BaseType = Context.getBaseElementType(FD->getType()); 12211 if (BaseType->isRecordType() && 12212 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12213 Record->setHasObjectMember(true); 12214 else if (BaseType->isObjCObjectPointerType() || 12215 BaseType.isObjCGCStrong()) 12216 Record->setHasObjectMember(true); 12217 } 12218 } 12219 if (Record && FD->getType().isVolatileQualified()) 12220 Record->setHasVolatileMember(true); 12221 // Keep track of the number of named members. 12222 if (FD->getIdentifier()) 12223 ++NumNamedMembers; 12224 } 12225 12226 // Okay, we successfully defined 'Record'. 12227 if (Record) { 12228 bool Completed = false; 12229 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12230 if (!CXXRecord->isInvalidDecl()) { 12231 // Set access bits correctly on the directly-declared conversions. 12232 for (CXXRecordDecl::conversion_iterator 12233 I = CXXRecord->conversion_begin(), 12234 E = CXXRecord->conversion_end(); I != E; ++I) 12235 I.setAccess((*I)->getAccess()); 12236 12237 if (!CXXRecord->isDependentType()) { 12238 if (CXXRecord->hasUserDeclaredDestructor()) { 12239 // Adjust user-defined destructor exception spec. 12240 if (getLangOpts().CPlusPlus11) 12241 AdjustDestructorExceptionSpec(CXXRecord, 12242 CXXRecord->getDestructor()); 12243 } 12244 12245 // Add any implicitly-declared members to this class. 12246 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12247 12248 // If we have virtual base classes, we may end up finding multiple 12249 // final overriders for a given virtual function. Check for this 12250 // problem now. 12251 if (CXXRecord->getNumVBases()) { 12252 CXXFinalOverriderMap FinalOverriders; 12253 CXXRecord->getFinalOverriders(FinalOverriders); 12254 12255 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12256 MEnd = FinalOverriders.end(); 12257 M != MEnd; ++M) { 12258 for (OverridingMethods::iterator SO = M->second.begin(), 12259 SOEnd = M->second.end(); 12260 SO != SOEnd; ++SO) { 12261 assert(SO->second.size() > 0 && 12262 "Virtual function without overridding functions?"); 12263 if (SO->second.size() == 1) 12264 continue; 12265 12266 // C++ [class.virtual]p2: 12267 // In a derived class, if a virtual member function of a base 12268 // class subobject has more than one final overrider the 12269 // program is ill-formed. 12270 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12271 << (const NamedDecl *)M->first << Record; 12272 Diag(M->first->getLocation(), 12273 diag::note_overridden_virtual_function); 12274 for (OverridingMethods::overriding_iterator 12275 OM = SO->second.begin(), 12276 OMEnd = SO->second.end(); 12277 OM != OMEnd; ++OM) 12278 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12279 << (const NamedDecl *)M->first << OM->Method->getParent(); 12280 12281 Record->setInvalidDecl(); 12282 } 12283 } 12284 CXXRecord->completeDefinition(&FinalOverriders); 12285 Completed = true; 12286 } 12287 } 12288 } 12289 } 12290 12291 if (!Completed) 12292 Record->completeDefinition(); 12293 12294 if (Record->hasAttrs()) { 12295 CheckAlignasUnderalignment(Record); 12296 12297 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12298 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12299 IA->getRange(), IA->getBestCase(), 12300 IA->getSemanticSpelling()); 12301 } 12302 12303 // Check if the structure/union declaration is a type that can have zero 12304 // size in C. For C this is a language extension, for C++ it may cause 12305 // compatibility problems. 12306 bool CheckForZeroSize; 12307 if (!getLangOpts().CPlusPlus) { 12308 CheckForZeroSize = true; 12309 } else { 12310 // For C++ filter out types that cannot be referenced in C code. 12311 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12312 CheckForZeroSize = 12313 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12314 !CXXRecord->isDependentType() && 12315 CXXRecord->isCLike(); 12316 } 12317 if (CheckForZeroSize) { 12318 bool ZeroSize = true; 12319 bool IsEmpty = true; 12320 unsigned NonBitFields = 0; 12321 for (RecordDecl::field_iterator I = Record->field_begin(), 12322 E = Record->field_end(); 12323 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12324 IsEmpty = false; 12325 if (I->isUnnamedBitfield()) { 12326 if (I->getBitWidthValue(Context) > 0) 12327 ZeroSize = false; 12328 } else { 12329 ++NonBitFields; 12330 QualType FieldType = I->getType(); 12331 if (FieldType->isIncompleteType() || 12332 !Context.getTypeSizeInChars(FieldType).isZero()) 12333 ZeroSize = false; 12334 } 12335 } 12336 12337 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12338 // allowed in C++, but warn if its declaration is inside 12339 // extern "C" block. 12340 if (ZeroSize) { 12341 Diag(RecLoc, getLangOpts().CPlusPlus ? 12342 diag::warn_zero_size_struct_union_in_extern_c : 12343 diag::warn_zero_size_struct_union_compat) 12344 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12345 } 12346 12347 // Structs without named members are extension in C (C99 6.7.2.1p7), 12348 // but are accepted by GCC. 12349 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12350 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12351 diag::ext_no_named_members_in_struct_union) 12352 << Record->isUnion(); 12353 } 12354 } 12355 } else { 12356 ObjCIvarDecl **ClsFields = 12357 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12358 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12359 ID->setEndOfDefinitionLoc(RBrac); 12360 // Add ivar's to class's DeclContext. 12361 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12362 ClsFields[i]->setLexicalDeclContext(ID); 12363 ID->addDecl(ClsFields[i]); 12364 } 12365 // Must enforce the rule that ivars in the base classes may not be 12366 // duplicates. 12367 if (ID->getSuperClass()) 12368 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12369 } else if (ObjCImplementationDecl *IMPDecl = 12370 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12371 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12372 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12373 // Ivar declared in @implementation never belongs to the implementation. 12374 // Only it is in implementation's lexical context. 12375 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12376 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12377 IMPDecl->setIvarLBraceLoc(LBrac); 12378 IMPDecl->setIvarRBraceLoc(RBrac); 12379 } else if (ObjCCategoryDecl *CDecl = 12380 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12381 // case of ivars in class extension; all other cases have been 12382 // reported as errors elsewhere. 12383 // FIXME. Class extension does not have a LocEnd field. 12384 // CDecl->setLocEnd(RBrac); 12385 // Add ivar's to class extension's DeclContext. 12386 // Diagnose redeclaration of private ivars. 12387 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12388 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12389 if (IDecl) { 12390 if (const ObjCIvarDecl *ClsIvar = 12391 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12392 Diag(ClsFields[i]->getLocation(), 12393 diag::err_duplicate_ivar_declaration); 12394 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12395 continue; 12396 } 12397 for (const auto *Ext : IDecl->known_extensions()) { 12398 if (const ObjCIvarDecl *ClsExtIvar 12399 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12400 Diag(ClsFields[i]->getLocation(), 12401 diag::err_duplicate_ivar_declaration); 12402 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12403 continue; 12404 } 12405 } 12406 } 12407 ClsFields[i]->setLexicalDeclContext(CDecl); 12408 CDecl->addDecl(ClsFields[i]); 12409 } 12410 CDecl->setIvarLBraceLoc(LBrac); 12411 CDecl->setIvarRBraceLoc(RBrac); 12412 } 12413 } 12414 12415 if (Attr) 12416 ProcessDeclAttributeList(S, Record, Attr); 12417 } 12418 12419 /// \brief Determine whether the given integral value is representable within 12420 /// the given type T. 12421 static bool isRepresentableIntegerValue(ASTContext &Context, 12422 llvm::APSInt &Value, 12423 QualType T) { 12424 assert(T->isIntegralType(Context) && "Integral type required!"); 12425 unsigned BitWidth = Context.getIntWidth(T); 12426 12427 if (Value.isUnsigned() || Value.isNonNegative()) { 12428 if (T->isSignedIntegerOrEnumerationType()) 12429 --BitWidth; 12430 return Value.getActiveBits() <= BitWidth; 12431 } 12432 return Value.getMinSignedBits() <= BitWidth; 12433 } 12434 12435 // \brief Given an integral type, return the next larger integral type 12436 // (or a NULL type of no such type exists). 12437 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12438 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12439 // enum checking below. 12440 assert(T->isIntegralType(Context) && "Integral type required!"); 12441 const unsigned NumTypes = 4; 12442 QualType SignedIntegralTypes[NumTypes] = { 12443 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12444 }; 12445 QualType UnsignedIntegralTypes[NumTypes] = { 12446 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12447 Context.UnsignedLongLongTy 12448 }; 12449 12450 unsigned BitWidth = Context.getTypeSize(T); 12451 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12452 : UnsignedIntegralTypes; 12453 for (unsigned I = 0; I != NumTypes; ++I) 12454 if (Context.getTypeSize(Types[I]) > BitWidth) 12455 return Types[I]; 12456 12457 return QualType(); 12458 } 12459 12460 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12461 EnumConstantDecl *LastEnumConst, 12462 SourceLocation IdLoc, 12463 IdentifierInfo *Id, 12464 Expr *Val) { 12465 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12466 llvm::APSInt EnumVal(IntWidth); 12467 QualType EltTy; 12468 12469 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12470 Val = 0; 12471 12472 if (Val) 12473 Val = DefaultLvalueConversion(Val).take(); 12474 12475 if (Val) { 12476 if (Enum->isDependentType() || Val->isTypeDependent()) 12477 EltTy = Context.DependentTy; 12478 else { 12479 SourceLocation ExpLoc; 12480 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12481 !getLangOpts().MSVCCompat) { 12482 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12483 // constant-expression in the enumerator-definition shall be a converted 12484 // constant expression of the underlying type. 12485 EltTy = Enum->getIntegerType(); 12486 ExprResult Converted = 12487 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12488 CCEK_Enumerator); 12489 if (Converted.isInvalid()) 12490 Val = 0; 12491 else 12492 Val = Converted.take(); 12493 } else if (!Val->isValueDependent() && 12494 !(Val = VerifyIntegerConstantExpression(Val, 12495 &EnumVal).take())) { 12496 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12497 } else { 12498 if (Enum->isFixed()) { 12499 EltTy = Enum->getIntegerType(); 12500 12501 // In Obj-C and Microsoft mode, require the enumeration value to be 12502 // representable in the underlying type of the enumeration. In C++11, 12503 // we perform a non-narrowing conversion as part of converted constant 12504 // expression checking. 12505 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12506 if (getLangOpts().MSVCCompat) { 12507 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12508 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12509 } else 12510 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12511 } else 12512 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12513 } else if (getLangOpts().CPlusPlus) { 12514 // C++11 [dcl.enum]p5: 12515 // If the underlying type is not fixed, the type of each enumerator 12516 // is the type of its initializing value: 12517 // - If an initializer is specified for an enumerator, the 12518 // initializing value has the same type as the expression. 12519 EltTy = Val->getType(); 12520 } else { 12521 // C99 6.7.2.2p2: 12522 // The expression that defines the value of an enumeration constant 12523 // shall be an integer constant expression that has a value 12524 // representable as an int. 12525 12526 // Complain if the value is not representable in an int. 12527 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12528 Diag(IdLoc, diag::ext_enum_value_not_int) 12529 << EnumVal.toString(10) << Val->getSourceRange() 12530 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12531 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12532 // Force the type of the expression to 'int'. 12533 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12534 } 12535 EltTy = Val->getType(); 12536 } 12537 } 12538 } 12539 } 12540 12541 if (!Val) { 12542 if (Enum->isDependentType()) 12543 EltTy = Context.DependentTy; 12544 else if (!LastEnumConst) { 12545 // C++0x [dcl.enum]p5: 12546 // If the underlying type is not fixed, the type of each enumerator 12547 // is the type of its initializing value: 12548 // - If no initializer is specified for the first enumerator, the 12549 // initializing value has an unspecified integral type. 12550 // 12551 // GCC uses 'int' for its unspecified integral type, as does 12552 // C99 6.7.2.2p3. 12553 if (Enum->isFixed()) { 12554 EltTy = Enum->getIntegerType(); 12555 } 12556 else { 12557 EltTy = Context.IntTy; 12558 } 12559 } else { 12560 // Assign the last value + 1. 12561 EnumVal = LastEnumConst->getInitVal(); 12562 ++EnumVal; 12563 EltTy = LastEnumConst->getType(); 12564 12565 // Check for overflow on increment. 12566 if (EnumVal < LastEnumConst->getInitVal()) { 12567 // C++0x [dcl.enum]p5: 12568 // If the underlying type is not fixed, the type of each enumerator 12569 // is the type of its initializing value: 12570 // 12571 // - Otherwise the type of the initializing value is the same as 12572 // the type of the initializing value of the preceding enumerator 12573 // unless the incremented value is not representable in that type, 12574 // in which case the type is an unspecified integral type 12575 // sufficient to contain the incremented value. If no such type 12576 // exists, the program is ill-formed. 12577 QualType T = getNextLargerIntegralType(Context, EltTy); 12578 if (T.isNull() || Enum->isFixed()) { 12579 // There is no integral type larger enough to represent this 12580 // value. Complain, then allow the value to wrap around. 12581 EnumVal = LastEnumConst->getInitVal(); 12582 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12583 ++EnumVal; 12584 if (Enum->isFixed()) 12585 // When the underlying type is fixed, this is ill-formed. 12586 Diag(IdLoc, diag::err_enumerator_wrapped) 12587 << EnumVal.toString(10) 12588 << EltTy; 12589 else 12590 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 12591 << EnumVal.toString(10); 12592 } else { 12593 EltTy = T; 12594 } 12595 12596 // Retrieve the last enumerator's value, extent that type to the 12597 // type that is supposed to be large enough to represent the incremented 12598 // value, then increment. 12599 EnumVal = LastEnumConst->getInitVal(); 12600 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12601 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12602 ++EnumVal; 12603 12604 // If we're not in C++, diagnose the overflow of enumerator values, 12605 // which in C99 means that the enumerator value is not representable in 12606 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12607 // permits enumerator values that are representable in some larger 12608 // integral type. 12609 if (!getLangOpts().CPlusPlus && !T.isNull()) 12610 Diag(IdLoc, diag::warn_enum_value_overflow); 12611 } else if (!getLangOpts().CPlusPlus && 12612 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12613 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12614 Diag(IdLoc, diag::ext_enum_value_not_int) 12615 << EnumVal.toString(10) << 1; 12616 } 12617 } 12618 } 12619 12620 if (!EltTy->isDependentType()) { 12621 // Make the enumerator value match the signedness and size of the 12622 // enumerator's type. 12623 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12624 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12625 } 12626 12627 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12628 Val, EnumVal); 12629 } 12630 12631 12632 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12633 SourceLocation IdLoc, IdentifierInfo *Id, 12634 AttributeList *Attr, 12635 SourceLocation EqualLoc, Expr *Val) { 12636 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12637 EnumConstantDecl *LastEnumConst = 12638 cast_or_null<EnumConstantDecl>(lastEnumConst); 12639 12640 // The scope passed in may not be a decl scope. Zip up the scope tree until 12641 // we find one that is. 12642 S = getNonFieldDeclScope(S); 12643 12644 // Verify that there isn't already something declared with this name in this 12645 // scope. 12646 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12647 ForRedeclaration); 12648 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12649 // Maybe we will complain about the shadowed template parameter. 12650 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12651 // Just pretend that we didn't see the previous declaration. 12652 PrevDecl = 0; 12653 } 12654 12655 if (PrevDecl) { 12656 // When in C++, we may get a TagDecl with the same name; in this case the 12657 // enum constant will 'hide' the tag. 12658 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12659 "Received TagDecl when not in C++!"); 12660 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12661 if (isa<EnumConstantDecl>(PrevDecl)) 12662 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12663 else 12664 Diag(IdLoc, diag::err_redefinition) << Id; 12665 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12666 return 0; 12667 } 12668 } 12669 12670 // C++ [class.mem]p15: 12671 // If T is the name of a class, then each of the following shall have a name 12672 // different from T: 12673 // - every enumerator of every member of class T that is an unscoped 12674 // enumerated type 12675 if (CXXRecordDecl *Record 12676 = dyn_cast<CXXRecordDecl>( 12677 TheEnumDecl->getDeclContext()->getRedeclContext())) 12678 if (!TheEnumDecl->isScoped() && 12679 Record->getIdentifier() && Record->getIdentifier() == Id) 12680 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12681 12682 EnumConstantDecl *New = 12683 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12684 12685 if (New) { 12686 // Process attributes. 12687 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12688 12689 // Register this decl in the current scope stack. 12690 New->setAccess(TheEnumDecl->getAccess()); 12691 PushOnScopeChains(New, S); 12692 } 12693 12694 ActOnDocumentableDecl(New); 12695 12696 return New; 12697 } 12698 12699 // Returns true when the enum initial expression does not trigger the 12700 // duplicate enum warning. A few common cases are exempted as follows: 12701 // Element2 = Element1 12702 // Element2 = Element1 + 1 12703 // Element2 = Element1 - 1 12704 // Where Element2 and Element1 are from the same enum. 12705 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12706 Expr *InitExpr = ECD->getInitExpr(); 12707 if (!InitExpr) 12708 return true; 12709 InitExpr = InitExpr->IgnoreImpCasts(); 12710 12711 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12712 if (!BO->isAdditiveOp()) 12713 return true; 12714 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12715 if (!IL) 12716 return true; 12717 if (IL->getValue() != 1) 12718 return true; 12719 12720 InitExpr = BO->getLHS(); 12721 } 12722 12723 // This checks if the elements are from the same enum. 12724 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12725 if (!DRE) 12726 return true; 12727 12728 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12729 if (!EnumConstant) 12730 return true; 12731 12732 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12733 Enum) 12734 return true; 12735 12736 return false; 12737 } 12738 12739 struct DupKey { 12740 int64_t val; 12741 bool isTombstoneOrEmptyKey; 12742 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12743 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12744 }; 12745 12746 static DupKey GetDupKey(const llvm::APSInt& Val) { 12747 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12748 false); 12749 } 12750 12751 struct DenseMapInfoDupKey { 12752 static DupKey getEmptyKey() { return DupKey(0, true); } 12753 static DupKey getTombstoneKey() { return DupKey(1, true); } 12754 static unsigned getHashValue(const DupKey Key) { 12755 return (unsigned)(Key.val * 37); 12756 } 12757 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12758 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12759 LHS.val == RHS.val; 12760 } 12761 }; 12762 12763 // Emits a warning when an element is implicitly set a value that 12764 // a previous element has already been set to. 12765 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12766 EnumDecl *Enum, 12767 QualType EnumType) { 12768 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12769 Enum->getLocation()) == 12770 DiagnosticsEngine::Ignored) 12771 return; 12772 // Avoid anonymous enums 12773 if (!Enum->getIdentifier()) 12774 return; 12775 12776 // Only check for small enums. 12777 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12778 return; 12779 12780 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12781 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12782 12783 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12784 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12785 ValueToVectorMap; 12786 12787 DuplicatesVector DupVector; 12788 ValueToVectorMap EnumMap; 12789 12790 // Populate the EnumMap with all values represented by enum constants without 12791 // an initialier. 12792 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12793 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12794 12795 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12796 // this constant. Skip this enum since it may be ill-formed. 12797 if (!ECD) { 12798 return; 12799 } 12800 12801 if (ECD->getInitExpr()) 12802 continue; 12803 12804 DupKey Key = GetDupKey(ECD->getInitVal()); 12805 DeclOrVector &Entry = EnumMap[Key]; 12806 12807 // First time encountering this value. 12808 if (Entry.isNull()) 12809 Entry = ECD; 12810 } 12811 12812 // Create vectors for any values that has duplicates. 12813 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12814 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12815 if (!ValidDuplicateEnum(ECD, Enum)) 12816 continue; 12817 12818 DupKey Key = GetDupKey(ECD->getInitVal()); 12819 12820 DeclOrVector& Entry = EnumMap[Key]; 12821 if (Entry.isNull()) 12822 continue; 12823 12824 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12825 // Ensure constants are different. 12826 if (D == ECD) 12827 continue; 12828 12829 // Create new vector and push values onto it. 12830 ECDVector *Vec = new ECDVector(); 12831 Vec->push_back(D); 12832 Vec->push_back(ECD); 12833 12834 // Update entry to point to the duplicates vector. 12835 Entry = Vec; 12836 12837 // Store the vector somewhere we can consult later for quick emission of 12838 // diagnostics. 12839 DupVector.push_back(Vec); 12840 continue; 12841 } 12842 12843 ECDVector *Vec = Entry.get<ECDVector*>(); 12844 // Make sure constants are not added more than once. 12845 if (*Vec->begin() == ECD) 12846 continue; 12847 12848 Vec->push_back(ECD); 12849 } 12850 12851 // Emit diagnostics. 12852 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12853 DupVectorEnd = DupVector.end(); 12854 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12855 ECDVector *Vec = *DupVectorIter; 12856 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12857 12858 // Emit warning for one enum constant. 12859 ECDVector::iterator I = Vec->begin(); 12860 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12861 << (*I)->getName() << (*I)->getInitVal().toString(10) 12862 << (*I)->getSourceRange(); 12863 ++I; 12864 12865 // Emit one note for each of the remaining enum constants with 12866 // the same value. 12867 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12868 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12869 << (*I)->getName() << (*I)->getInitVal().toString(10) 12870 << (*I)->getSourceRange(); 12871 delete Vec; 12872 } 12873 } 12874 12875 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12876 SourceLocation RBraceLoc, Decl *EnumDeclX, 12877 ArrayRef<Decl *> Elements, 12878 Scope *S, AttributeList *Attr) { 12879 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12880 QualType EnumType = Context.getTypeDeclType(Enum); 12881 12882 if (Attr) 12883 ProcessDeclAttributeList(S, Enum, Attr); 12884 12885 if (Enum->isDependentType()) { 12886 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12887 EnumConstantDecl *ECD = 12888 cast_or_null<EnumConstantDecl>(Elements[i]); 12889 if (!ECD) continue; 12890 12891 ECD->setType(EnumType); 12892 } 12893 12894 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12895 return; 12896 } 12897 12898 // TODO: If the result value doesn't fit in an int, it must be a long or long 12899 // long value. ISO C does not support this, but GCC does as an extension, 12900 // emit a warning. 12901 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12902 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12903 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12904 12905 // Verify that all the values are okay, compute the size of the values, and 12906 // reverse the list. 12907 unsigned NumNegativeBits = 0; 12908 unsigned NumPositiveBits = 0; 12909 12910 // Keep track of whether all elements have type int. 12911 bool AllElementsInt = true; 12912 12913 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12914 EnumConstantDecl *ECD = 12915 cast_or_null<EnumConstantDecl>(Elements[i]); 12916 if (!ECD) continue; // Already issued a diagnostic. 12917 12918 const llvm::APSInt &InitVal = ECD->getInitVal(); 12919 12920 // Keep track of the size of positive and negative values. 12921 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12922 NumPositiveBits = std::max(NumPositiveBits, 12923 (unsigned)InitVal.getActiveBits()); 12924 else 12925 NumNegativeBits = std::max(NumNegativeBits, 12926 (unsigned)InitVal.getMinSignedBits()); 12927 12928 // Keep track of whether every enum element has type int (very commmon). 12929 if (AllElementsInt) 12930 AllElementsInt = ECD->getType() == Context.IntTy; 12931 } 12932 12933 // Figure out the type that should be used for this enum. 12934 QualType BestType; 12935 unsigned BestWidth; 12936 12937 // C++0x N3000 [conv.prom]p3: 12938 // An rvalue of an unscoped enumeration type whose underlying 12939 // type is not fixed can be converted to an rvalue of the first 12940 // of the following types that can represent all the values of 12941 // the enumeration: int, unsigned int, long int, unsigned long 12942 // int, long long int, or unsigned long long int. 12943 // C99 6.4.4.3p2: 12944 // An identifier declared as an enumeration constant has type int. 12945 // The C99 rule is modified by a gcc extension 12946 QualType BestPromotionType; 12947 12948 bool Packed = Enum->hasAttr<PackedAttr>(); 12949 // -fshort-enums is the equivalent to specifying the packed attribute on all 12950 // enum definitions. 12951 if (LangOpts.ShortEnums) 12952 Packed = true; 12953 12954 if (Enum->isFixed()) { 12955 BestType = Enum->getIntegerType(); 12956 if (BestType->isPromotableIntegerType()) 12957 BestPromotionType = Context.getPromotedIntegerType(BestType); 12958 else 12959 BestPromotionType = BestType; 12960 // We don't need to set BestWidth, because BestType is going to be the type 12961 // of the enumerators, but we do anyway because otherwise some compilers 12962 // warn that it might be used uninitialized. 12963 BestWidth = CharWidth; 12964 } 12965 else if (NumNegativeBits) { 12966 // If there is a negative value, figure out the smallest integer type (of 12967 // int/long/longlong) that fits. 12968 // If it's packed, check also if it fits a char or a short. 12969 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12970 BestType = Context.SignedCharTy; 12971 BestWidth = CharWidth; 12972 } else if (Packed && NumNegativeBits <= ShortWidth && 12973 NumPositiveBits < ShortWidth) { 12974 BestType = Context.ShortTy; 12975 BestWidth = ShortWidth; 12976 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12977 BestType = Context.IntTy; 12978 BestWidth = IntWidth; 12979 } else { 12980 BestWidth = Context.getTargetInfo().getLongWidth(); 12981 12982 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12983 BestType = Context.LongTy; 12984 } else { 12985 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12986 12987 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12988 Diag(Enum->getLocation(), diag::ext_enum_too_large); 12989 BestType = Context.LongLongTy; 12990 } 12991 } 12992 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12993 } else { 12994 // If there is no negative value, figure out the smallest type that fits 12995 // all of the enumerator values. 12996 // If it's packed, check also if it fits a char or a short. 12997 if (Packed && NumPositiveBits <= CharWidth) { 12998 BestType = Context.UnsignedCharTy; 12999 BestPromotionType = Context.IntTy; 13000 BestWidth = CharWidth; 13001 } else if (Packed && NumPositiveBits <= ShortWidth) { 13002 BestType = Context.UnsignedShortTy; 13003 BestPromotionType = Context.IntTy; 13004 BestWidth = ShortWidth; 13005 } else if (NumPositiveBits <= IntWidth) { 13006 BestType = Context.UnsignedIntTy; 13007 BestWidth = IntWidth; 13008 BestPromotionType 13009 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13010 ? Context.UnsignedIntTy : Context.IntTy; 13011 } else if (NumPositiveBits <= 13012 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13013 BestType = Context.UnsignedLongTy; 13014 BestPromotionType 13015 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13016 ? Context.UnsignedLongTy : Context.LongTy; 13017 } else { 13018 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13019 assert(NumPositiveBits <= BestWidth && 13020 "How could an initializer get larger than ULL?"); 13021 BestType = Context.UnsignedLongLongTy; 13022 BestPromotionType 13023 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13024 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13025 } 13026 } 13027 13028 // Loop over all of the enumerator constants, changing their types to match 13029 // the type of the enum if needed. 13030 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13031 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13032 if (!ECD) continue; // Already issued a diagnostic. 13033 13034 // Standard C says the enumerators have int type, but we allow, as an 13035 // extension, the enumerators to be larger than int size. If each 13036 // enumerator value fits in an int, type it as an int, otherwise type it the 13037 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13038 // that X has type 'int', not 'unsigned'. 13039 13040 // Determine whether the value fits into an int. 13041 llvm::APSInt InitVal = ECD->getInitVal(); 13042 13043 // If it fits into an integer type, force it. Otherwise force it to match 13044 // the enum decl type. 13045 QualType NewTy; 13046 unsigned NewWidth; 13047 bool NewSign; 13048 if (!getLangOpts().CPlusPlus && 13049 !Enum->isFixed() && 13050 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13051 NewTy = Context.IntTy; 13052 NewWidth = IntWidth; 13053 NewSign = true; 13054 } else if (ECD->getType() == BestType) { 13055 // Already the right type! 13056 if (getLangOpts().CPlusPlus) 13057 // C++ [dcl.enum]p4: Following the closing brace of an 13058 // enum-specifier, each enumerator has the type of its 13059 // enumeration. 13060 ECD->setType(EnumType); 13061 continue; 13062 } else { 13063 NewTy = BestType; 13064 NewWidth = BestWidth; 13065 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13066 } 13067 13068 // Adjust the APSInt value. 13069 InitVal = InitVal.extOrTrunc(NewWidth); 13070 InitVal.setIsSigned(NewSign); 13071 ECD->setInitVal(InitVal); 13072 13073 // Adjust the Expr initializer and type. 13074 if (ECD->getInitExpr() && 13075 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13076 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13077 CK_IntegralCast, 13078 ECD->getInitExpr(), 13079 /*base paths*/ 0, 13080 VK_RValue)); 13081 if (getLangOpts().CPlusPlus) 13082 // C++ [dcl.enum]p4: Following the closing brace of an 13083 // enum-specifier, each enumerator has the type of its 13084 // enumeration. 13085 ECD->setType(EnumType); 13086 else 13087 ECD->setType(NewTy); 13088 } 13089 13090 Enum->completeDefinition(BestType, BestPromotionType, 13091 NumPositiveBits, NumNegativeBits); 13092 13093 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13094 13095 // Now that the enum type is defined, ensure it's not been underaligned. 13096 if (Enum->hasAttrs()) 13097 CheckAlignasUnderalignment(Enum); 13098 } 13099 13100 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13101 SourceLocation StartLoc, 13102 SourceLocation EndLoc) { 13103 StringLiteral *AsmString = cast<StringLiteral>(expr); 13104 13105 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13106 AsmString, StartLoc, 13107 EndLoc); 13108 CurContext->addDecl(New); 13109 return New; 13110 } 13111 13112 static void checkModuleImportContext(Sema &S, Module *M, 13113 SourceLocation ImportLoc, 13114 DeclContext *DC) { 13115 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13116 switch (LSD->getLanguage()) { 13117 case LinkageSpecDecl::lang_c: 13118 if (!M->IsExternC) { 13119 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13120 << M->getFullModuleName(); 13121 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13122 return; 13123 } 13124 break; 13125 case LinkageSpecDecl::lang_cxx: 13126 break; 13127 } 13128 DC = LSD->getParent(); 13129 } 13130 13131 while (isa<LinkageSpecDecl>(DC)) 13132 DC = DC->getParent(); 13133 if (!isa<TranslationUnitDecl>(DC)) { 13134 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13135 << M->getFullModuleName() << DC; 13136 S.Diag(cast<Decl>(DC)->getLocStart(), 13137 diag::note_module_import_not_at_top_level) 13138 << DC; 13139 } 13140 } 13141 13142 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13143 SourceLocation ImportLoc, 13144 ModuleIdPath Path) { 13145 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 13146 Module::AllVisible, 13147 /*IsIncludeDirective=*/false); 13148 if (!Mod) 13149 return true; 13150 13151 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13152 13153 SmallVector<SourceLocation, 2> IdentifierLocs; 13154 Module *ModCheck = Mod; 13155 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13156 // If we've run out of module parents, just drop the remaining identifiers. 13157 // We need the length to be consistent. 13158 if (!ModCheck) 13159 break; 13160 ModCheck = ModCheck->Parent; 13161 13162 IdentifierLocs.push_back(Path[I].second); 13163 } 13164 13165 ImportDecl *Import = ImportDecl::Create(Context, 13166 Context.getTranslationUnitDecl(), 13167 AtLoc.isValid()? AtLoc : ImportLoc, 13168 Mod, IdentifierLocs); 13169 Context.getTranslationUnitDecl()->addDecl(Import); 13170 return Import; 13171 } 13172 13173 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13174 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13175 13176 // FIXME: Should we synthesize an ImportDecl here? 13177 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13178 /*Complain=*/true); 13179 } 13180 13181 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 13182 // Create the implicit import declaration. 13183 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13184 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13185 Loc, Mod, Loc); 13186 TU->addDecl(ImportD); 13187 Consumer.HandleImplicitImportDecl(ImportD); 13188 13189 // Make the module visible. 13190 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13191 /*Complain=*/false); 13192 } 13193 13194 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13195 IdentifierInfo* AliasName, 13196 SourceLocation PragmaLoc, 13197 SourceLocation NameLoc, 13198 SourceLocation AliasNameLoc) { 13199 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13200 LookupOrdinaryName); 13201 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13202 AliasName->getName(), 0); 13203 13204 if (PrevDecl) 13205 PrevDecl->addAttr(Attr); 13206 else 13207 (void)ExtnameUndeclaredIdentifiers.insert( 13208 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13209 } 13210 13211 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13212 SourceLocation PragmaLoc, 13213 SourceLocation NameLoc) { 13214 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13215 13216 if (PrevDecl) { 13217 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13218 } else { 13219 (void)WeakUndeclaredIdentifiers.insert( 13220 std::pair<IdentifierInfo*,WeakInfo> 13221 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 13222 } 13223 } 13224 13225 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13226 IdentifierInfo* AliasName, 13227 SourceLocation PragmaLoc, 13228 SourceLocation NameLoc, 13229 SourceLocation AliasNameLoc) { 13230 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13231 LookupOrdinaryName); 13232 WeakInfo W = WeakInfo(Name, NameLoc); 13233 13234 if (PrevDecl) { 13235 if (!PrevDecl->hasAttr<AliasAttr>()) 13236 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13237 DeclApplyPragmaWeak(TUScope, ND, W); 13238 } else { 13239 (void)WeakUndeclaredIdentifiers.insert( 13240 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13241 } 13242 } 13243 13244 Decl *Sema::getObjCDeclContext() const { 13245 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13246 } 13247 13248 AvailabilityResult Sema::getCurContextAvailability() const { 13249 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13250 // If we are within an Objective-C method, we should consult 13251 // both the availability of the method as well as the 13252 // enclosing class. If the class is (say) deprecated, 13253 // the entire method is considered deprecated from the 13254 // purpose of checking if the current context is deprecated. 13255 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13256 AvailabilityResult R = MD->getAvailability(); 13257 if (R != AR_Available) 13258 return R; 13259 D = MD->getClassInterface(); 13260 } 13261 // If we are within an Objective-c @implementation, it 13262 // gets the same availability context as the @interface. 13263 else if (const ObjCImplementationDecl *ID = 13264 dyn_cast<ObjCImplementationDecl>(D)) { 13265 D = ID->getClassInterface(); 13266 } 13267 return D->getAvailability(); 13268 } 13269