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 "clang/Sema/Initialization.h" 16 #include "clang/Sema/Lookup.h" 17 #include "clang/Sema/CXXFieldCollector.h" 18 #include "clang/Sema/Scope.h" 19 #include "clang/Sema/ScopeInfo.h" 20 #include "TypeLocBuilder.h" 21 #include "clang/AST/APValue.h" 22 #include "clang/AST/ASTConsumer.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/CXXInheritance.h" 25 #include "clang/AST/DeclCXX.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/AST/DeclTemplate.h" 28 #include "clang/AST/EvaluatedExprVisitor.h" 29 #include "clang/AST/ExprCXX.h" 30 #include "clang/AST/StmtCXX.h" 31 #include "clang/AST/CharUnits.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/ParsedTemplate.h" 34 #include "clang/Parse/ParseDiagnostic.h" 35 #include "clang/Basic/PartialDiagnostic.h" 36 #include "clang/Basic/SourceManager.h" 37 #include "clang/Basic/TargetInfo.h" 38 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 39 #include "clang/Lex/Preprocessor.h" 40 #include "clang/Lex/HeaderSearch.h" 41 #include "llvm/ADT/Triple.h" 42 #include <algorithm> 43 #include <cstring> 44 #include <functional> 45 using namespace clang; 46 using namespace sema; 47 48 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 49 if (OwnedType) { 50 Decl *Group[2] = { OwnedType, Ptr }; 51 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 52 } 53 54 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 55 } 56 57 /// \brief If the identifier refers to a type name within this scope, 58 /// return the declaration of that type. 59 /// 60 /// This routine performs ordinary name lookup of the identifier II 61 /// within the given scope, with optional C++ scope specifier SS, to 62 /// determine whether the name refers to a type. If so, returns an 63 /// opaque pointer (actually a QualType) corresponding to that 64 /// type. Otherwise, returns NULL. 65 /// 66 /// If name lookup results in an ambiguity, this routine will complain 67 /// and then return NULL. 68 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 69 Scope *S, CXXScopeSpec *SS, 70 bool isClassName, bool HasTrailingDot, 71 ParsedType ObjectTypePtr, 72 bool WantNontrivialTypeSourceInfo) { 73 // Determine where we will perform name lookup. 74 DeclContext *LookupCtx = 0; 75 if (ObjectTypePtr) { 76 QualType ObjectType = ObjectTypePtr.get(); 77 if (ObjectType->isRecordType()) 78 LookupCtx = computeDeclContext(ObjectType); 79 } else if (SS && SS->isNotEmpty()) { 80 LookupCtx = computeDeclContext(*SS, false); 81 82 if (!LookupCtx) { 83 if (isDependentScopeSpecifier(*SS)) { 84 // C++ [temp.res]p3: 85 // A qualified-id that refers to a type and in which the 86 // nested-name-specifier depends on a template-parameter (14.6.2) 87 // shall be prefixed by the keyword typename to indicate that the 88 // qualified-id denotes a type, forming an 89 // elaborated-type-specifier (7.1.5.3). 90 // 91 // We therefore do not perform any name lookup if the result would 92 // refer to a member of an unknown specialization. 93 if (!isClassName) 94 return ParsedType(); 95 96 // We know from the grammar that this name refers to a type, 97 // so build a dependent node to describe the type. 98 if (WantNontrivialTypeSourceInfo) 99 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 100 101 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 102 QualType T = 103 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 104 II, NameLoc); 105 106 return ParsedType::make(T); 107 } 108 109 return ParsedType(); 110 } 111 112 if (!LookupCtx->isDependentContext() && 113 RequireCompleteDeclContext(*SS, LookupCtx)) 114 return ParsedType(); 115 } 116 117 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 118 // lookup for class-names. 119 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 120 LookupOrdinaryName; 121 LookupResult Result(*this, &II, NameLoc, Kind); 122 if (LookupCtx) { 123 // Perform "qualified" name lookup into the declaration context we 124 // computed, which is either the type of the base of a member access 125 // expression or the declaration context associated with a prior 126 // nested-name-specifier. 127 LookupQualifiedName(Result, LookupCtx); 128 129 if (ObjectTypePtr && Result.empty()) { 130 // C++ [basic.lookup.classref]p3: 131 // If the unqualified-id is ~type-name, the type-name is looked up 132 // in the context of the entire postfix-expression. If the type T of 133 // the object expression is of a class type C, the type-name is also 134 // looked up in the scope of class C. At least one of the lookups shall 135 // find a name that refers to (possibly cv-qualified) T. 136 LookupName(Result, S); 137 } 138 } else { 139 // Perform unqualified name lookup. 140 LookupName(Result, S); 141 } 142 143 NamedDecl *IIDecl = 0; 144 switch (Result.getResultKind()) { 145 case LookupResult::NotFound: 146 case LookupResult::NotFoundInCurrentInstantiation: 147 case LookupResult::FoundOverloaded: 148 case LookupResult::FoundUnresolvedValue: 149 Result.suppressDiagnostics(); 150 return ParsedType(); 151 152 case LookupResult::Ambiguous: 153 // Recover from type-hiding ambiguities by hiding the type. We'll 154 // do the lookup again when looking for an object, and we can 155 // diagnose the error then. If we don't do this, then the error 156 // about hiding the type will be immediately followed by an error 157 // that only makes sense if the identifier was treated like a type. 158 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 159 Result.suppressDiagnostics(); 160 return ParsedType(); 161 } 162 163 // Look to see if we have a type anywhere in the list of results. 164 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 165 Res != ResEnd; ++Res) { 166 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 167 if (!IIDecl || 168 (*Res)->getLocation().getRawEncoding() < 169 IIDecl->getLocation().getRawEncoding()) 170 IIDecl = *Res; 171 } 172 } 173 174 if (!IIDecl) { 175 // None of the entities we found is a type, so there is no way 176 // to even assume that the result is a type. In this case, don't 177 // complain about the ambiguity. The parser will either try to 178 // perform this lookup again (e.g., as an object name), which 179 // will produce the ambiguity, or will complain that it expected 180 // a type name. 181 Result.suppressDiagnostics(); 182 return ParsedType(); 183 } 184 185 // We found a type within the ambiguous lookup; diagnose the 186 // ambiguity and then return that type. This might be the right 187 // answer, or it might not be, but it suppresses any attempt to 188 // perform the name lookup again. 189 break; 190 191 case LookupResult::Found: 192 IIDecl = Result.getFoundDecl(); 193 break; 194 } 195 196 assert(IIDecl && "Didn't find decl"); 197 198 QualType T; 199 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 200 DiagnoseUseOfDecl(IIDecl, NameLoc); 201 202 if (T.isNull()) 203 T = Context.getTypeDeclType(TD); 204 205 if (SS && SS->isNotEmpty()) { 206 if (WantNontrivialTypeSourceInfo) { 207 // Construct a type with type-source information. 208 TypeLocBuilder Builder; 209 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 210 211 T = getElaboratedType(ETK_None, *SS, T); 212 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 213 ElabTL.setKeywordLoc(SourceLocation()); 214 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 215 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 216 } else { 217 T = getElaboratedType(ETK_None, *SS, T); 218 } 219 } 220 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 221 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 222 if (!HasTrailingDot) 223 T = Context.getObjCInterfaceType(IDecl); 224 } 225 226 if (T.isNull()) { 227 // If it's not plausibly a type, suppress diagnostics. 228 Result.suppressDiagnostics(); 229 return ParsedType(); 230 } 231 return ParsedType::make(T); 232 } 233 234 /// isTagName() - This method is called *for error recovery purposes only* 235 /// to determine if the specified name is a valid tag name ("struct foo"). If 236 /// so, this returns the TST for the tag corresponding to it (TST_enum, 237 /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 238 /// where the user forgot to specify the tag. 239 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 240 // Do a tag name lookup in this scope. 241 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 242 LookupName(R, S, false); 243 R.suppressDiagnostics(); 244 if (R.getResultKind() == LookupResult::Found) 245 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 246 switch (TD->getTagKind()) { 247 default: return DeclSpec::TST_unspecified; 248 case TTK_Struct: return DeclSpec::TST_struct; 249 case TTK_Union: return DeclSpec::TST_union; 250 case TTK_Class: return DeclSpec::TST_class; 251 case TTK_Enum: return DeclSpec::TST_enum; 252 } 253 } 254 255 return DeclSpec::TST_unspecified; 256 } 257 258 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 259 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 260 /// then downgrade the missing typename error to a warning. 261 /// This is needed for MSVC compatibility; Example: 262 /// @code 263 /// template<class T> class A { 264 /// public: 265 /// typedef int TYPE; 266 /// }; 267 /// template<class T> class B : public A<T> { 268 /// public: 269 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 270 /// }; 271 /// @endcode 272 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS) { 273 if (CurContext->isRecord()) { 274 const Type *Ty = SS->getScopeRep()->getAsType(); 275 276 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 277 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 278 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 279 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 280 return true; 281 } 282 return false; 283 } 284 285 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 286 SourceLocation IILoc, 287 Scope *S, 288 CXXScopeSpec *SS, 289 ParsedType &SuggestedType) { 290 // We don't have anything to suggest (yet). 291 SuggestedType = ParsedType(); 292 293 // There may have been a typo in the name of the type. Look up typo 294 // results, in case we have something that we can suggest. 295 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc), 296 LookupOrdinaryName, S, SS, NULL, 297 false, CTC_Type)) { 298 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 299 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 300 301 if (Corrected.isKeyword()) { 302 // We corrected to a keyword. 303 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it. 304 Diag(IILoc, diag::err_unknown_typename_suggest) 305 << &II << CorrectedQuotedStr; 306 return true; 307 } else { 308 NamedDecl *Result = Corrected.getCorrectionDecl(); 309 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) && 310 !Result->isInvalidDecl()) { 311 // We found a similarly-named type or interface; suggest that. 312 if (!SS || !SS->isSet()) 313 Diag(IILoc, diag::err_unknown_typename_suggest) 314 << &II << CorrectedQuotedStr 315 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 316 else if (DeclContext *DC = computeDeclContext(*SS, false)) 317 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 318 << &II << DC << CorrectedQuotedStr << SS->getRange() 319 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 320 else 321 llvm_unreachable("could not have corrected a typo here"); 322 323 Diag(Result->getLocation(), diag::note_previous_decl) 324 << CorrectedQuotedStr; 325 326 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 327 false, false, ParsedType(), 328 /*NonTrivialTypeSourceInfo=*/true); 329 return true; 330 } 331 } 332 } 333 334 if (getLangOptions().CPlusPlus) { 335 // See if II is a class template that the user forgot to pass arguments to. 336 UnqualifiedId Name; 337 Name.setIdentifier(&II, IILoc); 338 CXXScopeSpec EmptySS; 339 TemplateTy TemplateResult; 340 bool MemberOfUnknownSpecialization; 341 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 342 Name, ParsedType(), true, TemplateResult, 343 MemberOfUnknownSpecialization) == TNK_Type_template) { 344 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 345 Diag(IILoc, diag::err_template_missing_args) << TplName; 346 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 347 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 348 << TplDecl->getTemplateParameters()->getSourceRange(); 349 } 350 return true; 351 } 352 } 353 354 // FIXME: Should we move the logic that tries to recover from a missing tag 355 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 356 357 if (!SS || (!SS->isSet() && !SS->isInvalid())) 358 Diag(IILoc, diag::err_unknown_typename) << &II; 359 else if (DeclContext *DC = computeDeclContext(*SS, false)) 360 Diag(IILoc, diag::err_typename_nested_not_found) 361 << &II << DC << SS->getRange(); 362 else if (isDependentScopeSpecifier(*SS)) { 363 unsigned DiagID = diag::err_typename_missing; 364 if (getLangOptions().Microsoft && isMicrosoftMissingTypename(SS)) 365 DiagID = diag::warn_typename_missing; 366 367 Diag(SS->getRange().getBegin(), DiagID) 368 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName() 369 << SourceRange(SS->getRange().getBegin(), IILoc) 370 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 371 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get(); 372 } else { 373 assert(SS && SS->isInvalid() && 374 "Invalid scope specifier has already been diagnosed"); 375 } 376 377 return true; 378 } 379 380 /// \brief Determine whether the given result set contains either a type name 381 /// or 382 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 383 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus && 384 NextToken.is(tok::less); 385 386 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 387 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 388 return true; 389 390 if (CheckTemplate && isa<TemplateDecl>(*I)) 391 return true; 392 } 393 394 return false; 395 } 396 397 Sema::NameClassification Sema::ClassifyName(Scope *S, 398 CXXScopeSpec &SS, 399 IdentifierInfo *&Name, 400 SourceLocation NameLoc, 401 const Token &NextToken) { 402 DeclarationNameInfo NameInfo(Name, NameLoc); 403 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 404 405 if (NextToken.is(tok::coloncolon)) { 406 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 407 QualType(), false, SS, 0, false); 408 409 } 410 411 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 412 LookupParsedName(Result, S, &SS, !CurMethod); 413 414 // Perform lookup for Objective-C instance variables (including automatically 415 // synthesized instance variables), if we're in an Objective-C method. 416 // FIXME: This lookup really, really needs to be folded in to the normal 417 // unqualified lookup mechanism. 418 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 419 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 420 if (E.get() || E.isInvalid()) 421 return E; 422 423 // Synthesize ivars lazily. 424 if (getLangOptions().ObjCDefaultSynthProperties && 425 getLangOptions().ObjCNonFragileABI2) { 426 if (SynthesizeProvisionalIvar(Result, Name, NameLoc)) { 427 if (const ObjCPropertyDecl *Property = 428 canSynthesizeProvisionalIvar(Name)) { 429 Diag(NameLoc, diag::warn_synthesized_ivar_access) << Name; 430 Diag(Property->getLocation(), diag::note_property_declare); 431 } 432 433 // FIXME: This is strange. Shouldn't we just take the ivar returned 434 // from SynthesizeProvisionalIvar and continue with that? 435 E = LookupInObjCMethod(Result, S, Name, true); 436 if (E.get() || E.isInvalid()) 437 return E; 438 } 439 } 440 } 441 442 bool SecondTry = false; 443 bool IsFilteredTemplateName = false; 444 445 Corrected: 446 switch (Result.getResultKind()) { 447 case LookupResult::NotFound: 448 // If an unqualified-id is followed by a '(', then we have a function 449 // call. 450 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 451 // In C++, this is an ADL-only call. 452 // FIXME: Reference? 453 if (getLangOptions().CPlusPlus) 454 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 455 456 // C90 6.3.2.2: 457 // If the expression that precedes the parenthesized argument list in a 458 // function call consists solely of an identifier, and if no 459 // declaration is visible for this identifier, the identifier is 460 // implicitly declared exactly as if, in the innermost block containing 461 // the function call, the declaration 462 // 463 // extern int identifier (); 464 // 465 // appeared. 466 // 467 // We also allow this in C99 as an extension. 468 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 469 Result.addDecl(D); 470 Result.resolveKind(); 471 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 472 } 473 } 474 475 // In C, we first see whether there is a tag type by the same name, in 476 // which case it's likely that the user just forget to write "enum", 477 // "struct", or "union". 478 if (!getLangOptions().CPlusPlus && !SecondTry) { 479 Result.clear(LookupTagName); 480 LookupParsedName(Result, S, &SS); 481 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) { 482 const char *TagName = 0; 483 const char *FixItTagName = 0; 484 switch (Tag->getTagKind()) { 485 case TTK_Class: 486 TagName = "class"; 487 FixItTagName = "class "; 488 break; 489 490 case TTK_Enum: 491 TagName = "enum"; 492 FixItTagName = "enum "; 493 break; 494 495 case TTK_Struct: 496 TagName = "struct"; 497 FixItTagName = "struct "; 498 break; 499 500 case TTK_Union: 501 TagName = "union"; 502 FixItTagName = "union "; 503 break; 504 } 505 506 Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 507 << Name << TagName << getLangOptions().CPlusPlus 508 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 509 break; 510 } 511 512 Result.clear(LookupOrdinaryName); 513 } 514 515 // Perform typo correction to determine if there is another name that is 516 // close to this name. 517 if (!SecondTry) { 518 SecondTry = true; 519 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 520 Result.getLookupKind(), S, &SS)) { 521 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 522 unsigned QualifiedDiag = diag::err_no_member_suggest; 523 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 524 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 525 526 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 527 NamedDecl *UnderlyingFirstDecl 528 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 529 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 530 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 531 UnqualifiedDiag = diag::err_no_template_suggest; 532 QualifiedDiag = diag::err_no_member_template_suggest; 533 } else if (UnderlyingFirstDecl && 534 (isa<TypeDecl>(UnderlyingFirstDecl) || 535 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 536 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 537 UnqualifiedDiag = diag::err_unknown_typename_suggest; 538 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 539 } 540 541 if (SS.isEmpty()) 542 Diag(NameLoc, UnqualifiedDiag) 543 << Name << CorrectedQuotedStr 544 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 545 else 546 Diag(NameLoc, QualifiedDiag) 547 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 548 << SS.getRange() 549 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 550 551 // Update the name, so that the caller has the new name. 552 Name = Corrected.getCorrectionAsIdentifierInfo(); 553 554 // Also update the LookupResult... 555 // FIXME: This should probably go away at some point 556 Result.clear(); 557 Result.setLookupName(Corrected.getCorrection()); 558 if (FirstDecl) Result.addDecl(FirstDecl); 559 560 // Typo correction corrected to a keyword. 561 if (Corrected.isKeyword()) 562 return Corrected.getCorrectionAsIdentifierInfo(); 563 564 if (FirstDecl) 565 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 566 << CorrectedQuotedStr; 567 568 // If we found an Objective-C instance variable, let 569 // LookupInObjCMethod build the appropriate expression to 570 // reference the ivar. 571 // FIXME: This is a gross hack. 572 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 573 Result.clear(); 574 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 575 return move(E); 576 } 577 578 goto Corrected; 579 } 580 } 581 582 // We failed to correct; just fall through and let the parser deal with it. 583 Result.suppressDiagnostics(); 584 return NameClassification::Unknown(); 585 586 case LookupResult::NotFoundInCurrentInstantiation: 587 // We performed name lookup into the current instantiation, and there were 588 // dependent bases, so we treat this result the same way as any other 589 // dependent nested-name-specifier. 590 591 // C++ [temp.res]p2: 592 // A name used in a template declaration or definition and that is 593 // dependent on a template-parameter is assumed not to name a type 594 // unless the applicable name lookup finds a type name or the name is 595 // qualified by the keyword typename. 596 // 597 // FIXME: If the next token is '<', we might want to ask the parser to 598 // perform some heroics to see if we actually have a 599 // template-argument-list, which would indicate a missing 'template' 600 // keyword here. 601 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0); 602 603 case LookupResult::Found: 604 case LookupResult::FoundOverloaded: 605 case LookupResult::FoundUnresolvedValue: 606 break; 607 608 case LookupResult::Ambiguous: 609 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 610 hasAnyAcceptableTemplateNames(Result)) { 611 // C++ [temp.local]p3: 612 // A lookup that finds an injected-class-name (10.2) can result in an 613 // ambiguity in certain cases (for example, if it is found in more than 614 // one base class). If all of the injected-class-names that are found 615 // refer to specializations of the same class template, and if the name 616 // is followed by a template-argument-list, the reference refers to the 617 // class template itself and not a specialization thereof, and is not 618 // ambiguous. 619 // 620 // This filtering can make an ambiguous result into an unambiguous one, 621 // so try again after filtering out template names. 622 FilterAcceptableTemplateNames(Result); 623 if (!Result.isAmbiguous()) { 624 IsFilteredTemplateName = true; 625 break; 626 } 627 } 628 629 // Diagnose the ambiguity and return an error. 630 return NameClassification::Error(); 631 } 632 633 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 634 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 635 // C++ [temp.names]p3: 636 // After name lookup (3.4) finds that a name is a template-name or that 637 // an operator-function-id or a literal- operator-id refers to a set of 638 // overloaded functions any member of which is a function template if 639 // this is followed by a <, the < is always taken as the delimiter of a 640 // template-argument-list and never as the less-than operator. 641 if (!IsFilteredTemplateName) 642 FilterAcceptableTemplateNames(Result); 643 644 if (!Result.empty()) { 645 bool IsFunctionTemplate; 646 TemplateName Template; 647 if (Result.end() - Result.begin() > 1) { 648 IsFunctionTemplate = true; 649 Template = Context.getOverloadedTemplateName(Result.begin(), 650 Result.end()); 651 } else { 652 TemplateDecl *TD 653 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 654 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 655 656 if (SS.isSet() && !SS.isInvalid()) 657 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 658 /*TemplateKeyword=*/false, 659 TD); 660 else 661 Template = TemplateName(TD); 662 } 663 664 if (IsFunctionTemplate) { 665 // Function templates always go through overload resolution, at which 666 // point we'll perform the various checks (e.g., accessibility) we need 667 // to based on which function we selected. 668 Result.suppressDiagnostics(); 669 670 return NameClassification::FunctionTemplate(Template); 671 } 672 673 return NameClassification::TypeTemplate(Template); 674 } 675 } 676 677 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 678 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 679 DiagnoseUseOfDecl(Type, NameLoc); 680 QualType T = Context.getTypeDeclType(Type); 681 return ParsedType::make(T); 682 } 683 684 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 685 if (!Class) { 686 // FIXME: It's unfortunate that we don't have a Type node for handling this. 687 if (ObjCCompatibleAliasDecl *Alias 688 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 689 Class = Alias->getClassInterface(); 690 } 691 692 if (Class) { 693 DiagnoseUseOfDecl(Class, NameLoc); 694 695 if (NextToken.is(tok::period)) { 696 // Interface. <something> is parsed as a property reference expression. 697 // Just return "unknown" as a fall-through for now. 698 Result.suppressDiagnostics(); 699 return NameClassification::Unknown(); 700 } 701 702 QualType T = Context.getObjCInterfaceType(Class); 703 return ParsedType::make(T); 704 } 705 706 if (!Result.empty() && (*Result.begin())->isCXXClassMember()) 707 return BuildPossibleImplicitMemberExpr(SS, Result, 0); 708 709 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 710 return BuildDeclarationNameExpr(SS, Result, ADL); 711 } 712 713 // Determines the context to return to after temporarily entering a 714 // context. This depends in an unnecessarily complicated way on the 715 // exact ordering of callbacks from the parser. 716 DeclContext *Sema::getContainingDC(DeclContext *DC) { 717 718 // Functions defined inline within classes aren't parsed until we've 719 // finished parsing the top-level class, so the top-level class is 720 // the context we'll need to return to. 721 if (isa<FunctionDecl>(DC)) { 722 DC = DC->getLexicalParent(); 723 724 // A function not defined within a class will always return to its 725 // lexical context. 726 if (!isa<CXXRecordDecl>(DC)) 727 return DC; 728 729 // A C++ inline method/friend is parsed *after* the topmost class 730 // it was declared in is fully parsed ("complete"); the topmost 731 // class is the context we need to return to. 732 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 733 DC = RD; 734 735 // Return the declaration context of the topmost class the inline method is 736 // declared in. 737 return DC; 738 } 739 740 // ObjCMethodDecls are parsed (for some reason) outside the context 741 // of the class. 742 if (isa<ObjCMethodDecl>(DC)) 743 return DC->getLexicalParent()->getLexicalParent(); 744 745 return DC->getLexicalParent(); 746 } 747 748 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 749 assert(getContainingDC(DC) == CurContext && 750 "The next DeclContext should be lexically contained in the current one."); 751 CurContext = DC; 752 S->setEntity(DC); 753 } 754 755 void Sema::PopDeclContext() { 756 assert(CurContext && "DeclContext imbalance!"); 757 758 CurContext = getContainingDC(CurContext); 759 assert(CurContext && "Popped translation unit!"); 760 } 761 762 /// EnterDeclaratorContext - Used when we must lookup names in the context 763 /// of a declarator's nested name specifier. 764 /// 765 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 766 // C++0x [basic.lookup.unqual]p13: 767 // A name used in the definition of a static data member of class 768 // X (after the qualified-id of the static member) is looked up as 769 // if the name was used in a member function of X. 770 // C++0x [basic.lookup.unqual]p14: 771 // If a variable member of a namespace is defined outside of the 772 // scope of its namespace then any name used in the definition of 773 // the variable member (after the declarator-id) is looked up as 774 // if the definition of the variable member occurred in its 775 // namespace. 776 // Both of these imply that we should push a scope whose context 777 // is the semantic context of the declaration. We can't use 778 // PushDeclContext here because that context is not necessarily 779 // lexically contained in the current context. Fortunately, 780 // the containing scope should have the appropriate information. 781 782 assert(!S->getEntity() && "scope already has entity"); 783 784 #ifndef NDEBUG 785 Scope *Ancestor = S->getParent(); 786 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 787 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 788 #endif 789 790 CurContext = DC; 791 S->setEntity(DC); 792 } 793 794 void Sema::ExitDeclaratorContext(Scope *S) { 795 assert(S->getEntity() == CurContext && "Context imbalance!"); 796 797 // Switch back to the lexical context. The safety of this is 798 // enforced by an assert in EnterDeclaratorContext. 799 Scope *Ancestor = S->getParent(); 800 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 801 CurContext = (DeclContext*) Ancestor->getEntity(); 802 803 // We don't need to do anything with the scope, which is going to 804 // disappear. 805 } 806 807 /// \brief Determine whether we allow overloading of the function 808 /// PrevDecl with another declaration. 809 /// 810 /// This routine determines whether overloading is possible, not 811 /// whether some new function is actually an overload. It will return 812 /// true in C++ (where we can always provide overloads) or, as an 813 /// extension, in C when the previous function is already an 814 /// overloaded function declaration or has the "overloadable" 815 /// attribute. 816 static bool AllowOverloadingOfFunction(LookupResult &Previous, 817 ASTContext &Context) { 818 if (Context.getLangOptions().CPlusPlus) 819 return true; 820 821 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 822 return true; 823 824 return (Previous.getResultKind() == LookupResult::Found 825 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 826 } 827 828 /// Add this decl to the scope shadowed decl chains. 829 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 830 // Move up the scope chain until we find the nearest enclosing 831 // non-transparent context. The declaration will be introduced into this 832 // scope. 833 while (S->getEntity() && 834 ((DeclContext *)S->getEntity())->isTransparentContext()) 835 S = S->getParent(); 836 837 // Add scoped declarations into their context, so that they can be 838 // found later. Declarations without a context won't be inserted 839 // into any context. 840 if (AddToContext) 841 CurContext->addDecl(D); 842 843 // Out-of-line definitions shouldn't be pushed into scope in C++. 844 // Out-of-line variable and function definitions shouldn't even in C. 845 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 846 D->isOutOfLine()) 847 return; 848 849 // Template instantiations should also not be pushed into scope. 850 if (isa<FunctionDecl>(D) && 851 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 852 return; 853 854 // If this replaces anything in the current scope, 855 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 856 IEnd = IdResolver.end(); 857 for (; I != IEnd; ++I) { 858 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 859 S->RemoveDecl(*I); 860 IdResolver.RemoveDecl(*I); 861 862 // Should only need to replace one decl. 863 break; 864 } 865 } 866 867 S->AddDecl(D); 868 869 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 870 // Implicitly-generated labels may end up getting generated in an order that 871 // isn't strictly lexical, which breaks name lookup. Be careful to insert 872 // the label at the appropriate place in the identifier chain. 873 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 874 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 875 if (IDC == CurContext) { 876 if (!S->isDeclScope(*I)) 877 continue; 878 } else if (IDC->Encloses(CurContext)) 879 break; 880 } 881 882 IdResolver.InsertDeclAfter(I, D); 883 } else { 884 IdResolver.AddDecl(D); 885 } 886 } 887 888 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 889 bool ExplicitInstantiationOrSpecialization) { 890 return IdResolver.isDeclInScope(D, Ctx, Context, S, 891 ExplicitInstantiationOrSpecialization); 892 } 893 894 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 895 DeclContext *TargetDC = DC->getPrimaryContext(); 896 do { 897 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 898 if (ScopeDC->getPrimaryContext() == TargetDC) 899 return S; 900 } while ((S = S->getParent())); 901 902 return 0; 903 } 904 905 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 906 DeclContext*, 907 ASTContext&); 908 909 /// Filters out lookup results that don't fall within the given scope 910 /// as determined by isDeclInScope. 911 void Sema::FilterLookupForScope(LookupResult &R, 912 DeclContext *Ctx, Scope *S, 913 bool ConsiderLinkage, 914 bool ExplicitInstantiationOrSpecialization) { 915 LookupResult::Filter F = R.makeFilter(); 916 while (F.hasNext()) { 917 NamedDecl *D = F.next(); 918 919 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 920 continue; 921 922 if (ConsiderLinkage && 923 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 924 continue; 925 926 F.erase(); 927 } 928 929 F.done(); 930 } 931 932 static bool isUsingDecl(NamedDecl *D) { 933 return isa<UsingShadowDecl>(D) || 934 isa<UnresolvedUsingTypenameDecl>(D) || 935 isa<UnresolvedUsingValueDecl>(D); 936 } 937 938 /// Removes using shadow declarations from the lookup results. 939 static void RemoveUsingDecls(LookupResult &R) { 940 LookupResult::Filter F = R.makeFilter(); 941 while (F.hasNext()) 942 if (isUsingDecl(F.next())) 943 F.erase(); 944 945 F.done(); 946 } 947 948 /// \brief Check for this common pattern: 949 /// @code 950 /// class S { 951 /// S(const S&); // DO NOT IMPLEMENT 952 /// void operator=(const S&); // DO NOT IMPLEMENT 953 /// }; 954 /// @endcode 955 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 956 // FIXME: Should check for private access too but access is set after we get 957 // the decl here. 958 if (D->doesThisDeclarationHaveABody()) 959 return false; 960 961 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 962 return CD->isCopyConstructor(); 963 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 964 return Method->isCopyAssignmentOperator(); 965 return false; 966 } 967 968 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 969 assert(D); 970 971 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 972 return false; 973 974 // Ignore class templates. 975 if (D->getDeclContext()->isDependentContext() || 976 D->getLexicalDeclContext()->isDependentContext()) 977 return false; 978 979 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 980 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 981 return false; 982 983 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 984 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 985 return false; 986 } else { 987 // 'static inline' functions are used in headers; don't warn. 988 if (FD->getStorageClass() == SC_Static && 989 FD->isInlineSpecified()) 990 return false; 991 } 992 993 if (FD->doesThisDeclarationHaveABody() && 994 Context.DeclMustBeEmitted(FD)) 995 return false; 996 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 997 if (!VD->isFileVarDecl() || 998 VD->getType().isConstant(Context) || 999 Context.DeclMustBeEmitted(VD)) 1000 return false; 1001 1002 if (VD->isStaticDataMember() && 1003 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1004 return false; 1005 1006 } else { 1007 return false; 1008 } 1009 1010 // Only warn for unused decls internal to the translation unit. 1011 if (D->getLinkage() == ExternalLinkage) 1012 return false; 1013 1014 return true; 1015 } 1016 1017 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1018 if (!D) 1019 return; 1020 1021 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1022 const FunctionDecl *First = FD->getFirstDeclaration(); 1023 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1024 return; // First should already be in the vector. 1025 } 1026 1027 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1028 const VarDecl *First = VD->getFirstDeclaration(); 1029 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1030 return; // First should already be in the vector. 1031 } 1032 1033 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1034 UnusedFileScopedDecls.push_back(D); 1035 } 1036 1037 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1038 if (D->isInvalidDecl()) 1039 return false; 1040 1041 if (D->isUsed() || D->hasAttr<UnusedAttr>()) 1042 return false; 1043 1044 if (isa<LabelDecl>(D)) 1045 return true; 1046 1047 // White-list anything that isn't a local variable. 1048 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1049 !D->getDeclContext()->isFunctionOrMethod()) 1050 return false; 1051 1052 // Types of valid local variables should be complete, so this should succeed. 1053 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1054 1055 // White-list anything with an __attribute__((unused)) type. 1056 QualType Ty = VD->getType(); 1057 1058 // Only look at the outermost level of typedef. 1059 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 1060 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1061 return false; 1062 } 1063 1064 // If we failed to complete the type for some reason, or if the type is 1065 // dependent, don't diagnose the variable. 1066 if (Ty->isIncompleteType() || Ty->isDependentType()) 1067 return false; 1068 1069 if (const TagType *TT = Ty->getAs<TagType>()) { 1070 const TagDecl *Tag = TT->getDecl(); 1071 if (Tag->hasAttr<UnusedAttr>()) 1072 return false; 1073 1074 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1075 // FIXME: Checking for the presence of a user-declared constructor 1076 // isn't completely accurate; we'd prefer to check that the initializer 1077 // has no side effects. 1078 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor()) 1079 return false; 1080 } 1081 } 1082 1083 // TODO: __attribute__((unused)) templates? 1084 } 1085 1086 return true; 1087 } 1088 1089 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1090 /// unless they are marked attr(unused). 1091 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1092 if (!ShouldDiagnoseUnusedDecl(D)) 1093 return; 1094 1095 unsigned DiagID; 1096 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1097 DiagID = diag::warn_unused_exception_param; 1098 else if (isa<LabelDecl>(D)) 1099 DiagID = diag::warn_unused_label; 1100 else 1101 DiagID = diag::warn_unused_variable; 1102 1103 Diag(D->getLocation(), DiagID) << D->getDeclName(); 1104 } 1105 1106 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1107 // Verify that we have no forward references left. If so, there was a goto 1108 // or address of a label taken, but no definition of it. Label fwd 1109 // definitions are indicated with a null substmt. 1110 if (L->getStmt() == 0) 1111 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1112 } 1113 1114 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1115 if (S->decl_empty()) return; 1116 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1117 "Scope shouldn't contain decls!"); 1118 1119 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1120 I != E; ++I) { 1121 Decl *TmpD = (*I); 1122 assert(TmpD && "This decl didn't get pushed??"); 1123 1124 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1125 NamedDecl *D = cast<NamedDecl>(TmpD); 1126 1127 if (!D->getDeclName()) continue; 1128 1129 // Diagnose unused variables in this scope. 1130 if (!S->hasErrorOccurred()) 1131 DiagnoseUnusedDecl(D); 1132 1133 // If this was a forward reference to a label, verify it was defined. 1134 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1135 CheckPoppedLabel(LD, *this); 1136 1137 // Remove this name from our lexical scope. 1138 IdResolver.RemoveDecl(D); 1139 } 1140 } 1141 1142 /// \brief Look for an Objective-C class in the translation unit. 1143 /// 1144 /// \param Id The name of the Objective-C class we're looking for. If 1145 /// typo-correction fixes this name, the Id will be updated 1146 /// to the fixed name. 1147 /// 1148 /// \param IdLoc The location of the name in the translation unit. 1149 /// 1150 /// \param TypoCorrection If true, this routine will attempt typo correction 1151 /// if there is no class with the given name. 1152 /// 1153 /// \returns The declaration of the named Objective-C class, or NULL if the 1154 /// class could not be found. 1155 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1156 SourceLocation IdLoc, 1157 bool DoTypoCorrection) { 1158 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1159 // creation from this context. 1160 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1161 1162 if (!IDecl && DoTypoCorrection) { 1163 // Perform typo correction at the given location, but only if we 1164 // find an Objective-C class name. 1165 TypoCorrection C; 1166 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1167 TUScope, NULL, NULL, false, CTC_NoKeywords)) && 1168 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) { 1169 Diag(IdLoc, diag::err_undef_interface_suggest) 1170 << Id << IDecl->getDeclName() 1171 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1172 Diag(IDecl->getLocation(), diag::note_previous_decl) 1173 << IDecl->getDeclName(); 1174 1175 Id = IDecl->getIdentifier(); 1176 } 1177 } 1178 1179 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1180 } 1181 1182 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1183 /// from S, where a non-field would be declared. This routine copes 1184 /// with the difference between C and C++ scoping rules in structs and 1185 /// unions. For example, the following code is well-formed in C but 1186 /// ill-formed in C++: 1187 /// @code 1188 /// struct S6 { 1189 /// enum { BAR } e; 1190 /// }; 1191 /// 1192 /// void test_S6() { 1193 /// struct S6 a; 1194 /// a.e = BAR; 1195 /// } 1196 /// @endcode 1197 /// For the declaration of BAR, this routine will return a different 1198 /// scope. The scope S will be the scope of the unnamed enumeration 1199 /// within S6. In C++, this routine will return the scope associated 1200 /// with S6, because the enumeration's scope is a transparent 1201 /// context but structures can contain non-field names. In C, this 1202 /// routine will return the translation unit scope, since the 1203 /// enumeration's scope is a transparent context and structures cannot 1204 /// contain non-field names. 1205 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1206 while (((S->getFlags() & Scope::DeclScope) == 0) || 1207 (S->getEntity() && 1208 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1209 (S->isClassScope() && !getLangOptions().CPlusPlus)) 1210 S = S->getParent(); 1211 return S; 1212 } 1213 1214 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1215 /// file scope. lazily create a decl for it. ForRedeclaration is true 1216 /// if we're creating this built-in in anticipation of redeclaring the 1217 /// built-in. 1218 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1219 Scope *S, bool ForRedeclaration, 1220 SourceLocation Loc) { 1221 Builtin::ID BID = (Builtin::ID)bid; 1222 1223 ASTContext::GetBuiltinTypeError Error; 1224 QualType R = Context.GetBuiltinType(BID, Error); 1225 switch (Error) { 1226 case ASTContext::GE_None: 1227 // Okay 1228 break; 1229 1230 case ASTContext::GE_Missing_stdio: 1231 if (ForRedeclaration) 1232 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1233 << Context.BuiltinInfo.GetName(BID); 1234 return 0; 1235 1236 case ASTContext::GE_Missing_setjmp: 1237 if (ForRedeclaration) 1238 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1239 << Context.BuiltinInfo.GetName(BID); 1240 return 0; 1241 } 1242 1243 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1244 Diag(Loc, diag::ext_implicit_lib_function_decl) 1245 << Context.BuiltinInfo.GetName(BID) 1246 << R; 1247 if (Context.BuiltinInfo.getHeaderName(BID) && 1248 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1249 != Diagnostic::Ignored) 1250 Diag(Loc, diag::note_please_include_header) 1251 << Context.BuiltinInfo.getHeaderName(BID) 1252 << Context.BuiltinInfo.GetName(BID); 1253 } 1254 1255 FunctionDecl *New = FunctionDecl::Create(Context, 1256 Context.getTranslationUnitDecl(), 1257 Loc, Loc, II, R, /*TInfo=*/0, 1258 SC_Extern, 1259 SC_None, false, 1260 /*hasPrototype=*/true); 1261 New->setImplicit(); 1262 1263 // Create Decl objects for each parameter, adding them to the 1264 // FunctionDecl. 1265 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1266 llvm::SmallVector<ParmVarDecl*, 16> Params; 1267 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1268 ParmVarDecl *parm = 1269 ParmVarDecl::Create(Context, New, SourceLocation(), 1270 SourceLocation(), 0, 1271 FT->getArgType(i), /*TInfo=*/0, 1272 SC_None, SC_None, 0); 1273 parm->setScopeInfo(0, i); 1274 Params.push_back(parm); 1275 } 1276 New->setParams(Params.data(), Params.size()); 1277 } 1278 1279 AddKnownFunctionAttributes(New); 1280 1281 // TUScope is the translation-unit scope to insert this function into. 1282 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1283 // relate Scopes to DeclContexts, and probably eliminate CurContext 1284 // entirely, but we're not there yet. 1285 DeclContext *SavedContext = CurContext; 1286 CurContext = Context.getTranslationUnitDecl(); 1287 PushOnScopeChains(New, TUScope); 1288 CurContext = SavedContext; 1289 return New; 1290 } 1291 1292 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1293 /// same name and scope as a previous declaration 'Old'. Figure out 1294 /// how to resolve this situation, merging decls or emitting 1295 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1296 /// 1297 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1298 // If the new decl is known invalid already, don't bother doing any 1299 // merging checks. 1300 if (New->isInvalidDecl()) return; 1301 1302 // Allow multiple definitions for ObjC built-in typedefs. 1303 // FIXME: Verify the underlying types are equivalent! 1304 if (getLangOptions().ObjC1) { 1305 const IdentifierInfo *TypeID = New->getIdentifier(); 1306 switch (TypeID->getLength()) { 1307 default: break; 1308 case 2: 1309 if (!TypeID->isStr("id")) 1310 break; 1311 Context.ObjCIdRedefinitionType = New->getUnderlyingType(); 1312 // Install the built-in type for 'id', ignoring the current definition. 1313 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1314 return; 1315 case 5: 1316 if (!TypeID->isStr("Class")) 1317 break; 1318 Context.ObjCClassRedefinitionType = New->getUnderlyingType(); 1319 // Install the built-in type for 'Class', ignoring the current definition. 1320 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1321 return; 1322 case 3: 1323 if (!TypeID->isStr("SEL")) 1324 break; 1325 Context.ObjCSelRedefinitionType = New->getUnderlyingType(); 1326 // Install the built-in type for 'SEL', ignoring the current definition. 1327 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1328 return; 1329 case 8: 1330 if (!TypeID->isStr("Protocol")) 1331 break; 1332 Context.setObjCProtoType(New->getUnderlyingType()); 1333 return; 1334 } 1335 // Fall through - the typedef name was not a builtin type. 1336 } 1337 1338 // Verify the old decl was also a type. 1339 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1340 if (!Old) { 1341 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1342 << New->getDeclName(); 1343 1344 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1345 if (OldD->getLocation().isValid()) 1346 Diag(OldD->getLocation(), diag::note_previous_definition); 1347 1348 return New->setInvalidDecl(); 1349 } 1350 1351 // If the old declaration is invalid, just give up here. 1352 if (Old->isInvalidDecl()) 1353 return New->setInvalidDecl(); 1354 1355 // Determine the "old" type we'll use for checking and diagnostics. 1356 QualType OldType; 1357 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1358 OldType = OldTypedef->getUnderlyingType(); 1359 else 1360 OldType = Context.getTypeDeclType(Old); 1361 1362 // If the typedef types are not identical, reject them in all languages and 1363 // with any extensions enabled. 1364 1365 if (OldType != New->getUnderlyingType() && 1366 Context.getCanonicalType(OldType) != 1367 Context.getCanonicalType(New->getUnderlyingType())) { 1368 int Kind = 0; 1369 if (isa<TypeAliasDecl>(Old)) 1370 Kind = 1; 1371 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1372 << Kind << New->getUnderlyingType() << OldType; 1373 if (Old->getLocation().isValid()) 1374 Diag(Old->getLocation(), diag::note_previous_definition); 1375 return New->setInvalidDecl(); 1376 } 1377 1378 // The types match. Link up the redeclaration chain if the old 1379 // declaration was a typedef. 1380 // FIXME: this is a potential source of weirdness if the type 1381 // spellings don't match exactly. 1382 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1383 New->setPreviousDeclaration(Typedef); 1384 1385 if (getLangOptions().Microsoft) 1386 return; 1387 1388 if (getLangOptions().CPlusPlus) { 1389 // C++ [dcl.typedef]p2: 1390 // In a given non-class scope, a typedef specifier can be used to 1391 // redefine the name of any type declared in that scope to refer 1392 // to the type to which it already refers. 1393 if (!isa<CXXRecordDecl>(CurContext)) 1394 return; 1395 1396 // C++0x [dcl.typedef]p4: 1397 // In a given class scope, a typedef specifier can be used to redefine 1398 // any class-name declared in that scope that is not also a typedef-name 1399 // to refer to the type to which it already refers. 1400 // 1401 // This wording came in via DR424, which was a correction to the 1402 // wording in DR56, which accidentally banned code like: 1403 // 1404 // struct S { 1405 // typedef struct A { } A; 1406 // }; 1407 // 1408 // in the C++03 standard. We implement the C++0x semantics, which 1409 // allow the above but disallow 1410 // 1411 // struct S { 1412 // typedef int I; 1413 // typedef int I; 1414 // }; 1415 // 1416 // since that was the intent of DR56. 1417 if (!isa<TypedefNameDecl>(Old)) 1418 return; 1419 1420 Diag(New->getLocation(), diag::err_redefinition) 1421 << New->getDeclName(); 1422 Diag(Old->getLocation(), diag::note_previous_definition); 1423 return New->setInvalidDecl(); 1424 } 1425 1426 // If we have a redefinition of a typedef in C, emit a warning. This warning 1427 // is normally mapped to an error, but can be controlled with 1428 // -Wtypedef-redefinition. If either the original or the redefinition is 1429 // in a system header, don't emit this for compatibility with GCC. 1430 if (getDiagnostics().getSuppressSystemWarnings() && 1431 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1432 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1433 return; 1434 1435 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1436 << New->getDeclName(); 1437 Diag(Old->getLocation(), diag::note_previous_definition); 1438 return; 1439 } 1440 1441 /// DeclhasAttr - returns true if decl Declaration already has the target 1442 /// attribute. 1443 static bool 1444 DeclHasAttr(const Decl *D, const Attr *A) { 1445 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1446 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1447 if ((*i)->getKind() == A->getKind()) { 1448 // FIXME: Don't hardcode this check 1449 if (OA && isa<OwnershipAttr>(*i)) 1450 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1451 return true; 1452 } 1453 1454 return false; 1455 } 1456 1457 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 1458 static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl, 1459 ASTContext &C) { 1460 if (!oldDecl->hasAttrs()) 1461 return; 1462 1463 bool foundAny = newDecl->hasAttrs(); 1464 1465 // Ensure that any moving of objects within the allocated map is done before 1466 // we process them. 1467 if (!foundAny) newDecl->setAttrs(AttrVec()); 1468 1469 for (specific_attr_iterator<InheritableAttr> 1470 i = oldDecl->specific_attr_begin<InheritableAttr>(), 1471 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) { 1472 if (!DeclHasAttr(newDecl, *i)) { 1473 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C)); 1474 newAttr->setInherited(true); 1475 newDecl->addAttr(newAttr); 1476 foundAny = true; 1477 } 1478 } 1479 1480 if (!foundAny) newDecl->dropAttrs(); 1481 } 1482 1483 /// mergeParamDeclAttributes - Copy attributes from the old parameter 1484 /// to the new one. 1485 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 1486 const ParmVarDecl *oldDecl, 1487 ASTContext &C) { 1488 if (!oldDecl->hasAttrs()) 1489 return; 1490 1491 bool foundAny = newDecl->hasAttrs(); 1492 1493 // Ensure that any moving of objects within the allocated map is 1494 // done before we process them. 1495 if (!foundAny) newDecl->setAttrs(AttrVec()); 1496 1497 for (specific_attr_iterator<InheritableParamAttr> 1498 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 1499 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 1500 if (!DeclHasAttr(newDecl, *i)) { 1501 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 1502 newAttr->setInherited(true); 1503 newDecl->addAttr(newAttr); 1504 foundAny = true; 1505 } 1506 } 1507 1508 if (!foundAny) newDecl->dropAttrs(); 1509 } 1510 1511 namespace { 1512 1513 /// Used in MergeFunctionDecl to keep track of function parameters in 1514 /// C. 1515 struct GNUCompatibleParamWarning { 1516 ParmVarDecl *OldParm; 1517 ParmVarDecl *NewParm; 1518 QualType PromotedType; 1519 }; 1520 1521 } 1522 1523 /// getSpecialMember - get the special member enum for a method. 1524 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1525 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1526 if (Ctor->isDefaultConstructor()) 1527 return Sema::CXXDefaultConstructor; 1528 1529 if (Ctor->isCopyConstructor()) 1530 return Sema::CXXCopyConstructor; 1531 1532 if (Ctor->isMoveConstructor()) 1533 return Sema::CXXMoveConstructor; 1534 } else if (isa<CXXDestructorDecl>(MD)) { 1535 return Sema::CXXDestructor; 1536 } else if (MD->isCopyAssignmentOperator()) { 1537 return Sema::CXXCopyAssignment; 1538 } 1539 1540 return Sema::CXXInvalid; 1541 } 1542 1543 /// canRedefineFunction - checks if a function can be redefined. Currently, 1544 /// only extern inline functions can be redefined, and even then only in 1545 /// GNU89 mode. 1546 static bool canRedefineFunction(const FunctionDecl *FD, 1547 const LangOptions& LangOpts) { 1548 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 1549 !LangOpts.CPlusPlus && 1550 FD->isInlineSpecified() && 1551 FD->getStorageClass() == SC_Extern); 1552 } 1553 1554 /// MergeFunctionDecl - We just parsed a function 'New' from 1555 /// declarator D which has the same name and scope as a previous 1556 /// declaration 'Old'. Figure out how to resolve this situation, 1557 /// merging decls or emitting diagnostics as appropriate. 1558 /// 1559 /// In C++, New and Old must be declarations that are not 1560 /// overloaded. Use IsOverload to determine whether New and Old are 1561 /// overloaded, and to select the Old declaration that New should be 1562 /// merged with. 1563 /// 1564 /// Returns true if there was an error, false otherwise. 1565 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 1566 // Verify the old decl was also a function. 1567 FunctionDecl *Old = 0; 1568 if (FunctionTemplateDecl *OldFunctionTemplate 1569 = dyn_cast<FunctionTemplateDecl>(OldD)) 1570 Old = OldFunctionTemplate->getTemplatedDecl(); 1571 else 1572 Old = dyn_cast<FunctionDecl>(OldD); 1573 if (!Old) { 1574 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 1575 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 1576 Diag(Shadow->getTargetDecl()->getLocation(), 1577 diag::note_using_decl_target); 1578 Diag(Shadow->getUsingDecl()->getLocation(), 1579 diag::note_using_decl) << 0; 1580 return true; 1581 } 1582 1583 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1584 << New->getDeclName(); 1585 Diag(OldD->getLocation(), diag::note_previous_definition); 1586 return true; 1587 } 1588 1589 // Determine whether the previous declaration was a definition, 1590 // implicit declaration, or a declaration. 1591 diag::kind PrevDiag; 1592 if (Old->isThisDeclarationADefinition()) 1593 PrevDiag = diag::note_previous_definition; 1594 else if (Old->isImplicit()) 1595 PrevDiag = diag::note_previous_implicit_declaration; 1596 else 1597 PrevDiag = diag::note_previous_declaration; 1598 1599 QualType OldQType = Context.getCanonicalType(Old->getType()); 1600 QualType NewQType = Context.getCanonicalType(New->getType()); 1601 1602 // Don't complain about this if we're in GNU89 mode and the old function 1603 // is an extern inline function. 1604 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 1605 New->getStorageClass() == SC_Static && 1606 Old->getStorageClass() != SC_Static && 1607 !canRedefineFunction(Old, getLangOptions())) { 1608 if (getLangOptions().Microsoft) { 1609 Diag(New->getLocation(), diag::warn_static_non_static) << New; 1610 Diag(Old->getLocation(), PrevDiag); 1611 } else { 1612 Diag(New->getLocation(), diag::err_static_non_static) << New; 1613 Diag(Old->getLocation(), PrevDiag); 1614 return true; 1615 } 1616 } 1617 1618 // If a function is first declared with a calling convention, but is 1619 // later declared or defined without one, the second decl assumes the 1620 // calling convention of the first. 1621 // 1622 // For the new decl, we have to look at the NON-canonical type to tell the 1623 // difference between a function that really doesn't have a calling 1624 // convention and one that is declared cdecl. That's because in 1625 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 1626 // because it is the default calling convention. 1627 // 1628 // Note also that we DO NOT return at this point, because we still have 1629 // other tests to run. 1630 const FunctionType *OldType = cast<FunctionType>(OldQType); 1631 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 1632 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 1633 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 1634 bool RequiresAdjustment = false; 1635 if (OldTypeInfo.getCC() != CC_Default && 1636 NewTypeInfo.getCC() == CC_Default) { 1637 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 1638 RequiresAdjustment = true; 1639 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 1640 NewTypeInfo.getCC())) { 1641 // Calling conventions really aren't compatible, so complain. 1642 Diag(New->getLocation(), diag::err_cconv_change) 1643 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 1644 << (OldTypeInfo.getCC() == CC_Default) 1645 << (OldTypeInfo.getCC() == CC_Default ? "" : 1646 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 1647 Diag(Old->getLocation(), diag::note_previous_declaration); 1648 return true; 1649 } 1650 1651 // FIXME: diagnose the other way around? 1652 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 1653 NewTypeInfo = NewTypeInfo.withNoReturn(true); 1654 RequiresAdjustment = true; 1655 } 1656 1657 // Merge regparm attribute. 1658 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 1659 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 1660 if (NewTypeInfo.getHasRegParm()) { 1661 Diag(New->getLocation(), diag::err_regparm_mismatch) 1662 << NewType->getRegParmType() 1663 << OldType->getRegParmType(); 1664 Diag(Old->getLocation(), diag::note_previous_declaration); 1665 return true; 1666 } 1667 1668 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 1669 RequiresAdjustment = true; 1670 } 1671 1672 if (RequiresAdjustment) { 1673 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 1674 New->setType(QualType(NewType, 0)); 1675 NewQType = Context.getCanonicalType(New->getType()); 1676 } 1677 1678 if (getLangOptions().CPlusPlus) { 1679 // (C++98 13.1p2): 1680 // Certain function declarations cannot be overloaded: 1681 // -- Function declarations that differ only in the return type 1682 // cannot be overloaded. 1683 QualType OldReturnType = OldType->getResultType(); 1684 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 1685 QualType ResQT; 1686 if (OldReturnType != NewReturnType) { 1687 if (NewReturnType->isObjCObjectPointerType() 1688 && OldReturnType->isObjCObjectPointerType()) 1689 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 1690 if (ResQT.isNull()) { 1691 if (New->isCXXClassMember() && New->isOutOfLine()) 1692 Diag(New->getLocation(), 1693 diag::err_member_def_does_not_match_ret_type) << New; 1694 else 1695 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 1696 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1697 return true; 1698 } 1699 else 1700 NewQType = ResQT; 1701 } 1702 1703 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 1704 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 1705 if (OldMethod && NewMethod) { 1706 // Preserve triviality. 1707 NewMethod->setTrivial(OldMethod->isTrivial()); 1708 1709 bool isFriend = NewMethod->getFriendObjectKind(); 1710 1711 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) { 1712 // -- Member function declarations with the same name and the 1713 // same parameter types cannot be overloaded if any of them 1714 // is a static member function declaration. 1715 if (OldMethod->isStatic() || NewMethod->isStatic()) { 1716 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 1717 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1718 return true; 1719 } 1720 1721 // C++ [class.mem]p1: 1722 // [...] A member shall not be declared twice in the 1723 // member-specification, except that a nested class or member 1724 // class template can be declared and then later defined. 1725 unsigned NewDiag; 1726 if (isa<CXXConstructorDecl>(OldMethod)) 1727 NewDiag = diag::err_constructor_redeclared; 1728 else if (isa<CXXDestructorDecl>(NewMethod)) 1729 NewDiag = diag::err_destructor_redeclared; 1730 else if (isa<CXXConversionDecl>(NewMethod)) 1731 NewDiag = diag::err_conv_function_redeclared; 1732 else 1733 NewDiag = diag::err_member_redeclared; 1734 1735 Diag(New->getLocation(), NewDiag); 1736 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1737 1738 // Complain if this is an explicit declaration of a special 1739 // member that was initially declared implicitly. 1740 // 1741 // As an exception, it's okay to befriend such methods in order 1742 // to permit the implicit constructor/destructor/operator calls. 1743 } else if (OldMethod->isImplicit()) { 1744 if (isFriend) { 1745 NewMethod->setImplicit(); 1746 } else { 1747 Diag(NewMethod->getLocation(), 1748 diag::err_definition_of_implicitly_declared_member) 1749 << New << getSpecialMember(OldMethod); 1750 return true; 1751 } 1752 } else if (OldMethod->isExplicitlyDefaulted()) { 1753 Diag(NewMethod->getLocation(), 1754 diag::err_definition_of_explicitly_defaulted_member) 1755 << getSpecialMember(OldMethod); 1756 return true; 1757 } 1758 } 1759 1760 // (C++98 8.3.5p3): 1761 // All declarations for a function shall agree exactly in both the 1762 // return type and the parameter-type-list. 1763 // We also want to respect all the extended bits except noreturn. 1764 1765 // noreturn should now match unless the old type info didn't have it. 1766 QualType OldQTypeForComparison = OldQType; 1767 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 1768 assert(OldQType == QualType(OldType, 0)); 1769 const FunctionType *OldTypeForComparison 1770 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 1771 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 1772 assert(OldQTypeForComparison.isCanonical()); 1773 } 1774 1775 if (OldQTypeForComparison == NewQType) 1776 return MergeCompatibleFunctionDecls(New, Old); 1777 1778 // Fall through for conflicting redeclarations and redefinitions. 1779 } 1780 1781 // C: Function types need to be compatible, not identical. This handles 1782 // duplicate function decls like "void f(int); void f(enum X);" properly. 1783 if (!getLangOptions().CPlusPlus && 1784 Context.typesAreCompatible(OldQType, NewQType)) { 1785 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 1786 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 1787 const FunctionProtoType *OldProto = 0; 1788 if (isa<FunctionNoProtoType>(NewFuncType) && 1789 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 1790 // The old declaration provided a function prototype, but the 1791 // new declaration does not. Merge in the prototype. 1792 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 1793 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 1794 OldProto->arg_type_end()); 1795 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 1796 ParamTypes.data(), ParamTypes.size(), 1797 OldProto->getExtProtoInfo()); 1798 New->setType(NewQType); 1799 New->setHasInheritedPrototype(); 1800 1801 // Synthesize a parameter for each argument type. 1802 llvm::SmallVector<ParmVarDecl*, 16> Params; 1803 for (FunctionProtoType::arg_type_iterator 1804 ParamType = OldProto->arg_type_begin(), 1805 ParamEnd = OldProto->arg_type_end(); 1806 ParamType != ParamEnd; ++ParamType) { 1807 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 1808 SourceLocation(), 1809 SourceLocation(), 0, 1810 *ParamType, /*TInfo=*/0, 1811 SC_None, SC_None, 1812 0); 1813 Param->setScopeInfo(0, Params.size()); 1814 Param->setImplicit(); 1815 Params.push_back(Param); 1816 } 1817 1818 New->setParams(Params.data(), Params.size()); 1819 } 1820 1821 return MergeCompatibleFunctionDecls(New, Old); 1822 } 1823 1824 // GNU C permits a K&R definition to follow a prototype declaration 1825 // if the declared types of the parameters in the K&R definition 1826 // match the types in the prototype declaration, even when the 1827 // promoted types of the parameters from the K&R definition differ 1828 // from the types in the prototype. GCC then keeps the types from 1829 // the prototype. 1830 // 1831 // If a variadic prototype is followed by a non-variadic K&R definition, 1832 // the K&R definition becomes variadic. This is sort of an edge case, but 1833 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 1834 // C99 6.9.1p8. 1835 if (!getLangOptions().CPlusPlus && 1836 Old->hasPrototype() && !New->hasPrototype() && 1837 New->getType()->getAs<FunctionProtoType>() && 1838 Old->getNumParams() == New->getNumParams()) { 1839 llvm::SmallVector<QualType, 16> ArgTypes; 1840 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings; 1841 const FunctionProtoType *OldProto 1842 = Old->getType()->getAs<FunctionProtoType>(); 1843 const FunctionProtoType *NewProto 1844 = New->getType()->getAs<FunctionProtoType>(); 1845 1846 // Determine whether this is the GNU C extension. 1847 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 1848 NewProto->getResultType()); 1849 bool LooseCompatible = !MergedReturn.isNull(); 1850 for (unsigned Idx = 0, End = Old->getNumParams(); 1851 LooseCompatible && Idx != End; ++Idx) { 1852 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 1853 ParmVarDecl *NewParm = New->getParamDecl(Idx); 1854 if (Context.typesAreCompatible(OldParm->getType(), 1855 NewProto->getArgType(Idx))) { 1856 ArgTypes.push_back(NewParm->getType()); 1857 } else if (Context.typesAreCompatible(OldParm->getType(), 1858 NewParm->getType(), 1859 /*CompareUnqualified=*/true)) { 1860 GNUCompatibleParamWarning Warn 1861 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 1862 Warnings.push_back(Warn); 1863 ArgTypes.push_back(NewParm->getType()); 1864 } else 1865 LooseCompatible = false; 1866 } 1867 1868 if (LooseCompatible) { 1869 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 1870 Diag(Warnings[Warn].NewParm->getLocation(), 1871 diag::ext_param_promoted_not_compatible_with_prototype) 1872 << Warnings[Warn].PromotedType 1873 << Warnings[Warn].OldParm->getType(); 1874 if (Warnings[Warn].OldParm->getLocation().isValid()) 1875 Diag(Warnings[Warn].OldParm->getLocation(), 1876 diag::note_previous_declaration); 1877 } 1878 1879 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 1880 ArgTypes.size(), 1881 OldProto->getExtProtoInfo())); 1882 return MergeCompatibleFunctionDecls(New, Old); 1883 } 1884 1885 // Fall through to diagnose conflicting types. 1886 } 1887 1888 // A function that has already been declared has been redeclared or defined 1889 // with a different type- show appropriate diagnostic 1890 if (unsigned BuiltinID = Old->getBuiltinID()) { 1891 // The user has declared a builtin function with an incompatible 1892 // signature. 1893 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 1894 // The function the user is redeclaring is a library-defined 1895 // function like 'malloc' or 'printf'. Warn about the 1896 // redeclaration, then pretend that we don't know about this 1897 // library built-in. 1898 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 1899 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 1900 << Old << Old->getType(); 1901 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 1902 Old->setInvalidDecl(); 1903 return false; 1904 } 1905 1906 PrevDiag = diag::note_previous_builtin_declaration; 1907 } 1908 1909 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 1910 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1911 return true; 1912 } 1913 1914 /// \brief Completes the merge of two function declarations that are 1915 /// known to be compatible. 1916 /// 1917 /// This routine handles the merging of attributes and other 1918 /// properties of function declarations form the old declaration to 1919 /// the new declaration, once we know that New is in fact a 1920 /// redeclaration of Old. 1921 /// 1922 /// \returns false 1923 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 1924 // Merge the attributes 1925 mergeDeclAttributes(New, Old, Context); 1926 1927 // Merge the storage class. 1928 if (Old->getStorageClass() != SC_Extern && 1929 Old->getStorageClass() != SC_None) 1930 New->setStorageClass(Old->getStorageClass()); 1931 1932 // Merge "pure" flag. 1933 if (Old->isPure()) 1934 New->setPure(); 1935 1936 // Merge attributes from the parameters. These can mismatch with K&R 1937 // declarations. 1938 if (New->getNumParams() == Old->getNumParams()) 1939 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 1940 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 1941 Context); 1942 1943 if (getLangOptions().CPlusPlus) 1944 return MergeCXXFunctionDecl(New, Old); 1945 1946 return false; 1947 } 1948 1949 1950 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 1951 const ObjCMethodDecl *oldMethod) { 1952 // Merge the attributes. 1953 mergeDeclAttributes(newMethod, oldMethod, Context); 1954 1955 // Merge attributes from the parameters. 1956 for (ObjCMethodDecl::param_iterator oi = oldMethod->param_begin(), 1957 ni = newMethod->param_begin(), ne = newMethod->param_end(); 1958 ni != ne; ++ni, ++oi) 1959 mergeParamDeclAttributes(*ni, *oi, Context); 1960 1961 CheckObjCMethodOverride(newMethod, oldMethod, true); 1962 } 1963 1964 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 1965 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 1966 /// emitting diagnostics as appropriate. 1967 /// 1968 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 1969 /// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't 1970 /// check them before the initializer is attached. 1971 /// 1972 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 1973 if (New->isInvalidDecl() || Old->isInvalidDecl()) 1974 return; 1975 1976 QualType MergedT; 1977 if (getLangOptions().CPlusPlus) { 1978 AutoType *AT = New->getType()->getContainedAutoType(); 1979 if (AT && !AT->isDeduced()) { 1980 // We don't know what the new type is until the initializer is attached. 1981 return; 1982 } else if (Context.hasSameType(New->getType(), Old->getType())) { 1983 // These could still be something that needs exception specs checked. 1984 return MergeVarDeclExceptionSpecs(New, Old); 1985 } 1986 // C++ [basic.link]p10: 1987 // [...] the types specified by all declarations referring to a given 1988 // object or function shall be identical, except that declarations for an 1989 // array object can specify array types that differ by the presence or 1990 // absence of a major array bound (8.3.4). 1991 else if (Old->getType()->isIncompleteArrayType() && 1992 New->getType()->isArrayType()) { 1993 CanQual<ArrayType> OldArray 1994 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 1995 CanQual<ArrayType> NewArray 1996 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 1997 if (OldArray->getElementType() == NewArray->getElementType()) 1998 MergedT = New->getType(); 1999 } else if (Old->getType()->isArrayType() && 2000 New->getType()->isIncompleteArrayType()) { 2001 CanQual<ArrayType> OldArray 2002 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2003 CanQual<ArrayType> NewArray 2004 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2005 if (OldArray->getElementType() == NewArray->getElementType()) 2006 MergedT = Old->getType(); 2007 } else if (New->getType()->isObjCObjectPointerType() 2008 && Old->getType()->isObjCObjectPointerType()) { 2009 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2010 Old->getType()); 2011 } 2012 } else { 2013 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2014 } 2015 if (MergedT.isNull()) { 2016 Diag(New->getLocation(), diag::err_redefinition_different_type) 2017 << New->getDeclName(); 2018 Diag(Old->getLocation(), diag::note_previous_definition); 2019 return New->setInvalidDecl(); 2020 } 2021 New->setType(MergedT); 2022 } 2023 2024 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2025 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2026 /// situation, merging decls or emitting diagnostics as appropriate. 2027 /// 2028 /// Tentative definition rules (C99 6.9.2p2) are checked by 2029 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2030 /// definitions here, since the initializer hasn't been attached. 2031 /// 2032 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2033 // If the new decl is already invalid, don't do any other checking. 2034 if (New->isInvalidDecl()) 2035 return; 2036 2037 // Verify the old decl was also a variable. 2038 VarDecl *Old = 0; 2039 if (!Previous.isSingleResult() || 2040 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2041 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2042 << New->getDeclName(); 2043 Diag(Previous.getRepresentativeDecl()->getLocation(), 2044 diag::note_previous_definition); 2045 return New->setInvalidDecl(); 2046 } 2047 2048 // C++ [class.mem]p1: 2049 // A member shall not be declared twice in the member-specification [...] 2050 // 2051 // Here, we need only consider static data members. 2052 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2053 Diag(New->getLocation(), diag::err_duplicate_member) 2054 << New->getIdentifier(); 2055 Diag(Old->getLocation(), diag::note_previous_declaration); 2056 New->setInvalidDecl(); 2057 } 2058 2059 mergeDeclAttributes(New, Old, Context); 2060 // Warn if an already-declared variable is made a weak_import in a subsequent declaration 2061 if (New->getAttr<WeakImportAttr>() && 2062 Old->getStorageClass() == SC_None && 2063 !Old->getAttr<WeakImportAttr>()) { 2064 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2065 Diag(Old->getLocation(), diag::note_previous_definition); 2066 // Remove weak_import attribute on new declaration. 2067 New->dropAttr<WeakImportAttr>(); 2068 } 2069 2070 // Merge the types. 2071 MergeVarDeclTypes(New, Old); 2072 if (New->isInvalidDecl()) 2073 return; 2074 2075 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2076 if (New->getStorageClass() == SC_Static && 2077 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2078 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2079 Diag(Old->getLocation(), diag::note_previous_definition); 2080 return New->setInvalidDecl(); 2081 } 2082 // C99 6.2.2p4: 2083 // For an identifier declared with the storage-class specifier 2084 // extern in a scope in which a prior declaration of that 2085 // identifier is visible,23) if the prior declaration specifies 2086 // internal or external linkage, the linkage of the identifier at 2087 // the later declaration is the same as the linkage specified at 2088 // the prior declaration. If no prior declaration is visible, or 2089 // if the prior declaration specifies no linkage, then the 2090 // identifier has external linkage. 2091 if (New->hasExternalStorage() && Old->hasLinkage()) 2092 /* Okay */; 2093 else if (New->getStorageClass() != SC_Static && 2094 Old->getStorageClass() == SC_Static) { 2095 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2096 Diag(Old->getLocation(), diag::note_previous_definition); 2097 return New->setInvalidDecl(); 2098 } 2099 2100 // Check if extern is followed by non-extern and vice-versa. 2101 if (New->hasExternalStorage() && 2102 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2103 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2104 Diag(Old->getLocation(), diag::note_previous_definition); 2105 return New->setInvalidDecl(); 2106 } 2107 if (Old->hasExternalStorage() && 2108 !New->hasLinkage() && New->isLocalVarDecl()) { 2109 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2110 Diag(Old->getLocation(), diag::note_previous_definition); 2111 return New->setInvalidDecl(); 2112 } 2113 2114 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2115 2116 // FIXME: The test for external storage here seems wrong? We still 2117 // need to check for mismatches. 2118 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2119 // Don't complain about out-of-line definitions of static members. 2120 !(Old->getLexicalDeclContext()->isRecord() && 2121 !New->getLexicalDeclContext()->isRecord())) { 2122 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2123 Diag(Old->getLocation(), diag::note_previous_definition); 2124 return New->setInvalidDecl(); 2125 } 2126 2127 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2128 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2129 Diag(Old->getLocation(), diag::note_previous_definition); 2130 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2131 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2132 Diag(Old->getLocation(), diag::note_previous_definition); 2133 } 2134 2135 // C++ doesn't have tentative definitions, so go right ahead and check here. 2136 const VarDecl *Def; 2137 if (getLangOptions().CPlusPlus && 2138 New->isThisDeclarationADefinition() == VarDecl::Definition && 2139 (Def = Old->getDefinition())) { 2140 Diag(New->getLocation(), diag::err_redefinition) 2141 << New->getDeclName(); 2142 Diag(Def->getLocation(), diag::note_previous_definition); 2143 New->setInvalidDecl(); 2144 return; 2145 } 2146 // c99 6.2.2 P4. 2147 // For an identifier declared with the storage-class specifier extern in a 2148 // scope in which a prior declaration of that identifier is visible, if 2149 // the prior declaration specifies internal or external linkage, the linkage 2150 // of the identifier at the later declaration is the same as the linkage 2151 // specified at the prior declaration. 2152 // FIXME. revisit this code. 2153 if (New->hasExternalStorage() && 2154 Old->getLinkage() == InternalLinkage && 2155 New->getDeclContext() == Old->getDeclContext()) 2156 New->setStorageClass(Old->getStorageClass()); 2157 2158 // Keep a chain of previous declarations. 2159 New->setPreviousDeclaration(Old); 2160 2161 // Inherit access appropriately. 2162 New->setAccess(Old->getAccess()); 2163 } 2164 2165 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2166 /// no declarator (e.g. "struct foo;") is parsed. 2167 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2168 DeclSpec &DS) { 2169 return ParsedFreeStandingDeclSpec(S, AS, DS, 2170 MultiTemplateParamsArg(*this, 0, 0)); 2171 } 2172 2173 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2174 /// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2175 /// parameters to cope with template friend declarations. 2176 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2177 DeclSpec &DS, 2178 MultiTemplateParamsArg TemplateParams) { 2179 Decl *TagD = 0; 2180 TagDecl *Tag = 0; 2181 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2182 DS.getTypeSpecType() == DeclSpec::TST_struct || 2183 DS.getTypeSpecType() == DeclSpec::TST_union || 2184 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2185 TagD = DS.getRepAsDecl(); 2186 2187 if (!TagD) // We probably had an error 2188 return 0; 2189 2190 // Note that the above type specs guarantee that the 2191 // type rep is a Decl, whereas in many of the others 2192 // it's a Type. 2193 Tag = dyn_cast<TagDecl>(TagD); 2194 } 2195 2196 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 2197 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 2198 // or incomplete types shall not be restrict-qualified." 2199 if (TypeQuals & DeclSpec::TQ_restrict) 2200 Diag(DS.getRestrictSpecLoc(), 2201 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 2202 << DS.getSourceRange(); 2203 } 2204 2205 if (DS.isFriendSpecified()) { 2206 // If we're dealing with a decl but not a TagDecl, assume that 2207 // whatever routines created it handled the friendship aspect. 2208 if (TagD && !Tag) 2209 return 0; 2210 return ActOnFriendTypeDecl(S, DS, TemplateParams); 2211 } 2212 2213 // Track whether we warned about the fact that there aren't any 2214 // declarators. 2215 bool emittedWarning = false; 2216 2217 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 2218 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList()); 2219 2220 if (!Record->getDeclName() && Record->isDefinition() && 2221 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 2222 if (getLangOptions().CPlusPlus || 2223 Record->getDeclContext()->isRecord()) 2224 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 2225 2226 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2227 << DS.getSourceRange(); 2228 emittedWarning = true; 2229 } 2230 } 2231 2232 // Check for Microsoft C extension: anonymous struct. 2233 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus && 2234 CurContext->isRecord() && 2235 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 2236 // Handle 2 kinds of anonymous struct: 2237 // struct STRUCT; 2238 // and 2239 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 2240 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 2241 if ((Record && Record->getDeclName() && !Record->isDefinition()) || 2242 (DS.getTypeSpecType() == DeclSpec::TST_typename && 2243 DS.getRepAsType().get()->isStructureType())) { 2244 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct) 2245 << DS.getSourceRange(); 2246 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 2247 } 2248 } 2249 2250 if (getLangOptions().CPlusPlus && 2251 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 2252 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 2253 if (Enum->enumerator_begin() == Enum->enumerator_end() && 2254 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 2255 Diag(Enum->getLocation(), diag::ext_no_declarators) 2256 << DS.getSourceRange(); 2257 emittedWarning = true; 2258 } 2259 2260 // Skip all the checks below if we have a type error. 2261 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 2262 2263 if (!DS.isMissingDeclaratorOk()) { 2264 // Warn about typedefs of enums without names, since this is an 2265 // extension in both Microsoft and GNU. 2266 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 2267 Tag && isa<EnumDecl>(Tag)) { 2268 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 2269 << DS.getSourceRange(); 2270 return Tag; 2271 } 2272 2273 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2274 << DS.getSourceRange(); 2275 emittedWarning = true; 2276 } 2277 2278 // We're going to complain about a bunch of spurious specifiers; 2279 // only do this if we're declaring a tag, because otherwise we 2280 // should be getting diag::ext_no_declarators. 2281 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 2282 return TagD; 2283 2284 // Note that a linkage-specification sets a storage class, but 2285 // 'extern "C" struct foo;' is actually valid and not theoretically 2286 // useless. 2287 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 2288 if (!DS.isExternInLinkageSpec()) 2289 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 2290 << DeclSpec::getSpecifierName(scs); 2291 2292 if (DS.isThreadSpecified()) 2293 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 2294 if (DS.getTypeQualifiers()) { 2295 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2296 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 2297 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2298 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 2299 // Restrict is covered above. 2300 } 2301 if (DS.isInlineSpecified()) 2302 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 2303 if (DS.isVirtualSpecified()) 2304 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 2305 if (DS.isExplicitSpecified()) 2306 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 2307 2308 // FIXME: Warn on useless attributes 2309 2310 return TagD; 2311 } 2312 2313 /// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec. 2314 /// builds a statement for it and returns it so it is evaluated. 2315 StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) { 2316 StmtResult R; 2317 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) { 2318 Expr *Exp = DS.getRepAsExpr(); 2319 QualType Ty = Exp->getType(); 2320 if (Ty->isPointerType()) { 2321 do 2322 Ty = Ty->getAs<PointerType>()->getPointeeType(); 2323 while (Ty->isPointerType()); 2324 } 2325 if (Ty->isVariableArrayType()) { 2326 R = ActOnExprStmt(MakeFullExpr(Exp)); 2327 } 2328 } 2329 return R; 2330 } 2331 2332 /// We are trying to inject an anonymous member into the given scope; 2333 /// check if there's an existing declaration that can't be overloaded. 2334 /// 2335 /// \return true if this is a forbidden redeclaration 2336 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 2337 Scope *S, 2338 DeclContext *Owner, 2339 DeclarationName Name, 2340 SourceLocation NameLoc, 2341 unsigned diagnostic) { 2342 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 2343 Sema::ForRedeclaration); 2344 if (!SemaRef.LookupName(R, S)) return false; 2345 2346 if (R.getAsSingle<TagDecl>()) 2347 return false; 2348 2349 // Pick a representative declaration. 2350 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 2351 assert(PrevDecl && "Expected a non-null Decl"); 2352 2353 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 2354 return false; 2355 2356 SemaRef.Diag(NameLoc, diagnostic) << Name; 2357 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 2358 2359 return true; 2360 } 2361 2362 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 2363 /// anonymous struct or union AnonRecord into the owning context Owner 2364 /// and scope S. This routine will be invoked just after we realize 2365 /// that an unnamed union or struct is actually an anonymous union or 2366 /// struct, e.g., 2367 /// 2368 /// @code 2369 /// union { 2370 /// int i; 2371 /// float f; 2372 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 2373 /// // f into the surrounding scope.x 2374 /// @endcode 2375 /// 2376 /// This routine is recursive, injecting the names of nested anonymous 2377 /// structs/unions into the owning context and scope as well. 2378 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 2379 DeclContext *Owner, 2380 RecordDecl *AnonRecord, 2381 AccessSpecifier AS, 2382 llvm::SmallVector<NamedDecl*, 2> &Chaining, 2383 bool MSAnonStruct) { 2384 unsigned diagKind 2385 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 2386 : diag::err_anonymous_struct_member_redecl; 2387 2388 bool Invalid = false; 2389 2390 // Look every FieldDecl and IndirectFieldDecl with a name. 2391 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 2392 DEnd = AnonRecord->decls_end(); 2393 D != DEnd; ++D) { 2394 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 2395 cast<NamedDecl>(*D)->getDeclName()) { 2396 ValueDecl *VD = cast<ValueDecl>(*D); 2397 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 2398 VD->getLocation(), diagKind)) { 2399 // C++ [class.union]p2: 2400 // The names of the members of an anonymous union shall be 2401 // distinct from the names of any other entity in the 2402 // scope in which the anonymous union is declared. 2403 Invalid = true; 2404 } else { 2405 // C++ [class.union]p2: 2406 // For the purpose of name lookup, after the anonymous union 2407 // definition, the members of the anonymous union are 2408 // considered to have been defined in the scope in which the 2409 // anonymous union is declared. 2410 unsigned OldChainingSize = Chaining.size(); 2411 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 2412 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 2413 PE = IF->chain_end(); PI != PE; ++PI) 2414 Chaining.push_back(*PI); 2415 else 2416 Chaining.push_back(VD); 2417 2418 assert(Chaining.size() >= 2); 2419 NamedDecl **NamedChain = 2420 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 2421 for (unsigned i = 0; i < Chaining.size(); i++) 2422 NamedChain[i] = Chaining[i]; 2423 2424 IndirectFieldDecl* IndirectField = 2425 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 2426 VD->getIdentifier(), VD->getType(), 2427 NamedChain, Chaining.size()); 2428 2429 IndirectField->setAccess(AS); 2430 IndirectField->setImplicit(); 2431 SemaRef.PushOnScopeChains(IndirectField, S); 2432 2433 // That includes picking up the appropriate access specifier. 2434 if (AS != AS_none) IndirectField->setAccess(AS); 2435 2436 Chaining.resize(OldChainingSize); 2437 } 2438 } 2439 } 2440 2441 return Invalid; 2442 } 2443 2444 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 2445 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 2446 /// illegal input values are mapped to SC_None. 2447 static StorageClass 2448 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2449 switch (StorageClassSpec) { 2450 case DeclSpec::SCS_unspecified: return SC_None; 2451 case DeclSpec::SCS_extern: return SC_Extern; 2452 case DeclSpec::SCS_static: return SC_Static; 2453 case DeclSpec::SCS_auto: return SC_Auto; 2454 case DeclSpec::SCS_register: return SC_Register; 2455 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2456 // Illegal SCSs map to None: error reporting is up to the caller. 2457 case DeclSpec::SCS_mutable: // Fall through. 2458 case DeclSpec::SCS_typedef: return SC_None; 2459 } 2460 llvm_unreachable("unknown storage class specifier"); 2461 } 2462 2463 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 2464 /// a StorageClass. Any error reporting is up to the caller: 2465 /// illegal input values are mapped to SC_None. 2466 static StorageClass 2467 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2468 switch (StorageClassSpec) { 2469 case DeclSpec::SCS_unspecified: return SC_None; 2470 case DeclSpec::SCS_extern: return SC_Extern; 2471 case DeclSpec::SCS_static: return SC_Static; 2472 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2473 // Illegal SCSs map to None: error reporting is up to the caller. 2474 case DeclSpec::SCS_auto: // Fall through. 2475 case DeclSpec::SCS_mutable: // Fall through. 2476 case DeclSpec::SCS_register: // Fall through. 2477 case DeclSpec::SCS_typedef: return SC_None; 2478 } 2479 llvm_unreachable("unknown storage class specifier"); 2480 } 2481 2482 /// BuildAnonymousStructOrUnion - Handle the declaration of an 2483 /// anonymous structure or union. Anonymous unions are a C++ feature 2484 /// (C++ [class.union]) and a GNU C extension; anonymous structures 2485 /// are a GNU C and GNU C++ extension. 2486 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2487 AccessSpecifier AS, 2488 RecordDecl *Record) { 2489 DeclContext *Owner = Record->getDeclContext(); 2490 2491 // Diagnose whether this anonymous struct/union is an extension. 2492 if (Record->isUnion() && !getLangOptions().CPlusPlus) 2493 Diag(Record->getLocation(), diag::ext_anonymous_union); 2494 else if (!Record->isUnion()) 2495 Diag(Record->getLocation(), diag::ext_anonymous_struct); 2496 2497 // C and C++ require different kinds of checks for anonymous 2498 // structs/unions. 2499 bool Invalid = false; 2500 if (getLangOptions().CPlusPlus) { 2501 const char* PrevSpec = 0; 2502 unsigned DiagID; 2503 // C++ [class.union]p3: 2504 // Anonymous unions declared in a named namespace or in the 2505 // global namespace shall be declared static. 2506 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 2507 (isa<TranslationUnitDecl>(Owner) || 2508 (isa<NamespaceDecl>(Owner) && 2509 cast<NamespaceDecl>(Owner)->getDeclName()))) { 2510 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 2511 Invalid = true; 2512 2513 // Recover by adding 'static'. 2514 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), 2515 PrevSpec, DiagID, getLangOptions()); 2516 } 2517 // C++ [class.union]p3: 2518 // A storage class is not allowed in a declaration of an 2519 // anonymous union in a class scope. 2520 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 2521 isa<RecordDecl>(Owner)) { 2522 Diag(DS.getStorageClassSpecLoc(), 2523 diag::err_anonymous_union_with_storage_spec); 2524 Invalid = true; 2525 2526 // Recover by removing the storage specifier. 2527 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 2528 PrevSpec, DiagID, getLangOptions()); 2529 } 2530 2531 // Ignore const/volatile/restrict qualifiers. 2532 if (DS.getTypeQualifiers()) { 2533 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2534 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2535 << Record->isUnion() << 0 2536 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 2537 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2538 Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2539 << Record->isUnion() << 1 2540 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 2541 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 2542 Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2543 << Record->isUnion() << 2 2544 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 2545 2546 DS.ClearTypeQualifiers(); 2547 } 2548 2549 // C++ [class.union]p2: 2550 // The member-specification of an anonymous union shall only 2551 // define non-static data members. [Note: nested types and 2552 // functions cannot be declared within an anonymous union. ] 2553 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 2554 MemEnd = Record->decls_end(); 2555 Mem != MemEnd; ++Mem) { 2556 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 2557 // C++ [class.union]p3: 2558 // An anonymous union shall not have private or protected 2559 // members (clause 11). 2560 assert(FD->getAccess() != AS_none); 2561 if (FD->getAccess() != AS_public) { 2562 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 2563 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 2564 Invalid = true; 2565 } 2566 2567 // C++ [class.union]p1 2568 // An object of a class with a non-trivial constructor, a non-trivial 2569 // copy constructor, a non-trivial destructor, or a non-trivial copy 2570 // assignment operator cannot be a member of a union, nor can an 2571 // array of such objects. 2572 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(FD)) 2573 Invalid = true; 2574 } else if ((*Mem)->isImplicit()) { 2575 // Any implicit members are fine. 2576 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 2577 // This is a type that showed up in an 2578 // elaborated-type-specifier inside the anonymous struct or 2579 // union, but which actually declares a type outside of the 2580 // anonymous struct or union. It's okay. 2581 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 2582 if (!MemRecord->isAnonymousStructOrUnion() && 2583 MemRecord->getDeclName()) { 2584 // Visual C++ allows type definition in anonymous struct or union. 2585 if (getLangOptions().Microsoft) 2586 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 2587 << (int)Record->isUnion(); 2588 else { 2589 // This is a nested type declaration. 2590 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 2591 << (int)Record->isUnion(); 2592 Invalid = true; 2593 } 2594 } 2595 } else if (isa<AccessSpecDecl>(*Mem)) { 2596 // Any access specifier is fine. 2597 } else { 2598 // We have something that isn't a non-static data 2599 // member. Complain about it. 2600 unsigned DK = diag::err_anonymous_record_bad_member; 2601 if (isa<TypeDecl>(*Mem)) 2602 DK = diag::err_anonymous_record_with_type; 2603 else if (isa<FunctionDecl>(*Mem)) 2604 DK = diag::err_anonymous_record_with_function; 2605 else if (isa<VarDecl>(*Mem)) 2606 DK = diag::err_anonymous_record_with_static; 2607 2608 // Visual C++ allows type definition in anonymous struct or union. 2609 if (getLangOptions().Microsoft && 2610 DK == diag::err_anonymous_record_with_type) 2611 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 2612 << (int)Record->isUnion(); 2613 else { 2614 Diag((*Mem)->getLocation(), DK) 2615 << (int)Record->isUnion(); 2616 Invalid = true; 2617 } 2618 } 2619 } 2620 } 2621 2622 if (!Record->isUnion() && !Owner->isRecord()) { 2623 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 2624 << (int)getLangOptions().CPlusPlus; 2625 Invalid = true; 2626 } 2627 2628 // Mock up a declarator. 2629 Declarator Dc(DS, Declarator::MemberContext); 2630 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2631 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 2632 2633 // Create a declaration for this anonymous struct/union. 2634 NamedDecl *Anon = 0; 2635 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 2636 Anon = FieldDecl::Create(Context, OwningClass, 2637 DS.getSourceRange().getBegin(), 2638 Record->getLocation(), 2639 /*IdentifierInfo=*/0, 2640 Context.getTypeDeclType(Record), 2641 TInfo, 2642 /*BitWidth=*/0, /*Mutable=*/false, 2643 /*HasInit=*/false); 2644 Anon->setAccess(AS); 2645 if (getLangOptions().CPlusPlus) 2646 FieldCollector->Add(cast<FieldDecl>(Anon)); 2647 } else { 2648 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 2649 assert(SCSpec != DeclSpec::SCS_typedef && 2650 "Parser allowed 'typedef' as storage class VarDecl."); 2651 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 2652 if (SCSpec == DeclSpec::SCS_mutable) { 2653 // mutable can only appear on non-static class members, so it's always 2654 // an error here 2655 Diag(Record->getLocation(), diag::err_mutable_nonmember); 2656 Invalid = true; 2657 SC = SC_None; 2658 } 2659 SCSpec = DS.getStorageClassSpecAsWritten(); 2660 VarDecl::StorageClass SCAsWritten 2661 = StorageClassSpecToVarDeclStorageClass(SCSpec); 2662 2663 Anon = VarDecl::Create(Context, Owner, 2664 DS.getSourceRange().getBegin(), 2665 Record->getLocation(), /*IdentifierInfo=*/0, 2666 Context.getTypeDeclType(Record), 2667 TInfo, SC, SCAsWritten); 2668 } 2669 Anon->setImplicit(); 2670 2671 // Add the anonymous struct/union object to the current 2672 // context. We'll be referencing this object when we refer to one of 2673 // its members. 2674 Owner->addDecl(Anon); 2675 2676 // Inject the members of the anonymous struct/union into the owning 2677 // context and into the identifier resolver chain for name lookup 2678 // purposes. 2679 llvm::SmallVector<NamedDecl*, 2> Chain; 2680 Chain.push_back(Anon); 2681 2682 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 2683 Chain, false)) 2684 Invalid = true; 2685 2686 // Mark this as an anonymous struct/union type. Note that we do not 2687 // do this until after we have already checked and injected the 2688 // members of this anonymous struct/union type, because otherwise 2689 // the members could be injected twice: once by DeclContext when it 2690 // builds its lookup table, and once by 2691 // InjectAnonymousStructOrUnionMembers. 2692 Record->setAnonymousStructOrUnion(true); 2693 2694 if (Invalid) 2695 Anon->setInvalidDecl(); 2696 2697 return Anon; 2698 } 2699 2700 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 2701 /// Microsoft C anonymous structure. 2702 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 2703 /// Example: 2704 /// 2705 /// struct A { int a; }; 2706 /// struct B { struct A; int b; }; 2707 /// 2708 /// void foo() { 2709 /// B var; 2710 /// var.a = 3; 2711 /// } 2712 /// 2713 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2714 RecordDecl *Record) { 2715 2716 // If there is no Record, get the record via the typedef. 2717 if (!Record) 2718 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 2719 2720 // Mock up a declarator. 2721 Declarator Dc(DS, Declarator::TypeNameContext); 2722 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2723 assert(TInfo && "couldn't build declarator info for anonymous struct"); 2724 2725 // Create a declaration for this anonymous struct. 2726 NamedDecl* Anon = FieldDecl::Create(Context, 2727 cast<RecordDecl>(CurContext), 2728 DS.getSourceRange().getBegin(), 2729 DS.getSourceRange().getBegin(), 2730 /*IdentifierInfo=*/0, 2731 Context.getTypeDeclType(Record), 2732 TInfo, 2733 /*BitWidth=*/0, /*Mutable=*/false, 2734 /*HasInit=*/false); 2735 Anon->setImplicit(); 2736 2737 // Add the anonymous struct object to the current context. 2738 CurContext->addDecl(Anon); 2739 2740 // Inject the members of the anonymous struct into the current 2741 // context and into the identifier resolver chain for name lookup 2742 // purposes. 2743 llvm::SmallVector<NamedDecl*, 2> Chain; 2744 Chain.push_back(Anon); 2745 2746 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 2747 Record->getDefinition(), 2748 AS_none, Chain, true)) 2749 Anon->setInvalidDecl(); 2750 2751 return Anon; 2752 } 2753 2754 /// GetNameForDeclarator - Determine the full declaration name for the 2755 /// given Declarator. 2756 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 2757 return GetNameFromUnqualifiedId(D.getName()); 2758 } 2759 2760 /// \brief Retrieves the declaration name from a parsed unqualified-id. 2761 DeclarationNameInfo 2762 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 2763 DeclarationNameInfo NameInfo; 2764 NameInfo.setLoc(Name.StartLocation); 2765 2766 switch (Name.getKind()) { 2767 2768 case UnqualifiedId::IK_ImplicitSelfParam: 2769 case UnqualifiedId::IK_Identifier: 2770 NameInfo.setName(Name.Identifier); 2771 NameInfo.setLoc(Name.StartLocation); 2772 return NameInfo; 2773 2774 case UnqualifiedId::IK_OperatorFunctionId: 2775 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 2776 Name.OperatorFunctionId.Operator)); 2777 NameInfo.setLoc(Name.StartLocation); 2778 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 2779 = Name.OperatorFunctionId.SymbolLocations[0]; 2780 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 2781 = Name.EndLocation.getRawEncoding(); 2782 return NameInfo; 2783 2784 case UnqualifiedId::IK_LiteralOperatorId: 2785 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 2786 Name.Identifier)); 2787 NameInfo.setLoc(Name.StartLocation); 2788 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 2789 return NameInfo; 2790 2791 case UnqualifiedId::IK_ConversionFunctionId: { 2792 TypeSourceInfo *TInfo; 2793 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 2794 if (Ty.isNull()) 2795 return DeclarationNameInfo(); 2796 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 2797 Context.getCanonicalType(Ty))); 2798 NameInfo.setLoc(Name.StartLocation); 2799 NameInfo.setNamedTypeInfo(TInfo); 2800 return NameInfo; 2801 } 2802 2803 case UnqualifiedId::IK_ConstructorName: { 2804 TypeSourceInfo *TInfo; 2805 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 2806 if (Ty.isNull()) 2807 return DeclarationNameInfo(); 2808 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2809 Context.getCanonicalType(Ty))); 2810 NameInfo.setLoc(Name.StartLocation); 2811 NameInfo.setNamedTypeInfo(TInfo); 2812 return NameInfo; 2813 } 2814 2815 case UnqualifiedId::IK_ConstructorTemplateId: { 2816 // In well-formed code, we can only have a constructor 2817 // template-id that refers to the current context, so go there 2818 // to find the actual type being constructed. 2819 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 2820 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 2821 return DeclarationNameInfo(); 2822 2823 // Determine the type of the class being constructed. 2824 QualType CurClassType = Context.getTypeDeclType(CurClass); 2825 2826 // FIXME: Check two things: that the template-id names the same type as 2827 // CurClassType, and that the template-id does not occur when the name 2828 // was qualified. 2829 2830 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2831 Context.getCanonicalType(CurClassType))); 2832 NameInfo.setLoc(Name.StartLocation); 2833 // FIXME: should we retrieve TypeSourceInfo? 2834 NameInfo.setNamedTypeInfo(0); 2835 return NameInfo; 2836 } 2837 2838 case UnqualifiedId::IK_DestructorName: { 2839 TypeSourceInfo *TInfo; 2840 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 2841 if (Ty.isNull()) 2842 return DeclarationNameInfo(); 2843 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 2844 Context.getCanonicalType(Ty))); 2845 NameInfo.setLoc(Name.StartLocation); 2846 NameInfo.setNamedTypeInfo(TInfo); 2847 return NameInfo; 2848 } 2849 2850 case UnqualifiedId::IK_TemplateId: { 2851 TemplateName TName = Name.TemplateId->Template.get(); 2852 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 2853 return Context.getNameForTemplate(TName, TNameLoc); 2854 } 2855 2856 } // switch (Name.getKind()) 2857 2858 assert(false && "Unknown name kind"); 2859 return DeclarationNameInfo(); 2860 } 2861 2862 /// isNearlyMatchingFunction - Determine whether the C++ functions 2863 /// Declaration and Definition are "nearly" matching. This heuristic 2864 /// is used to improve diagnostics in the case where an out-of-line 2865 /// function definition doesn't match any declaration within 2866 /// the class or namespace. 2867 static bool isNearlyMatchingFunction(ASTContext &Context, 2868 FunctionDecl *Declaration, 2869 FunctionDecl *Definition) { 2870 if (Declaration->param_size() != Definition->param_size()) 2871 return false; 2872 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 2873 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 2874 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 2875 2876 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(), 2877 DefParamTy.getNonReferenceType())) 2878 return false; 2879 } 2880 2881 return true; 2882 } 2883 2884 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 2885 /// declarator needs to be rebuilt in the current instantiation. 2886 /// Any bits of declarator which appear before the name are valid for 2887 /// consideration here. That's specifically the type in the decl spec 2888 /// and the base type in any member-pointer chunks. 2889 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 2890 DeclarationName Name) { 2891 // The types we specifically need to rebuild are: 2892 // - typenames, typeofs, and decltypes 2893 // - types which will become injected class names 2894 // Of course, we also need to rebuild any type referencing such a 2895 // type. It's safest to just say "dependent", but we call out a 2896 // few cases here. 2897 2898 DeclSpec &DS = D.getMutableDeclSpec(); 2899 switch (DS.getTypeSpecType()) { 2900 case DeclSpec::TST_typename: 2901 case DeclSpec::TST_typeofType: 2902 case DeclSpec::TST_decltype: 2903 case DeclSpec::TST_underlyingType: { 2904 // Grab the type from the parser. 2905 TypeSourceInfo *TSI = 0; 2906 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 2907 if (T.isNull() || !T->isDependentType()) break; 2908 2909 // Make sure there's a type source info. This isn't really much 2910 // of a waste; most dependent types should have type source info 2911 // attached already. 2912 if (!TSI) 2913 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 2914 2915 // Rebuild the type in the current instantiation. 2916 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 2917 if (!TSI) return true; 2918 2919 // Store the new type back in the decl spec. 2920 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 2921 DS.UpdateTypeRep(LocType); 2922 break; 2923 } 2924 2925 case DeclSpec::TST_typeofExpr: { 2926 Expr *E = DS.getRepAsExpr(); 2927 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 2928 if (Result.isInvalid()) return true; 2929 DS.UpdateExprRep(Result.get()); 2930 break; 2931 } 2932 2933 default: 2934 // Nothing to do for these decl specs. 2935 break; 2936 } 2937 2938 // It doesn't matter what order we do this in. 2939 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 2940 DeclaratorChunk &Chunk = D.getTypeObject(I); 2941 2942 // The only type information in the declarator which can come 2943 // before the declaration name is the base type of a member 2944 // pointer. 2945 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 2946 continue; 2947 2948 // Rebuild the scope specifier in-place. 2949 CXXScopeSpec &SS = Chunk.Mem.Scope(); 2950 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 2951 return true; 2952 } 2953 2954 return false; 2955 } 2956 2957 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 2958 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this), 2959 /*IsFunctionDefinition=*/false); 2960 } 2961 2962 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 2963 /// If T is the name of a class, then each of the following shall have a 2964 /// name different from T: 2965 /// - every static data member of class T; 2966 /// - every member function of class T 2967 /// - every member of class T that is itself a type; 2968 /// \returns true if the declaration name violates these rules. 2969 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 2970 DeclarationNameInfo NameInfo) { 2971 DeclarationName Name = NameInfo.getName(); 2972 2973 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 2974 if (Record->getIdentifier() && Record->getDeclName() == Name) { 2975 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 2976 return true; 2977 } 2978 2979 return false; 2980 } 2981 2982 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 2983 MultiTemplateParamsArg TemplateParamLists, 2984 bool IsFunctionDefinition) { 2985 // TODO: consider using NameInfo for diagnostic. 2986 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2987 DeclarationName Name = NameInfo.getName(); 2988 2989 // All of these full declarators require an identifier. If it doesn't have 2990 // one, the ParsedFreeStandingDeclSpec action should be used. 2991 if (!Name) { 2992 if (!D.isInvalidType()) // Reject this if we think it is valid. 2993 Diag(D.getDeclSpec().getSourceRange().getBegin(), 2994 diag::err_declarator_need_ident) 2995 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 2996 return 0; 2997 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 2998 return 0; 2999 3000 // The scope passed in may not be a decl scope. Zip up the scope tree until 3001 // we find one that is. 3002 while ((S->getFlags() & Scope::DeclScope) == 0 || 3003 (S->getFlags() & Scope::TemplateParamScope) != 0) 3004 S = S->getParent(); 3005 3006 DeclContext *DC = CurContext; 3007 if (D.getCXXScopeSpec().isInvalid()) 3008 D.setInvalidType(); 3009 else if (D.getCXXScopeSpec().isSet()) { 3010 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 3011 UPPC_DeclarationQualifier)) 3012 return 0; 3013 3014 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 3015 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 3016 if (!DC) { 3017 // If we could not compute the declaration context, it's because the 3018 // declaration context is dependent but does not refer to a class, 3019 // class template, or class template partial specialization. Complain 3020 // and return early, to avoid the coming semantic disaster. 3021 Diag(D.getIdentifierLoc(), 3022 diag::err_template_qualified_declarator_no_match) 3023 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 3024 << D.getCXXScopeSpec().getRange(); 3025 return 0; 3026 } 3027 bool IsDependentContext = DC->isDependentContext(); 3028 3029 if (!IsDependentContext && 3030 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 3031 return 0; 3032 3033 if (isa<CXXRecordDecl>(DC)) { 3034 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) { 3035 Diag(D.getIdentifierLoc(), 3036 diag::err_member_def_undefined_record) 3037 << Name << DC << D.getCXXScopeSpec().getRange(); 3038 D.setInvalidType(); 3039 } else if (isa<CXXRecordDecl>(CurContext) && 3040 !D.getDeclSpec().isFriendSpecified()) { 3041 // The user provided a superfluous scope specifier inside a class 3042 // definition: 3043 // 3044 // class X { 3045 // void X::f(); 3046 // }; 3047 if (CurContext->Equals(DC)) 3048 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 3049 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange()); 3050 else 3051 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3052 << Name << D.getCXXScopeSpec().getRange(); 3053 3054 // Pretend that this qualifier was not here. 3055 D.getCXXScopeSpec().clear(); 3056 } 3057 } 3058 3059 // Check whether we need to rebuild the type of the given 3060 // declaration in the current instantiation. 3061 if (EnteringContext && IsDependentContext && 3062 TemplateParamLists.size() != 0) { 3063 ContextRAII SavedContext(*this, DC); 3064 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 3065 D.setInvalidType(); 3066 } 3067 } 3068 3069 if (DiagnoseClassNameShadow(DC, NameInfo)) 3070 // If this is a typedef, we'll end up spewing multiple diagnostics. 3071 // Just return early; it's safer. 3072 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3073 return 0; 3074 3075 NamedDecl *New; 3076 3077 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3078 QualType R = TInfo->getType(); 3079 3080 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 3081 UPPC_DeclarationType)) 3082 D.setInvalidType(); 3083 3084 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 3085 ForRedeclaration); 3086 3087 // See if this is a redefinition of a variable in the same scope. 3088 if (!D.getCXXScopeSpec().isSet()) { 3089 bool IsLinkageLookup = false; 3090 3091 // If the declaration we're planning to build will be a function 3092 // or object with linkage, then look for another declaration with 3093 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 3094 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3095 /* Do nothing*/; 3096 else if (R->isFunctionType()) { 3097 if (CurContext->isFunctionOrMethod() || 3098 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3099 IsLinkageLookup = true; 3100 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 3101 IsLinkageLookup = true; 3102 else if (CurContext->getRedeclContext()->isTranslationUnit() && 3103 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3104 IsLinkageLookup = true; 3105 3106 if (IsLinkageLookup) 3107 Previous.clear(LookupRedeclarationWithLinkage); 3108 3109 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 3110 } else { // Something like "int foo::x;" 3111 LookupQualifiedName(Previous, DC); 3112 3113 // Don't consider using declarations as previous declarations for 3114 // out-of-line members. 3115 RemoveUsingDecls(Previous); 3116 3117 // C++ 7.3.1.2p2: 3118 // Members (including explicit specializations of templates) of a named 3119 // namespace can also be defined outside that namespace by explicit 3120 // qualification of the name being defined, provided that the entity being 3121 // defined was already declared in the namespace and the definition appears 3122 // after the point of declaration in a namespace that encloses the 3123 // declarations namespace. 3124 // 3125 // Note that we only check the context at this point. We don't yet 3126 // have enough information to make sure that PrevDecl is actually 3127 // the declaration we want to match. For example, given: 3128 // 3129 // class X { 3130 // void f(); 3131 // void f(float); 3132 // }; 3133 // 3134 // void X::f(int) { } // ill-formed 3135 // 3136 // In this case, PrevDecl will point to the overload set 3137 // containing the two f's declared in X, but neither of them 3138 // matches. 3139 3140 // First check whether we named the global scope. 3141 if (isa<TranslationUnitDecl>(DC)) { 3142 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 3143 << Name << D.getCXXScopeSpec().getRange(); 3144 } else { 3145 DeclContext *Cur = CurContext; 3146 while (isa<LinkageSpecDecl>(Cur)) 3147 Cur = Cur->getParent(); 3148 if (!Cur->Encloses(DC)) { 3149 // The qualifying scope doesn't enclose the original declaration. 3150 // Emit diagnostic based on current scope. 3151 SourceLocation L = D.getIdentifierLoc(); 3152 SourceRange R = D.getCXXScopeSpec().getRange(); 3153 if (isa<FunctionDecl>(Cur)) 3154 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 3155 else 3156 Diag(L, diag::err_invalid_declarator_scope) 3157 << Name << cast<NamedDecl>(DC) << R; 3158 D.setInvalidType(); 3159 } 3160 } 3161 } 3162 3163 if (Previous.isSingleResult() && 3164 Previous.getFoundDecl()->isTemplateParameter()) { 3165 // Maybe we will complain about the shadowed template parameter. 3166 if (!D.isInvalidType()) 3167 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 3168 Previous.getFoundDecl())) 3169 D.setInvalidType(); 3170 3171 // Just pretend that we didn't see the previous declaration. 3172 Previous.clear(); 3173 } 3174 3175 // In C++, the previous declaration we find might be a tag type 3176 // (class or enum). In this case, the new declaration will hide the 3177 // tag type. Note that this does does not apply if we're declaring a 3178 // typedef (C++ [dcl.typedef]p4). 3179 if (Previous.isSingleTagDecl() && 3180 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 3181 Previous.clear(); 3182 3183 bool Redeclaration = false; 3184 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3185 if (TemplateParamLists.size()) { 3186 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 3187 return 0; 3188 } 3189 3190 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration); 3191 } else if (R->isFunctionType()) { 3192 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous, 3193 move(TemplateParamLists), 3194 IsFunctionDefinition, Redeclaration); 3195 } else { 3196 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous, 3197 move(TemplateParamLists), 3198 Redeclaration); 3199 } 3200 3201 if (New == 0) 3202 return 0; 3203 3204 // If this has an identifier and is not an invalid redeclaration or 3205 // function template specialization, add it to the scope stack. 3206 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl())) 3207 PushOnScopeChains(New, S); 3208 3209 return New; 3210 } 3211 3212 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 3213 /// types into constant array types in certain situations which would otherwise 3214 /// be errors (for GCC compatibility). 3215 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3216 ASTContext &Context, 3217 bool &SizeIsNegative, 3218 llvm::APSInt &Oversized) { 3219 // This method tries to turn a variable array into a constant 3220 // array even when the size isn't an ICE. This is necessary 3221 // for compatibility with code that depends on gcc's buggy 3222 // constant expression folding, like struct {char x[(int)(char*)2];} 3223 SizeIsNegative = false; 3224 Oversized = 0; 3225 3226 if (T->isDependentType()) 3227 return QualType(); 3228 3229 QualifierCollector Qs; 3230 const Type *Ty = Qs.strip(T); 3231 3232 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 3233 QualType Pointee = PTy->getPointeeType(); 3234 QualType FixedType = 3235 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 3236 Oversized); 3237 if (FixedType.isNull()) return FixedType; 3238 FixedType = Context.getPointerType(FixedType); 3239 return Qs.apply(Context, FixedType); 3240 } 3241 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 3242 QualType Inner = PTy->getInnerType(); 3243 QualType FixedType = 3244 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 3245 Oversized); 3246 if (FixedType.isNull()) return FixedType; 3247 FixedType = Context.getParenType(FixedType); 3248 return Qs.apply(Context, FixedType); 3249 } 3250 3251 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3252 if (!VLATy) 3253 return QualType(); 3254 // FIXME: We should probably handle this case 3255 if (VLATy->getElementType()->isVariablyModifiedType()) 3256 return QualType(); 3257 3258 Expr::EvalResult EvalResult; 3259 if (!VLATy->getSizeExpr() || 3260 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 3261 !EvalResult.Val.isInt()) 3262 return QualType(); 3263 3264 // Check whether the array size is negative. 3265 llvm::APSInt &Res = EvalResult.Val.getInt(); 3266 if (Res.isSigned() && Res.isNegative()) { 3267 SizeIsNegative = true; 3268 return QualType(); 3269 } 3270 3271 // Check whether the array is too large to be addressed. 3272 unsigned ActiveSizeBits 3273 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 3274 Res); 3275 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 3276 Oversized = Res; 3277 return QualType(); 3278 } 3279 3280 return Context.getConstantArrayType(VLATy->getElementType(), 3281 Res, ArrayType::Normal, 0); 3282 } 3283 3284 /// \brief Register the given locally-scoped external C declaration so 3285 /// that it can be found later for redeclarations 3286 void 3287 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 3288 const LookupResult &Previous, 3289 Scope *S) { 3290 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 3291 "Decl is not a locally-scoped decl!"); 3292 // Note that we have a locally-scoped external with this name. 3293 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 3294 3295 if (!Previous.isSingleResult()) 3296 return; 3297 3298 NamedDecl *PrevDecl = Previous.getFoundDecl(); 3299 3300 // If there was a previous declaration of this variable, it may be 3301 // in our identifier chain. Update the identifier chain with the new 3302 // declaration. 3303 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 3304 // The previous declaration was found on the identifer resolver 3305 // chain, so remove it from its scope. 3306 3307 if (S->isDeclScope(PrevDecl)) { 3308 // Special case for redeclarations in the SAME scope. 3309 // Because this declaration is going to be added to the identifier chain 3310 // later, we should temporarily take it OFF the chain. 3311 IdResolver.RemoveDecl(ND); 3312 3313 } else { 3314 // Find the scope for the original declaration. 3315 while (S && !S->isDeclScope(PrevDecl)) 3316 S = S->getParent(); 3317 } 3318 3319 if (S) 3320 S->RemoveDecl(PrevDecl); 3321 } 3322 } 3323 3324 /// \brief Diagnose function specifiers on a declaration of an identifier that 3325 /// does not identify a function. 3326 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 3327 // FIXME: We should probably indicate the identifier in question to avoid 3328 // confusion for constructs like "inline int a(), b;" 3329 if (D.getDeclSpec().isInlineSpecified()) 3330 Diag(D.getDeclSpec().getInlineSpecLoc(), 3331 diag::err_inline_non_function); 3332 3333 if (D.getDeclSpec().isVirtualSpecified()) 3334 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3335 diag::err_virtual_non_function); 3336 3337 if (D.getDeclSpec().isExplicitSpecified()) 3338 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3339 diag::err_explicit_non_function); 3340 } 3341 3342 NamedDecl* 3343 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 3344 QualType R, TypeSourceInfo *TInfo, 3345 LookupResult &Previous, bool &Redeclaration) { 3346 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 3347 if (D.getCXXScopeSpec().isSet()) { 3348 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 3349 << D.getCXXScopeSpec().getRange(); 3350 D.setInvalidType(); 3351 // Pretend we didn't see the scope specifier. 3352 DC = CurContext; 3353 Previous.clear(); 3354 } 3355 3356 if (getLangOptions().CPlusPlus) { 3357 // Check that there are no default arguments (C++ only). 3358 CheckExtraCXXDefaultArguments(D); 3359 } 3360 3361 DiagnoseFunctionSpecifiers(D); 3362 3363 if (D.getDeclSpec().isThreadSpecified()) 3364 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3365 3366 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 3367 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 3368 << D.getName().getSourceRange(); 3369 return 0; 3370 } 3371 3372 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo); 3373 if (!NewTD) return 0; 3374 3375 // Handle attributes prior to checking for duplicates in MergeVarDecl 3376 ProcessDeclAttributes(S, NewTD, D); 3377 3378 CheckTypedefForVariablyModifiedType(S, NewTD); 3379 3380 return ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 3381 } 3382 3383 void 3384 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 3385 // C99 6.7.7p2: If a typedef name specifies a variably modified type 3386 // then it shall have block scope. 3387 // Note that variably modified types must be fixed before merging the decl so 3388 // that redeclarations will match. 3389 QualType T = NewTD->getUnderlyingType(); 3390 if (T->isVariablyModifiedType()) { 3391 getCurFunction()->setHasBranchProtectedScope(); 3392 3393 if (S->getFnParent() == 0) { 3394 bool SizeIsNegative; 3395 llvm::APSInt Oversized; 3396 QualType FixedTy = 3397 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 3398 Oversized); 3399 if (!FixedTy.isNull()) { 3400 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 3401 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 3402 } else { 3403 if (SizeIsNegative) 3404 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 3405 else if (T->isVariableArrayType()) 3406 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 3407 else if (Oversized.getBoolValue()) 3408 Diag(NewTD->getLocation(), diag::err_array_too_large) << Oversized.toString(10); 3409 else 3410 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 3411 NewTD->setInvalidDecl(); 3412 } 3413 } 3414 } 3415 } 3416 3417 3418 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 3419 /// declares a typedef-name, either using the 'typedef' type specifier or via 3420 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 3421 NamedDecl* 3422 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 3423 LookupResult &Previous, bool &Redeclaration) { 3424 // Merge the decl with the existing one if appropriate. If the decl is 3425 // in an outer scope, it isn't the same thing. 3426 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 3427 /*ExplicitInstantiationOrSpecialization=*/false); 3428 if (!Previous.empty()) { 3429 Redeclaration = true; 3430 MergeTypedefNameDecl(NewTD, Previous); 3431 } 3432 3433 // If this is the C FILE type, notify the AST context. 3434 if (IdentifierInfo *II = NewTD->getIdentifier()) 3435 if (!NewTD->isInvalidDecl() && 3436 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 3437 if (II->isStr("FILE")) 3438 Context.setFILEDecl(NewTD); 3439 else if (II->isStr("jmp_buf")) 3440 Context.setjmp_bufDecl(NewTD); 3441 else if (II->isStr("sigjmp_buf")) 3442 Context.setsigjmp_bufDecl(NewTD); 3443 else if (II->isStr("__builtin_va_list")) 3444 Context.setBuiltinVaListType(Context.getTypedefType(NewTD)); 3445 } 3446 3447 return NewTD; 3448 } 3449 3450 /// \brief Determines whether the given declaration is an out-of-scope 3451 /// previous declaration. 3452 /// 3453 /// This routine should be invoked when name lookup has found a 3454 /// previous declaration (PrevDecl) that is not in the scope where a 3455 /// new declaration by the same name is being introduced. If the new 3456 /// declaration occurs in a local scope, previous declarations with 3457 /// linkage may still be considered previous declarations (C99 3458 /// 6.2.2p4-5, C++ [basic.link]p6). 3459 /// 3460 /// \param PrevDecl the previous declaration found by name 3461 /// lookup 3462 /// 3463 /// \param DC the context in which the new declaration is being 3464 /// declared. 3465 /// 3466 /// \returns true if PrevDecl is an out-of-scope previous declaration 3467 /// for a new delcaration with the same name. 3468 static bool 3469 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 3470 ASTContext &Context) { 3471 if (!PrevDecl) 3472 return false; 3473 3474 if (!PrevDecl->hasLinkage()) 3475 return false; 3476 3477 if (Context.getLangOptions().CPlusPlus) { 3478 // C++ [basic.link]p6: 3479 // If there is a visible declaration of an entity with linkage 3480 // having the same name and type, ignoring entities declared 3481 // outside the innermost enclosing namespace scope, the block 3482 // scope declaration declares that same entity and receives the 3483 // linkage of the previous declaration. 3484 DeclContext *OuterContext = DC->getRedeclContext(); 3485 if (!OuterContext->isFunctionOrMethod()) 3486 // This rule only applies to block-scope declarations. 3487 return false; 3488 3489 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 3490 if (PrevOuterContext->isRecord()) 3491 // We found a member function: ignore it. 3492 return false; 3493 3494 // Find the innermost enclosing namespace for the new and 3495 // previous declarations. 3496 OuterContext = OuterContext->getEnclosingNamespaceContext(); 3497 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 3498 3499 // The previous declaration is in a different namespace, so it 3500 // isn't the same function. 3501 if (!OuterContext->Equals(PrevOuterContext)) 3502 return false; 3503 } 3504 3505 return true; 3506 } 3507 3508 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 3509 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3510 if (!SS.isSet()) return; 3511 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 3512 } 3513 3514 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 3515 QualType type = decl->getType(); 3516 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 3517 if (lifetime == Qualifiers::OCL_Autoreleasing) { 3518 // Various kinds of declaration aren't allowed to be __autoreleasing. 3519 unsigned kind = -1U; 3520 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3521 if (var->hasAttr<BlocksAttr>()) 3522 kind = 0; // __block 3523 else if (!var->hasLocalStorage()) 3524 kind = 1; // global 3525 } else if (isa<ObjCIvarDecl>(decl)) { 3526 kind = 3; // ivar 3527 } else if (isa<FieldDecl>(decl)) { 3528 kind = 2; // field 3529 } 3530 3531 if (kind != -1U) { 3532 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 3533 << kind; 3534 } 3535 } else if (lifetime == Qualifiers::OCL_None) { 3536 // Try to infer lifetime. 3537 if (!type->isObjCLifetimeType()) 3538 return false; 3539 3540 lifetime = type->getObjCARCImplicitLifetime(); 3541 type = Context.getLifetimeQualifiedType(type, lifetime); 3542 decl->setType(type); 3543 } 3544 3545 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3546 // Thread-local variables cannot have lifetime. 3547 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 3548 var->isThreadSpecified()) { 3549 Diag(var->getLocation(), diag::err_arc_thread_ownership) 3550 << var->getType(); 3551 return true; 3552 } 3553 } 3554 3555 return false; 3556 } 3557 3558 NamedDecl* 3559 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 3560 QualType R, TypeSourceInfo *TInfo, 3561 LookupResult &Previous, 3562 MultiTemplateParamsArg TemplateParamLists, 3563 bool &Redeclaration) { 3564 DeclarationName Name = GetNameForDeclarator(D).getName(); 3565 3566 // Check that there are no default arguments (C++ only). 3567 if (getLangOptions().CPlusPlus) 3568 CheckExtraCXXDefaultArguments(D); 3569 3570 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 3571 assert(SCSpec != DeclSpec::SCS_typedef && 3572 "Parser allowed 'typedef' as storage class VarDecl."); 3573 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3574 if (SCSpec == DeclSpec::SCS_mutable) { 3575 // mutable can only appear on non-static class members, so it's always 3576 // an error here 3577 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 3578 D.setInvalidType(); 3579 SC = SC_None; 3580 } 3581 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 3582 VarDecl::StorageClass SCAsWritten 3583 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3584 3585 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3586 if (!II) { 3587 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 3588 << Name.getAsString(); 3589 return 0; 3590 } 3591 3592 DiagnoseFunctionSpecifiers(D); 3593 3594 if (!DC->isRecord() && S->getFnParent() == 0) { 3595 // C99 6.9p2: The storage-class specifiers auto and register shall not 3596 // appear in the declaration specifiers in an external declaration. 3597 if (SC == SC_Auto || SC == SC_Register) { 3598 3599 // If this is a register variable with an asm label specified, then this 3600 // is a GNU extension. 3601 if (SC == SC_Register && D.getAsmLabel()) 3602 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 3603 else 3604 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 3605 D.setInvalidType(); 3606 } 3607 } 3608 3609 bool isExplicitSpecialization = false; 3610 VarDecl *NewVD; 3611 if (!getLangOptions().CPlusPlus) { 3612 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3613 D.getIdentifierLoc(), II, 3614 R, TInfo, SC, SCAsWritten); 3615 3616 if (D.isInvalidType()) 3617 NewVD->setInvalidDecl(); 3618 } else { 3619 if (DC->isRecord() && !CurContext->isRecord()) { 3620 // This is an out-of-line definition of a static data member. 3621 if (SC == SC_Static) { 3622 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3623 diag::err_static_out_of_line) 3624 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3625 } else if (SC == SC_None) 3626 SC = SC_Static; 3627 } 3628 if (SC == SC_Static) { 3629 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 3630 if (RD->isLocalClass()) 3631 Diag(D.getIdentifierLoc(), 3632 diag::err_static_data_member_not_allowed_in_local_class) 3633 << Name << RD->getDeclName(); 3634 3635 // C++ [class.union]p1: If a union contains a static data member, 3636 // the program is ill-formed. 3637 // 3638 // We also disallow static data members in anonymous structs. 3639 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName())) 3640 Diag(D.getIdentifierLoc(), 3641 diag::err_static_data_member_not_allowed_in_union_or_anon_struct) 3642 << Name << RD->isUnion(); 3643 } 3644 } 3645 3646 // Match up the template parameter lists with the scope specifier, then 3647 // determine whether we have a template or a template specialization. 3648 isExplicitSpecialization = false; 3649 bool Invalid = false; 3650 if (TemplateParameterList *TemplateParams 3651 = MatchTemplateParametersToScopeSpecifier( 3652 D.getDeclSpec().getSourceRange().getBegin(), 3653 D.getIdentifierLoc(), 3654 D.getCXXScopeSpec(), 3655 TemplateParamLists.get(), 3656 TemplateParamLists.size(), 3657 /*never a friend*/ false, 3658 isExplicitSpecialization, 3659 Invalid)) { 3660 if (TemplateParams->size() > 0) { 3661 // There is no such thing as a variable template. 3662 Diag(D.getIdentifierLoc(), diag::err_template_variable) 3663 << II 3664 << SourceRange(TemplateParams->getTemplateLoc(), 3665 TemplateParams->getRAngleLoc()); 3666 return 0; 3667 } else { 3668 // There is an extraneous 'template<>' for this variable. Complain 3669 // about it, but allow the declaration of the variable. 3670 Diag(TemplateParams->getTemplateLoc(), 3671 diag::err_template_variable_noparams) 3672 << II 3673 << SourceRange(TemplateParams->getTemplateLoc(), 3674 TemplateParams->getRAngleLoc()); 3675 } 3676 } 3677 3678 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3679 D.getIdentifierLoc(), II, 3680 R, TInfo, SC, SCAsWritten); 3681 3682 // If this decl has an auto type in need of deduction, make a note of the 3683 // Decl so we can diagnose uses of it in its own initializer. 3684 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 3685 R->getContainedAutoType()) 3686 ParsingInitForAutoVars.insert(NewVD); 3687 3688 if (D.isInvalidType() || Invalid) 3689 NewVD->setInvalidDecl(); 3690 3691 SetNestedNameSpecifier(NewVD, D); 3692 3693 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 3694 NewVD->setTemplateParameterListsInfo(Context, 3695 TemplateParamLists.size(), 3696 TemplateParamLists.release()); 3697 } 3698 } 3699 3700 if (D.getDeclSpec().isThreadSpecified()) { 3701 if (NewVD->hasLocalStorage()) 3702 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 3703 else if (!Context.Target.isTLSSupported()) 3704 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 3705 else 3706 NewVD->setThreadSpecified(true); 3707 } 3708 3709 // Set the lexical context. If the declarator has a C++ scope specifier, the 3710 // lexical context will be different from the semantic context. 3711 NewVD->setLexicalDeclContext(CurContext); 3712 3713 // Handle attributes prior to checking for duplicates in MergeVarDecl 3714 ProcessDeclAttributes(S, NewVD, D); 3715 3716 // In auto-retain/release, infer strong retension for variables of 3717 // retainable type. 3718 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 3719 NewVD->setInvalidDecl(); 3720 3721 // Handle GNU asm-label extension (encoded as an attribute). 3722 if (Expr *E = (Expr*)D.getAsmLabel()) { 3723 // The parser guarantees this is a string. 3724 StringLiteral *SE = cast<StringLiteral>(E); 3725 llvm::StringRef Label = SE->getString(); 3726 if (S->getFnParent() != 0) { 3727 switch (SC) { 3728 case SC_None: 3729 case SC_Auto: 3730 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 3731 break; 3732 case SC_Register: 3733 if (!Context.Target.isValidGCCRegisterName(Label)) 3734 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 3735 break; 3736 case SC_Static: 3737 case SC_Extern: 3738 case SC_PrivateExtern: 3739 break; 3740 } 3741 } 3742 3743 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 3744 Context, Label)); 3745 } 3746 3747 // Diagnose shadowed variables before filtering for scope. 3748 if (!D.getCXXScopeSpec().isSet()) 3749 CheckShadow(S, NewVD, Previous); 3750 3751 // Don't consider existing declarations that are in a different 3752 // scope and are out-of-semantic-context declarations (if the new 3753 // declaration has linkage). 3754 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 3755 isExplicitSpecialization); 3756 3757 if (!getLangOptions().CPlusPlus) 3758 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 3759 else { 3760 // Merge the decl with the existing one if appropriate. 3761 if (!Previous.empty()) { 3762 if (Previous.isSingleResult() && 3763 isa<FieldDecl>(Previous.getFoundDecl()) && 3764 D.getCXXScopeSpec().isSet()) { 3765 // The user tried to define a non-static data member 3766 // out-of-line (C++ [dcl.meaning]p1). 3767 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 3768 << D.getCXXScopeSpec().getRange(); 3769 Previous.clear(); 3770 NewVD->setInvalidDecl(); 3771 } 3772 } else if (D.getCXXScopeSpec().isSet()) { 3773 // No previous declaration in the qualifying scope. 3774 Diag(D.getIdentifierLoc(), diag::err_no_member) 3775 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 3776 << D.getCXXScopeSpec().getRange(); 3777 NewVD->setInvalidDecl(); 3778 } 3779 3780 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 3781 3782 // This is an explicit specialization of a static data member. Check it. 3783 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 3784 CheckMemberSpecialization(NewVD, Previous)) 3785 NewVD->setInvalidDecl(); 3786 } 3787 3788 // attributes declared post-definition are currently ignored 3789 // FIXME: This should be handled in attribute merging, not 3790 // here. 3791 if (Previous.isSingleResult()) { 3792 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3793 if (Def && (Def = Def->getDefinition()) && 3794 Def != NewVD && D.hasAttributes()) { 3795 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 3796 Diag(Def->getLocation(), diag::note_previous_definition); 3797 } 3798 } 3799 3800 // If this is a locally-scoped extern C variable, update the map of 3801 // such variables. 3802 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 3803 !NewVD->isInvalidDecl()) 3804 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 3805 3806 // If there's a #pragma GCC visibility in scope, and this isn't a class 3807 // member, set the visibility of this variable. 3808 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 3809 AddPushedVisibilityAttribute(NewVD); 3810 3811 MarkUnusedFileScopedDecl(NewVD); 3812 3813 return NewVD; 3814 } 3815 3816 /// \brief Diagnose variable or built-in function shadowing. Implements 3817 /// -Wshadow. 3818 /// 3819 /// This method is called whenever a VarDecl is added to a "useful" 3820 /// scope. 3821 /// 3822 /// \param S the scope in which the shadowing name is being declared 3823 /// \param R the lookup of the name 3824 /// 3825 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 3826 // Return if warning is ignored. 3827 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 3828 Diagnostic::Ignored) 3829 return; 3830 3831 // Don't diagnose declarations at file scope. 3832 if (D->hasGlobalStorage()) 3833 return; 3834 3835 DeclContext *NewDC = D->getDeclContext(); 3836 3837 // Only diagnose if we're shadowing an unambiguous field or variable. 3838 if (R.getResultKind() != LookupResult::Found) 3839 return; 3840 3841 NamedDecl* ShadowedDecl = R.getFoundDecl(); 3842 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 3843 return; 3844 3845 // Fields are not shadowed by variables in C++ static methods. 3846 if (isa<FieldDecl>(ShadowedDecl)) 3847 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 3848 if (MD->isStatic()) 3849 return; 3850 3851 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 3852 if (shadowedVar->isExternC()) { 3853 // For shadowing external vars, make sure that we point to the global 3854 // declaration, not a locally scoped extern declaration. 3855 for (VarDecl::redecl_iterator 3856 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 3857 I != E; ++I) 3858 if (I->isFileVarDecl()) { 3859 ShadowedDecl = *I; 3860 break; 3861 } 3862 } 3863 3864 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 3865 3866 // Only warn about certain kinds of shadowing for class members. 3867 if (NewDC && NewDC->isRecord()) { 3868 // In particular, don't warn about shadowing non-class members. 3869 if (!OldDC->isRecord()) 3870 return; 3871 3872 // TODO: should we warn about static data members shadowing 3873 // static data members from base classes? 3874 3875 // TODO: don't diagnose for inaccessible shadowed members. 3876 // This is hard to do perfectly because we might friend the 3877 // shadowing context, but that's just a false negative. 3878 } 3879 3880 // Determine what kind of declaration we're shadowing. 3881 unsigned Kind; 3882 if (isa<RecordDecl>(OldDC)) { 3883 if (isa<FieldDecl>(ShadowedDecl)) 3884 Kind = 3; // field 3885 else 3886 Kind = 2; // static data member 3887 } else if (OldDC->isFileContext()) 3888 Kind = 1; // global 3889 else 3890 Kind = 0; // local 3891 3892 DeclarationName Name = R.getLookupName(); 3893 3894 // Emit warning and note. 3895 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 3896 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 3897 } 3898 3899 /// \brief Check -Wshadow without the advantage of a previous lookup. 3900 void Sema::CheckShadow(Scope *S, VarDecl *D) { 3901 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 3902 Diagnostic::Ignored) 3903 return; 3904 3905 LookupResult R(*this, D->getDeclName(), D->getLocation(), 3906 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 3907 LookupName(R, S); 3908 CheckShadow(S, D, R); 3909 } 3910 3911 /// \brief Perform semantic checking on a newly-created variable 3912 /// declaration. 3913 /// 3914 /// This routine performs all of the type-checking required for a 3915 /// variable declaration once it has been built. It is used both to 3916 /// check variables after they have been parsed and their declarators 3917 /// have been translated into a declaration, and to check variables 3918 /// that have been instantiated from a template. 3919 /// 3920 /// Sets NewVD->isInvalidDecl() if an error was encountered. 3921 void Sema::CheckVariableDeclaration(VarDecl *NewVD, 3922 LookupResult &Previous, 3923 bool &Redeclaration) { 3924 // If the decl is already known invalid, don't check it. 3925 if (NewVD->isInvalidDecl()) 3926 return; 3927 3928 QualType T = NewVD->getType(); 3929 3930 if (T->isObjCObjectType()) { 3931 Diag(NewVD->getLocation(), diag::err_statically_allocated_object); 3932 return NewVD->setInvalidDecl(); 3933 } 3934 3935 // Emit an error if an address space was applied to decl with local storage. 3936 // This includes arrays of objects with address space qualifiers, but not 3937 // automatic variables that point to other address spaces. 3938 // ISO/IEC TR 18037 S5.1.2 3939 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 3940 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 3941 return NewVD->setInvalidDecl(); 3942 } 3943 3944 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 3945 && !NewVD->hasAttr<BlocksAttr>()) { 3946 if (getLangOptions().getGCMode() != LangOptions::NonGC) 3947 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 3948 else 3949 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 3950 } 3951 3952 bool isVM = T->isVariablyModifiedType(); 3953 if (isVM || NewVD->hasAttr<CleanupAttr>() || 3954 NewVD->hasAttr<BlocksAttr>()) 3955 getCurFunction()->setHasBranchProtectedScope(); 3956 3957 if ((isVM && NewVD->hasLinkage()) || 3958 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 3959 bool SizeIsNegative; 3960 llvm::APSInt Oversized; 3961 QualType FixedTy = 3962 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 3963 Oversized); 3964 3965 if (FixedTy.isNull() && T->isVariableArrayType()) { 3966 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 3967 // FIXME: This won't give the correct result for 3968 // int a[10][n]; 3969 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 3970 3971 if (NewVD->isFileVarDecl()) 3972 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 3973 << SizeRange; 3974 else if (NewVD->getStorageClass() == SC_Static) 3975 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 3976 << SizeRange; 3977 else 3978 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 3979 << SizeRange; 3980 return NewVD->setInvalidDecl(); 3981 } 3982 3983 if (FixedTy.isNull()) { 3984 if (NewVD->isFileVarDecl()) 3985 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 3986 else 3987 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 3988 return NewVD->setInvalidDecl(); 3989 } 3990 3991 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 3992 NewVD->setType(FixedTy); 3993 } 3994 3995 if (Previous.empty() && NewVD->isExternC()) { 3996 // Since we did not find anything by this name and we're declaring 3997 // an extern "C" variable, look for a non-visible extern "C" 3998 // declaration with the same name. 3999 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4000 = LocallyScopedExternalDecls.find(NewVD->getDeclName()); 4001 if (Pos != LocallyScopedExternalDecls.end()) 4002 Previous.addDecl(Pos->second); 4003 } 4004 4005 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 4006 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 4007 << T; 4008 return NewVD->setInvalidDecl(); 4009 } 4010 4011 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 4012 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 4013 return NewVD->setInvalidDecl(); 4014 } 4015 4016 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 4017 Diag(NewVD->getLocation(), diag::err_block_on_vm); 4018 return NewVD->setInvalidDecl(); 4019 } 4020 4021 // Function pointers and references cannot have qualified function type, only 4022 // function pointer-to-members can do that. 4023 QualType Pointee; 4024 unsigned PtrOrRef = 0; 4025 if (const PointerType *Ptr = T->getAs<PointerType>()) 4026 Pointee = Ptr->getPointeeType(); 4027 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) { 4028 Pointee = Ref->getPointeeType(); 4029 PtrOrRef = 1; 4030 } 4031 if (!Pointee.isNull() && Pointee->isFunctionProtoType() && 4032 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) { 4033 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer) 4034 << PtrOrRef; 4035 return NewVD->setInvalidDecl(); 4036 } 4037 4038 if (!Previous.empty()) { 4039 Redeclaration = true; 4040 MergeVarDecl(NewVD, Previous); 4041 } 4042 } 4043 4044 /// \brief Data used with FindOverriddenMethod 4045 struct FindOverriddenMethodData { 4046 Sema *S; 4047 CXXMethodDecl *Method; 4048 }; 4049 4050 /// \brief Member lookup function that determines whether a given C++ 4051 /// method overrides a method in a base class, to be used with 4052 /// CXXRecordDecl::lookupInBases(). 4053 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 4054 CXXBasePath &Path, 4055 void *UserData) { 4056 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4057 4058 FindOverriddenMethodData *Data 4059 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 4060 4061 DeclarationName Name = Data->Method->getDeclName(); 4062 4063 // FIXME: Do we care about other names here too? 4064 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4065 // We really want to find the base class destructor here. 4066 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 4067 CanQualType CT = Data->S->Context.getCanonicalType(T); 4068 4069 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 4070 } 4071 4072 for (Path.Decls = BaseRecord->lookup(Name); 4073 Path.Decls.first != Path.Decls.second; 4074 ++Path.Decls.first) { 4075 NamedDecl *D = *Path.Decls.first; 4076 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4077 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 4078 return true; 4079 } 4080 } 4081 4082 return false; 4083 } 4084 4085 /// AddOverriddenMethods - See if a method overrides any in the base classes, 4086 /// and if so, check that it's a valid override and remember it. 4087 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4088 // Look for virtual methods in base classes that this method might override. 4089 CXXBasePaths Paths; 4090 FindOverriddenMethodData Data; 4091 Data.Method = MD; 4092 Data.S = this; 4093 bool AddedAny = false; 4094 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 4095 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 4096 E = Paths.found_decls_end(); I != E; ++I) { 4097 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 4098 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 4099 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 4100 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 4101 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 4102 AddedAny = true; 4103 } 4104 } 4105 } 4106 } 4107 4108 return AddedAny; 4109 } 4110 4111 static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD) { 4112 LookupResult Prev(S, NewFD->getDeclName(), NewFD->getLocation(), 4113 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4114 S.LookupQualifiedName(Prev, NewFD->getDeclContext()); 4115 assert(!Prev.isAmbiguous() && 4116 "Cannot have an ambiguity in previous-declaration lookup"); 4117 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 4118 Func != FuncEnd; ++Func) { 4119 if (isa<FunctionDecl>(*Func) && 4120 isNearlyMatchingFunction(S.Context, cast<FunctionDecl>(*Func), NewFD)) 4121 S.Diag((*Func)->getLocation(), diag::note_member_def_close_match); 4122 } 4123 } 4124 4125 NamedDecl* 4126 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4127 QualType R, TypeSourceInfo *TInfo, 4128 LookupResult &Previous, 4129 MultiTemplateParamsArg TemplateParamLists, 4130 bool IsFunctionDefinition, bool &Redeclaration) { 4131 assert(R.getTypePtr()->isFunctionType()); 4132 4133 // TODO: consider using NameInfo for diagnostic. 4134 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4135 DeclarationName Name = NameInfo.getName(); 4136 FunctionDecl::StorageClass SC = SC_None; 4137 switch (D.getDeclSpec().getStorageClassSpec()) { 4138 default: assert(0 && "Unknown storage class!"); 4139 case DeclSpec::SCS_auto: 4140 case DeclSpec::SCS_register: 4141 case DeclSpec::SCS_mutable: 4142 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4143 diag::err_typecheck_sclass_func); 4144 D.setInvalidType(); 4145 break; 4146 case DeclSpec::SCS_unspecified: SC = SC_None; break; 4147 case DeclSpec::SCS_extern: SC = SC_Extern; break; 4148 case DeclSpec::SCS_static: { 4149 if (CurContext->getRedeclContext()->isFunctionOrMethod()) { 4150 // C99 6.7.1p5: 4151 // The declaration of an identifier for a function that has 4152 // block scope shall have no explicit storage-class specifier 4153 // other than extern 4154 // See also (C++ [dcl.stc]p4). 4155 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4156 diag::err_static_block_func); 4157 SC = SC_None; 4158 } else 4159 SC = SC_Static; 4160 break; 4161 } 4162 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break; 4163 } 4164 4165 if (D.getDeclSpec().isThreadSpecified()) 4166 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4167 4168 // Do not allow returning a objc interface by-value. 4169 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 4170 Diag(D.getIdentifierLoc(), 4171 diag::err_object_cannot_be_passed_returned_by_value) << 0 4172 << R->getAs<FunctionType>()->getResultType(); 4173 D.setInvalidType(); 4174 } 4175 4176 FunctionDecl *NewFD; 4177 bool isInline = D.getDeclSpec().isInlineSpecified(); 4178 bool isFriend = false; 4179 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4180 FunctionDecl::StorageClass SCAsWritten 4181 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 4182 FunctionTemplateDecl *FunctionTemplate = 0; 4183 bool isExplicitSpecialization = false; 4184 bool isFunctionTemplateSpecialization = false; 4185 4186 if (!getLangOptions().CPlusPlus) { 4187 // Determine whether the function was written with a 4188 // prototype. This true when: 4189 // - there is a prototype in the declarator, or 4190 // - the type R of the function is some kind of typedef or other reference 4191 // to a type name (which eventually refers to a function type). 4192 bool HasPrototype = 4193 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 4194 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 4195 4196 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4197 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 4198 HasPrototype); 4199 if (D.isInvalidType()) 4200 NewFD->setInvalidDecl(); 4201 4202 // Set the lexical context. 4203 NewFD->setLexicalDeclContext(CurContext); 4204 // Filter out previous declarations that don't match the scope. 4205 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 4206 /*ExplicitInstantiationOrSpecialization=*/false); 4207 } else { 4208 isFriend = D.getDeclSpec().isFriendSpecified(); 4209 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4210 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 4211 bool isVirtualOkay = false; 4212 4213 // Check that the return type is not an abstract class type. 4214 // For record types, this is done by the AbstractClassUsageDiagnoser once 4215 // the class has been completely parsed. 4216 if (!DC->isRecord() && 4217 RequireNonAbstractType(D.getIdentifierLoc(), 4218 R->getAs<FunctionType>()->getResultType(), 4219 diag::err_abstract_type_in_decl, 4220 AbstractReturnType)) 4221 D.setInvalidType(); 4222 4223 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 4224 // This is a C++ constructor declaration. 4225 assert(DC->isRecord() && 4226 "Constructors can only be declared in a member context"); 4227 4228 R = CheckConstructorDeclarator(D, R, SC); 4229 4230 // Create the new declaration 4231 CXXConstructorDecl *NewCD = CXXConstructorDecl::Create( 4232 Context, 4233 cast<CXXRecordDecl>(DC), 4234 D.getSourceRange().getBegin(), 4235 NameInfo, R, TInfo, 4236 isExplicit, isInline, 4237 /*isImplicitlyDeclared=*/false); 4238 4239 NewFD = NewCD; 4240 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4241 // This is a C++ destructor declaration. 4242 if (DC->isRecord()) { 4243 R = CheckDestructorDeclarator(D, R, SC); 4244 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 4245 4246 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(Context, Record, 4247 D.getSourceRange().getBegin(), 4248 NameInfo, R, TInfo, 4249 isInline, 4250 /*isImplicitlyDeclared=*/false); 4251 NewFD = NewDD; 4252 isVirtualOkay = true; 4253 4254 // If the class is complete, then we now create the implicit exception 4255 // specification. If the class is incomplete or dependent, we can't do 4256 // it yet. 4257 if (getLangOptions().CPlusPlus0x && !Record->isDependentType() && 4258 Record->getDefinition() && !Record->isBeingDefined() && 4259 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 4260 AdjustDestructorExceptionSpec(Record, NewDD); 4261 } 4262 4263 } else { 4264 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 4265 4266 // Create a FunctionDecl to satisfy the function definition parsing 4267 // code path. 4268 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4269 D.getIdentifierLoc(), Name, R, TInfo, 4270 SC, SCAsWritten, isInline, 4271 /*hasPrototype=*/true); 4272 D.setInvalidType(); 4273 } 4274 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 4275 if (!DC->isRecord()) { 4276 Diag(D.getIdentifierLoc(), 4277 diag::err_conv_function_not_member); 4278 return 0; 4279 } 4280 4281 CheckConversionDeclarator(D, R, SC); 4282 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 4283 D.getSourceRange().getBegin(), 4284 NameInfo, R, TInfo, 4285 isInline, isExplicit, 4286 SourceLocation()); 4287 4288 isVirtualOkay = true; 4289 } else if (DC->isRecord()) { 4290 // If the of the function is the same as the name of the record, then this 4291 // must be an invalid constructor that has a return type. 4292 // (The parser checks for a return type and makes the declarator a 4293 // constructor if it has no return type). 4294 // must have an invalid constructor that has a return type 4295 if (Name.getAsIdentifierInfo() && 4296 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 4297 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 4298 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 4299 << SourceRange(D.getIdentifierLoc()); 4300 return 0; 4301 } 4302 4303 bool isStatic = SC == SC_Static; 4304 4305 // [class.free]p1: 4306 // Any allocation function for a class T is a static member 4307 // (even if not explicitly declared static). 4308 if (Name.getCXXOverloadedOperator() == OO_New || 4309 Name.getCXXOverloadedOperator() == OO_Array_New) 4310 isStatic = true; 4311 4312 // [class.free]p6 Any deallocation function for a class X is a static member 4313 // (even if not explicitly declared static). 4314 if (Name.getCXXOverloadedOperator() == OO_Delete || 4315 Name.getCXXOverloadedOperator() == OO_Array_Delete) 4316 isStatic = true; 4317 4318 // This is a C++ method declaration. 4319 CXXMethodDecl *NewMD = CXXMethodDecl::Create( 4320 Context, cast<CXXRecordDecl>(DC), 4321 D.getSourceRange().getBegin(), 4322 NameInfo, R, TInfo, 4323 isStatic, SCAsWritten, isInline, 4324 SourceLocation()); 4325 NewFD = NewMD; 4326 4327 isVirtualOkay = !isStatic; 4328 } else { 4329 // Determine whether the function was written with a 4330 // prototype. This true when: 4331 // - we're in C++ (where every function has a prototype), 4332 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4333 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 4334 true/*HasPrototype*/); 4335 } 4336 4337 if (isFriend && !isInline && IsFunctionDefinition) { 4338 // C++ [class.friend]p5 4339 // A function can be defined in a friend declaration of a 4340 // class . . . . Such a function is implicitly inline. 4341 NewFD->setImplicitlyInline(); 4342 } 4343 4344 SetNestedNameSpecifier(NewFD, D); 4345 isExplicitSpecialization = false; 4346 isFunctionTemplateSpecialization = false; 4347 if (D.isInvalidType()) 4348 NewFD->setInvalidDecl(); 4349 4350 // Set the lexical context. If the declarator has a C++ 4351 // scope specifier, or is the object of a friend declaration, the 4352 // lexical context will be different from the semantic context. 4353 NewFD->setLexicalDeclContext(CurContext); 4354 4355 // Match up the template parameter lists with the scope specifier, then 4356 // determine whether we have a template or a template specialization. 4357 bool Invalid = false; 4358 if (TemplateParameterList *TemplateParams 4359 = MatchTemplateParametersToScopeSpecifier( 4360 D.getDeclSpec().getSourceRange().getBegin(), 4361 D.getIdentifierLoc(), 4362 D.getCXXScopeSpec(), 4363 TemplateParamLists.get(), 4364 TemplateParamLists.size(), 4365 isFriend, 4366 isExplicitSpecialization, 4367 Invalid)) { 4368 if (TemplateParams->size() > 0) { 4369 // This is a function template 4370 4371 // Check that we can declare a template here. 4372 if (CheckTemplateDeclScope(S, TemplateParams)) 4373 return 0; 4374 4375 // A destructor cannot be a template. 4376 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4377 Diag(NewFD->getLocation(), diag::err_destructor_template); 4378 return 0; 4379 } 4380 4381 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 4382 NewFD->getLocation(), 4383 Name, TemplateParams, 4384 NewFD); 4385 FunctionTemplate->setLexicalDeclContext(CurContext); 4386 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 4387 4388 // For source fidelity, store the other template param lists. 4389 if (TemplateParamLists.size() > 1) { 4390 NewFD->setTemplateParameterListsInfo(Context, 4391 TemplateParamLists.size() - 1, 4392 TemplateParamLists.release()); 4393 } 4394 } else { 4395 // This is a function template specialization. 4396 isFunctionTemplateSpecialization = true; 4397 // For source fidelity, store all the template param lists. 4398 NewFD->setTemplateParameterListsInfo(Context, 4399 TemplateParamLists.size(), 4400 TemplateParamLists.release()); 4401 4402 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 4403 if (isFriend) { 4404 // We want to remove the "template<>", found here. 4405 SourceRange RemoveRange = TemplateParams->getSourceRange(); 4406 4407 // If we remove the template<> and the name is not a 4408 // template-id, we're actually silently creating a problem: 4409 // the friend declaration will refer to an untemplated decl, 4410 // and clearly the user wants a template specialization. So 4411 // we need to insert '<>' after the name. 4412 SourceLocation InsertLoc; 4413 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 4414 InsertLoc = D.getName().getSourceRange().getEnd(); 4415 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 4416 } 4417 4418 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 4419 << Name << RemoveRange 4420 << FixItHint::CreateRemoval(RemoveRange) 4421 << FixItHint::CreateInsertion(InsertLoc, "<>"); 4422 } 4423 } 4424 } 4425 else { 4426 // All template param lists were matched against the scope specifier: 4427 // this is NOT (an explicit specialization of) a template. 4428 if (TemplateParamLists.size() > 0) 4429 // For source fidelity, store all the template param lists. 4430 NewFD->setTemplateParameterListsInfo(Context, 4431 TemplateParamLists.size(), 4432 TemplateParamLists.release()); 4433 } 4434 4435 if (Invalid) { 4436 NewFD->setInvalidDecl(); 4437 if (FunctionTemplate) 4438 FunctionTemplate->setInvalidDecl(); 4439 } 4440 4441 // C++ [dcl.fct.spec]p5: 4442 // The virtual specifier shall only be used in declarations of 4443 // nonstatic class member functions that appear within a 4444 // member-specification of a class declaration; see 10.3. 4445 // 4446 if (isVirtual && !NewFD->isInvalidDecl()) { 4447 if (!isVirtualOkay) { 4448 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4449 diag::err_virtual_non_function); 4450 } else if (!CurContext->isRecord()) { 4451 // 'virtual' was specified outside of the class. 4452 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4453 diag::err_virtual_out_of_class) 4454 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4455 } else if (NewFD->getDescribedFunctionTemplate()) { 4456 // C++ [temp.mem]p3: 4457 // A member function template shall not be virtual. 4458 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4459 diag::err_virtual_member_function_template) 4460 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4461 } else { 4462 // Okay: Add virtual to the method. 4463 NewFD->setVirtualAsWritten(true); 4464 } 4465 } 4466 4467 // C++ [dcl.fct.spec]p3: 4468 // The inline specifier shall not appear on a block scope function declaration. 4469 if (isInline && !NewFD->isInvalidDecl()) { 4470 if (CurContext->isFunctionOrMethod()) { 4471 // 'inline' is not allowed on block scope function declaration. 4472 Diag(D.getDeclSpec().getInlineSpecLoc(), 4473 diag::err_inline_declaration_block_scope) << Name 4474 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 4475 } 4476 } 4477 4478 // C++ [dcl.fct.spec]p6: 4479 // The explicit specifier shall be used only in the declaration of a 4480 // constructor or conversion function within its class definition; see 12.3.1 4481 // and 12.3.2. 4482 if (isExplicit && !NewFD->isInvalidDecl()) { 4483 if (!CurContext->isRecord()) { 4484 // 'explicit' was specified outside of the class. 4485 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4486 diag::err_explicit_out_of_class) 4487 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4488 } else if (!isa<CXXConstructorDecl>(NewFD) && 4489 !isa<CXXConversionDecl>(NewFD)) { 4490 // 'explicit' was specified on a function that wasn't a constructor 4491 // or conversion function. 4492 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4493 diag::err_explicit_non_ctor_or_conv_function) 4494 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4495 } 4496 } 4497 4498 // Filter out previous declarations that don't match the scope. 4499 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 4500 isExplicitSpecialization || 4501 isFunctionTemplateSpecialization); 4502 4503 if (isFriend) { 4504 // For now, claim that the objects have no previous declaration. 4505 if (FunctionTemplate) { 4506 FunctionTemplate->setObjectOfFriendDecl(false); 4507 FunctionTemplate->setAccess(AS_public); 4508 } 4509 NewFD->setObjectOfFriendDecl(false); 4510 NewFD->setAccess(AS_public); 4511 } 4512 4513 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) { 4514 // A method is implicitly inline if it's defined in its class 4515 // definition. 4516 NewFD->setImplicitlyInline(); 4517 } 4518 4519 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 4520 !CurContext->isRecord()) { 4521 // C++ [class.static]p1: 4522 // A data or function member of a class may be declared static 4523 // in a class definition, in which case it is a static member of 4524 // the class. 4525 4526 // Complain about the 'static' specifier if it's on an out-of-line 4527 // member function definition. 4528 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4529 diag::err_static_out_of_line) 4530 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4531 } 4532 } 4533 4534 // Handle GNU asm-label extension (encoded as an attribute). 4535 if (Expr *E = (Expr*) D.getAsmLabel()) { 4536 // The parser guarantees this is a string. 4537 StringLiteral *SE = cast<StringLiteral>(E); 4538 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 4539 SE->getString())); 4540 } 4541 4542 // Copy the parameter declarations from the declarator D to the function 4543 // declaration NewFD, if they are available. First scavenge them into Params. 4544 llvm::SmallVector<ParmVarDecl*, 16> Params; 4545 if (D.isFunctionDeclarator()) { 4546 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4547 4548 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 4549 // function that takes no arguments, not a function that takes a 4550 // single void argument. 4551 // We let through "const void" here because Sema::GetTypeForDeclarator 4552 // already checks for that case. 4553 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 4554 FTI.ArgInfo[0].Param && 4555 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 4556 // Empty arg list, don't push any params. 4557 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param); 4558 4559 // In C++, the empty parameter-type-list must be spelled "void"; a 4560 // typedef of void is not permitted. 4561 if (getLangOptions().CPlusPlus && 4562 Param->getType().getUnqualifiedType() != Context.VoidTy) { 4563 bool IsTypeAlias = false; 4564 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 4565 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 4566 else if (const TemplateSpecializationType *TST = 4567 Param->getType()->getAs<TemplateSpecializationType>()) 4568 IsTypeAlias = TST->isTypeAlias(); 4569 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 4570 << IsTypeAlias; 4571 } 4572 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 4573 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 4574 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 4575 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 4576 Param->setDeclContext(NewFD); 4577 Params.push_back(Param); 4578 4579 if (Param->isInvalidDecl()) 4580 NewFD->setInvalidDecl(); 4581 } 4582 } 4583 4584 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 4585 // When we're declaring a function with a typedef, typeof, etc as in the 4586 // following example, we'll need to synthesize (unnamed) 4587 // parameters for use in the declaration. 4588 // 4589 // @code 4590 // typedef void fn(int); 4591 // fn f; 4592 // @endcode 4593 4594 // Synthesize a parameter for each argument type. 4595 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 4596 AE = FT->arg_type_end(); AI != AE; ++AI) { 4597 ParmVarDecl *Param = 4598 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 4599 Param->setScopeInfo(0, Params.size()); 4600 Params.push_back(Param); 4601 } 4602 } else { 4603 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 4604 "Should not need args for typedef of non-prototype fn"); 4605 } 4606 // Finally, we know we have the right number of parameters, install them. 4607 NewFD->setParams(Params.data(), Params.size()); 4608 4609 // Process the non-inheritable attributes on this declaration. 4610 ProcessDeclAttributes(S, NewFD, D, 4611 /*NonInheritable=*/true, /*Inheritable=*/false); 4612 4613 if (!getLangOptions().CPlusPlus) { 4614 // Perform semantic checking on the function declaration. 4615 bool isExplicitSpecialization=false; 4616 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 4617 Redeclaration); 4618 assert((NewFD->isInvalidDecl() || !Redeclaration || 4619 Previous.getResultKind() != LookupResult::FoundOverloaded) && 4620 "previous declaration set still overloaded"); 4621 } else { 4622 // If the declarator is a template-id, translate the parser's template 4623 // argument list into our AST format. 4624 bool HasExplicitTemplateArgs = false; 4625 TemplateArgumentListInfo TemplateArgs; 4626 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 4627 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 4628 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 4629 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 4630 ASTTemplateArgsPtr TemplateArgsPtr(*this, 4631 TemplateId->getTemplateArgs(), 4632 TemplateId->NumArgs); 4633 translateTemplateArguments(TemplateArgsPtr, 4634 TemplateArgs); 4635 TemplateArgsPtr.release(); 4636 4637 HasExplicitTemplateArgs = true; 4638 4639 if (NewFD->isInvalidDecl()) { 4640 HasExplicitTemplateArgs = false; 4641 } else if (FunctionTemplate) { 4642 // Function template with explicit template arguments. 4643 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 4644 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 4645 4646 HasExplicitTemplateArgs = false; 4647 } else if (!isFunctionTemplateSpecialization && 4648 !D.getDeclSpec().isFriendSpecified()) { 4649 // We have encountered something that the user meant to be a 4650 // specialization (because it has explicitly-specified template 4651 // arguments) but that was not introduced with a "template<>" (or had 4652 // too few of them). 4653 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 4654 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 4655 << FixItHint::CreateInsertion( 4656 D.getDeclSpec().getSourceRange().getBegin(), 4657 "template<> "); 4658 isFunctionTemplateSpecialization = true; 4659 } else { 4660 // "friend void foo<>(int);" is an implicit specialization decl. 4661 isFunctionTemplateSpecialization = true; 4662 } 4663 } else if (isFriend && isFunctionTemplateSpecialization) { 4664 // This combination is only possible in a recovery case; the user 4665 // wrote something like: 4666 // template <> friend void foo(int); 4667 // which we're recovering from as if the user had written: 4668 // friend void foo<>(int); 4669 // Go ahead and fake up a template id. 4670 HasExplicitTemplateArgs = true; 4671 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 4672 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 4673 } 4674 4675 // If it's a friend (and only if it's a friend), it's possible 4676 // that either the specialized function type or the specialized 4677 // template is dependent, and therefore matching will fail. In 4678 // this case, don't check the specialization yet. 4679 if (isFunctionTemplateSpecialization && isFriend && 4680 (NewFD->getType()->isDependentType() || DC->isDependentContext())) { 4681 assert(HasExplicitTemplateArgs && 4682 "friend function specialization without template args"); 4683 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 4684 Previous)) 4685 NewFD->setInvalidDecl(); 4686 } else if (isFunctionTemplateSpecialization) { 4687 if (CurContext->isDependentContext() && CurContext->isRecord() 4688 && !isFriend) { 4689 Diag(NewFD->getLocation(), diag::err_function_specialization_in_class) 4690 << NewFD->getDeclName(); 4691 NewFD->setInvalidDecl(); 4692 return 0; 4693 } else if (CheckFunctionTemplateSpecialization(NewFD, 4694 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 4695 Previous)) 4696 NewFD->setInvalidDecl(); 4697 4698 // C++ [dcl.stc]p1: 4699 // A storage-class-specifier shall not be specified in an explicit 4700 // specialization (14.7.3) 4701 if (SC != SC_None) { 4702 if (SC != NewFD->getStorageClass()) 4703 Diag(NewFD->getLocation(), 4704 diag::err_explicit_specialization_inconsistent_storage_class) 4705 << SC 4706 << FixItHint::CreateRemoval( 4707 D.getDeclSpec().getStorageClassSpecLoc()); 4708 4709 else 4710 Diag(NewFD->getLocation(), 4711 diag::ext_explicit_specialization_storage_class) 4712 << FixItHint::CreateRemoval( 4713 D.getDeclSpec().getStorageClassSpecLoc()); 4714 } 4715 4716 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 4717 if (CheckMemberSpecialization(NewFD, Previous)) 4718 NewFD->setInvalidDecl(); 4719 } 4720 4721 // Perform semantic checking on the function declaration. 4722 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 4723 Redeclaration); 4724 4725 assert((NewFD->isInvalidDecl() || !Redeclaration || 4726 Previous.getResultKind() != LookupResult::FoundOverloaded) && 4727 "previous declaration set still overloaded"); 4728 4729 NamedDecl *PrincipalDecl = (FunctionTemplate 4730 ? cast<NamedDecl>(FunctionTemplate) 4731 : NewFD); 4732 4733 if (isFriend && Redeclaration) { 4734 AccessSpecifier Access = AS_public; 4735 if (!NewFD->isInvalidDecl()) 4736 Access = NewFD->getPreviousDeclaration()->getAccess(); 4737 4738 NewFD->setAccess(Access); 4739 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 4740 4741 PrincipalDecl->setObjectOfFriendDecl(true); 4742 } 4743 4744 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 4745 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 4746 PrincipalDecl->setNonMemberOperator(); 4747 4748 // If we have a function template, check the template parameter 4749 // list. This will check and merge default template arguments. 4750 if (FunctionTemplate) { 4751 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration(); 4752 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 4753 PrevTemplate? PrevTemplate->getTemplateParameters() : 0, 4754 D.getDeclSpec().isFriendSpecified() 4755 ? (IsFunctionDefinition 4756 ? TPC_FriendFunctionTemplateDefinition 4757 : TPC_FriendFunctionTemplate) 4758 : (D.getCXXScopeSpec().isSet() && 4759 DC && DC->isRecord() && 4760 DC->isDependentContext()) 4761 ? TPC_ClassTemplateMember 4762 : TPC_FunctionTemplate); 4763 } 4764 4765 if (NewFD->isInvalidDecl()) { 4766 // Ignore all the rest of this. 4767 } else if (!Redeclaration) { 4768 // Fake up an access specifier if it's supposed to be a class member. 4769 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 4770 NewFD->setAccess(AS_public); 4771 4772 // Qualified decls generally require a previous declaration. 4773 if (D.getCXXScopeSpec().isSet()) { 4774 // ...with the major exception of templated-scope or 4775 // dependent-scope friend declarations. 4776 4777 // TODO: we currently also suppress this check in dependent 4778 // contexts because (1) the parameter depth will be off when 4779 // matching friend templates and (2) we might actually be 4780 // selecting a friend based on a dependent factor. But there 4781 // are situations where these conditions don't apply and we 4782 // can actually do this check immediately. 4783 if (isFriend && 4784 (TemplateParamLists.size() || 4785 D.getCXXScopeSpec().getScopeRep()->isDependent() || 4786 CurContext->isDependentContext())) { 4787 // ignore these 4788 } else { 4789 // The user tried to provide an out-of-line definition for a 4790 // function that is a member of a class or namespace, but there 4791 // was no such member function declared (C++ [class.mfct]p2, 4792 // C++ [namespace.memdef]p2). For example: 4793 // 4794 // class X { 4795 // void f() const; 4796 // }; 4797 // 4798 // void X::f() { } // ill-formed 4799 // 4800 // Complain about this problem, and attempt to suggest close 4801 // matches (e.g., those that differ only in cv-qualifiers and 4802 // whether the parameter types are references). 4803 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 4804 << Name << DC << D.getCXXScopeSpec().getRange(); 4805 NewFD->setInvalidDecl(); 4806 4807 DiagnoseInvalidRedeclaration(*this, NewFD); 4808 } 4809 4810 // Unqualified local friend declarations are required to resolve 4811 // to something. 4812 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 4813 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend); 4814 NewFD->setInvalidDecl(); 4815 DiagnoseInvalidRedeclaration(*this, NewFD); 4816 } 4817 4818 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && 4819 !isFriend && !isFunctionTemplateSpecialization && 4820 !isExplicitSpecialization) { 4821 // An out-of-line member function declaration must also be a 4822 // definition (C++ [dcl.meaning]p1). 4823 // Note that this is not the case for explicit specializations of 4824 // function templates or member functions of class templates, per 4825 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension 4826 // for compatibility with old SWIG code which likes to generate them. 4827 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 4828 << D.getCXXScopeSpec().getRange(); 4829 } 4830 } 4831 4832 4833 // Handle attributes. We need to have merged decls when handling attributes 4834 // (for example to check for conflicts, etc). 4835 // FIXME: This needs to happen before we merge declarations. Then, 4836 // let attribute merging cope with attribute conflicts. 4837 ProcessDeclAttributes(S, NewFD, D, 4838 /*NonInheritable=*/false, /*Inheritable=*/true); 4839 4840 // attributes declared post-definition are currently ignored 4841 // FIXME: This should happen during attribute merging 4842 if (Redeclaration && Previous.isSingleResult()) { 4843 const FunctionDecl *Def; 4844 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl()); 4845 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) { 4846 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 4847 Diag(Def->getLocation(), diag::note_previous_definition); 4848 } 4849 } 4850 4851 AddKnownFunctionAttributes(NewFD); 4852 4853 if (NewFD->hasAttr<OverloadableAttr>() && 4854 !NewFD->getType()->getAs<FunctionProtoType>()) { 4855 Diag(NewFD->getLocation(), 4856 diag::err_attribute_overloadable_no_prototype) 4857 << NewFD; 4858 4859 // Turn this into a variadic function with no parameters. 4860 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 4861 FunctionProtoType::ExtProtoInfo EPI; 4862 EPI.Variadic = true; 4863 EPI.ExtInfo = FT->getExtInfo(); 4864 4865 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 4866 NewFD->setType(R); 4867 } 4868 4869 // If there's a #pragma GCC visibility in scope, and this isn't a class 4870 // member, set the visibility of this function. 4871 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 4872 AddPushedVisibilityAttribute(NewFD); 4873 4874 // If this is a locally-scoped extern C function, update the 4875 // map of such names. 4876 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 4877 && !NewFD->isInvalidDecl()) 4878 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 4879 4880 // Set this FunctionDecl's range up to the right paren. 4881 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 4882 4883 if (getLangOptions().CPlusPlus) { 4884 if (FunctionTemplate) { 4885 if (NewFD->isInvalidDecl()) 4886 FunctionTemplate->setInvalidDecl(); 4887 return FunctionTemplate; 4888 } 4889 } 4890 4891 MarkUnusedFileScopedDecl(NewFD); 4892 4893 if (getLangOptions().CUDA) 4894 if (IdentifierInfo *II = NewFD->getIdentifier()) 4895 if (!NewFD->isInvalidDecl() && 4896 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4897 if (II->isStr("cudaConfigureCall")) { 4898 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 4899 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 4900 4901 Context.setcudaConfigureCallDecl(NewFD); 4902 } 4903 } 4904 4905 return NewFD; 4906 } 4907 4908 /// \brief Perform semantic checking of a new function declaration. 4909 /// 4910 /// Performs semantic analysis of the new function declaration 4911 /// NewFD. This routine performs all semantic checking that does not 4912 /// require the actual declarator involved in the declaration, and is 4913 /// used both for the declaration of functions as they are parsed 4914 /// (called via ActOnDeclarator) and for the declaration of functions 4915 /// that have been instantiated via C++ template instantiation (called 4916 /// via InstantiateDecl). 4917 /// 4918 /// \param IsExplicitSpecialiation whether this new function declaration is 4919 /// an explicit specialization of the previous declaration. 4920 /// 4921 /// This sets NewFD->isInvalidDecl() to true if there was an error. 4922 void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 4923 LookupResult &Previous, 4924 bool IsExplicitSpecialization, 4925 bool &Redeclaration) { 4926 // If NewFD is already known erroneous, don't do any of this checking. 4927 if (NewFD->isInvalidDecl()) { 4928 // If this is a class member, mark the class invalid immediately. 4929 // This avoids some consistency errors later. 4930 if (isa<CXXMethodDecl>(NewFD)) 4931 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl(); 4932 4933 return; 4934 } 4935 4936 if (NewFD->getResultType()->isVariablyModifiedType()) { 4937 // Functions returning a variably modified type violate C99 6.7.5.2p2 4938 // because all functions have linkage. 4939 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 4940 return NewFD->setInvalidDecl(); 4941 } 4942 4943 if (NewFD->isMain()) 4944 CheckMain(NewFD); 4945 4946 // Check for a previous declaration of this name. 4947 if (Previous.empty() && NewFD->isExternC()) { 4948 // Since we did not find anything by this name and we're declaring 4949 // an extern "C" function, look for a non-visible extern "C" 4950 // declaration with the same name. 4951 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4952 = LocallyScopedExternalDecls.find(NewFD->getDeclName()); 4953 if (Pos != LocallyScopedExternalDecls.end()) 4954 Previous.addDecl(Pos->second); 4955 } 4956 4957 // Merge or overload the declaration with an existing declaration of 4958 // the same name, if appropriate. 4959 if (!Previous.empty()) { 4960 // Determine whether NewFD is an overload of PrevDecl or 4961 // a declaration that requires merging. If it's an overload, 4962 // there's no more work to do here; we'll just add the new 4963 // function to the scope. 4964 4965 NamedDecl *OldDecl = 0; 4966 if (!AllowOverloadingOfFunction(Previous, Context)) { 4967 Redeclaration = true; 4968 OldDecl = Previous.getFoundDecl(); 4969 } else { 4970 switch (CheckOverload(S, NewFD, Previous, OldDecl, 4971 /*NewIsUsingDecl*/ false)) { 4972 case Ovl_Match: 4973 Redeclaration = true; 4974 break; 4975 4976 case Ovl_NonFunction: 4977 Redeclaration = true; 4978 break; 4979 4980 case Ovl_Overload: 4981 Redeclaration = false; 4982 break; 4983 } 4984 4985 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 4986 // If a function name is overloadable in C, then every function 4987 // with that name must be marked "overloadable". 4988 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 4989 << Redeclaration << NewFD; 4990 NamedDecl *OverloadedDecl = 0; 4991 if (Redeclaration) 4992 OverloadedDecl = OldDecl; 4993 else if (!Previous.empty()) 4994 OverloadedDecl = Previous.getRepresentativeDecl(); 4995 if (OverloadedDecl) 4996 Diag(OverloadedDecl->getLocation(), 4997 diag::note_attribute_overloadable_prev_overload); 4998 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 4999 Context)); 5000 } 5001 } 5002 5003 if (Redeclaration) { 5004 // NewFD and OldDecl represent declarations that need to be 5005 // merged. 5006 if (MergeFunctionDecl(NewFD, OldDecl)) 5007 return NewFD->setInvalidDecl(); 5008 5009 Previous.clear(); 5010 Previous.addDecl(OldDecl); 5011 5012 if (FunctionTemplateDecl *OldTemplateDecl 5013 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 5014 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 5015 FunctionTemplateDecl *NewTemplateDecl 5016 = NewFD->getDescribedFunctionTemplate(); 5017 assert(NewTemplateDecl && "Template/non-template mismatch"); 5018 if (CXXMethodDecl *Method 5019 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 5020 Method->setAccess(OldTemplateDecl->getAccess()); 5021 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 5022 } 5023 5024 // If this is an explicit specialization of a member that is a function 5025 // template, mark it as a member specialization. 5026 if (IsExplicitSpecialization && 5027 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 5028 NewTemplateDecl->setMemberSpecialization(); 5029 assert(OldTemplateDecl->isMemberSpecialization()); 5030 } 5031 } else { 5032 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 5033 NewFD->setAccess(OldDecl->getAccess()); 5034 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 5035 } 5036 } 5037 } 5038 5039 // Semantic checking for this function declaration (in isolation). 5040 if (getLangOptions().CPlusPlus) { 5041 // C++-specific checks. 5042 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 5043 CheckConstructor(Constructor); 5044 } else if (CXXDestructorDecl *Destructor = 5045 dyn_cast<CXXDestructorDecl>(NewFD)) { 5046 CXXRecordDecl *Record = Destructor->getParent(); 5047 QualType ClassType = Context.getTypeDeclType(Record); 5048 5049 // FIXME: Shouldn't we be able to perform this check even when the class 5050 // type is dependent? Both gcc and edg can handle that. 5051 if (!ClassType->isDependentType()) { 5052 DeclarationName Name 5053 = Context.DeclarationNames.getCXXDestructorName( 5054 Context.getCanonicalType(ClassType)); 5055 if (NewFD->getDeclName() != Name) { 5056 Diag(NewFD->getLocation(), diag::err_destructor_name); 5057 return NewFD->setInvalidDecl(); 5058 } 5059 } 5060 } else if (CXXConversionDecl *Conversion 5061 = dyn_cast<CXXConversionDecl>(NewFD)) { 5062 ActOnConversionDeclarator(Conversion); 5063 } 5064 5065 // Find any virtual functions that this function overrides. 5066 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 5067 if (!Method->isFunctionTemplateSpecialization() && 5068 !Method->getDescribedFunctionTemplate()) { 5069 if (AddOverriddenMethods(Method->getParent(), Method)) { 5070 // If the function was marked as "static", we have a problem. 5071 if (NewFD->getStorageClass() == SC_Static) { 5072 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual) 5073 << NewFD->getDeclName(); 5074 for (CXXMethodDecl::method_iterator 5075 Overridden = Method->begin_overridden_methods(), 5076 OverriddenEnd = Method->end_overridden_methods(); 5077 Overridden != OverriddenEnd; 5078 ++Overridden) { 5079 Diag((*Overridden)->getLocation(), 5080 diag::note_overridden_virtual_function); 5081 } 5082 } 5083 } 5084 } 5085 } 5086 5087 // Extra checking for C++ overloaded operators (C++ [over.oper]). 5088 if (NewFD->isOverloadedOperator() && 5089 CheckOverloadedOperatorDeclaration(NewFD)) 5090 return NewFD->setInvalidDecl(); 5091 5092 // Extra checking for C++0x literal operators (C++0x [over.literal]). 5093 if (NewFD->getLiteralIdentifier() && 5094 CheckLiteralOperatorDeclaration(NewFD)) 5095 return NewFD->setInvalidDecl(); 5096 5097 // In C++, check default arguments now that we have merged decls. Unless 5098 // the lexical context is the class, because in this case this is done 5099 // during delayed parsing anyway. 5100 if (!CurContext->isRecord()) 5101 CheckCXXDefaultArguments(NewFD); 5102 5103 // If this function declares a builtin function, check the type of this 5104 // declaration against the expected type for the builtin. 5105 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 5106 ASTContext::GetBuiltinTypeError Error; 5107 QualType T = Context.GetBuiltinType(BuiltinID, Error); 5108 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 5109 // The type of this function differs from the type of the builtin, 5110 // so forget about the builtin entirely. 5111 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 5112 } 5113 } 5114 } 5115 } 5116 5117 void Sema::CheckMain(FunctionDecl* FD) { 5118 // C++ [basic.start.main]p3: A program that declares main to be inline 5119 // or static is ill-formed. 5120 // C99 6.7.4p4: In a hosted environment, the inline function specifier 5121 // shall not appear in a declaration of main. 5122 // static main is not an error under C99, but we should warn about it. 5123 bool isInline = FD->isInlineSpecified(); 5124 bool isStatic = FD->getStorageClass() == SC_Static; 5125 if (isInline || isStatic) { 5126 unsigned diagID = diag::warn_unusual_main_decl; 5127 if (isInline || getLangOptions().CPlusPlus) 5128 diagID = diag::err_unusual_main_decl; 5129 5130 int which = isStatic + (isInline << 1) - 1; 5131 Diag(FD->getLocation(), diagID) << which; 5132 } 5133 5134 QualType T = FD->getType(); 5135 assert(T->isFunctionType() && "function decl is not of function type"); 5136 const FunctionType* FT = T->getAs<FunctionType>(); 5137 5138 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 5139 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 5140 FD->setInvalidDecl(true); 5141 } 5142 5143 // Treat protoless main() as nullary. 5144 if (isa<FunctionNoProtoType>(FT)) return; 5145 5146 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 5147 unsigned nparams = FTP->getNumArgs(); 5148 assert(FD->getNumParams() == nparams); 5149 5150 bool HasExtraParameters = (nparams > 3); 5151 5152 // Darwin passes an undocumented fourth argument of type char**. If 5153 // other platforms start sprouting these, the logic below will start 5154 // getting shifty. 5155 if (nparams == 4 && Context.Target.getTriple().isOSDarwin()) 5156 HasExtraParameters = false; 5157 5158 if (HasExtraParameters) { 5159 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 5160 FD->setInvalidDecl(true); 5161 nparams = 3; 5162 } 5163 5164 // FIXME: a lot of the following diagnostics would be improved 5165 // if we had some location information about types. 5166 5167 QualType CharPP = 5168 Context.getPointerType(Context.getPointerType(Context.CharTy)); 5169 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 5170 5171 for (unsigned i = 0; i < nparams; ++i) { 5172 QualType AT = FTP->getArgType(i); 5173 5174 bool mismatch = true; 5175 5176 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 5177 mismatch = false; 5178 else if (Expected[i] == CharPP) { 5179 // As an extension, the following forms are okay: 5180 // char const ** 5181 // char const * const * 5182 // char * const * 5183 5184 QualifierCollector qs; 5185 const PointerType* PT; 5186 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 5187 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 5188 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 5189 qs.removeConst(); 5190 mismatch = !qs.empty(); 5191 } 5192 } 5193 5194 if (mismatch) { 5195 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 5196 // TODO: suggest replacing given type with expected type 5197 FD->setInvalidDecl(true); 5198 } 5199 } 5200 5201 if (nparams == 1 && !FD->isInvalidDecl()) { 5202 Diag(FD->getLocation(), diag::warn_main_one_arg); 5203 } 5204 5205 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 5206 Diag(FD->getLocation(), diag::err_main_template_decl); 5207 FD->setInvalidDecl(); 5208 } 5209 } 5210 5211 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 5212 // FIXME: Need strict checking. In C89, we need to check for 5213 // any assignment, increment, decrement, function-calls, or 5214 // commas outside of a sizeof. In C99, it's the same list, 5215 // except that the aforementioned are allowed in unevaluated 5216 // expressions. Everything else falls under the 5217 // "may accept other forms of constant expressions" exception. 5218 // (We never end up here for C++, so the constant expression 5219 // rules there don't matter.) 5220 if (Init->isConstantInitializer(Context, false)) 5221 return false; 5222 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 5223 << Init->getSourceRange(); 5224 return true; 5225 } 5226 5227 namespace { 5228 // Visits an initialization expression to see if OrigDecl is evaluated in 5229 // its own initialization and throws a warning if it does. 5230 class SelfReferenceChecker 5231 : public EvaluatedExprVisitor<SelfReferenceChecker> { 5232 Sema &S; 5233 Decl *OrigDecl; 5234 5235 public: 5236 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 5237 5238 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 5239 S(S), OrigDecl(OrigDecl) { } 5240 5241 void VisitExpr(Expr *E) { 5242 if (isa<ObjCMessageExpr>(*E)) return; 5243 Inherited::VisitExpr(E); 5244 } 5245 5246 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 5247 CheckForSelfReference(E); 5248 Inherited::VisitImplicitCastExpr(E); 5249 } 5250 5251 void CheckForSelfReference(ImplicitCastExpr *E) { 5252 if (E->getCastKind() != CK_LValueToRValue) return; 5253 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts(); 5254 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr); 5255 if (!DRE) return; 5256 Decl* ReferenceDecl = DRE->getDecl(); 5257 if (OrigDecl != ReferenceDecl) return; 5258 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName, 5259 Sema::NotForRedeclaration); 5260 S.DiagRuntimeBehavior(SubExpr->getLocStart(), SubExpr, 5261 S.PDiag(diag::warn_uninit_self_reference_in_init) 5262 << Result.getLookupName() 5263 << OrigDecl->getLocation() 5264 << SubExpr->getSourceRange()); 5265 } 5266 }; 5267 } 5268 5269 /// AddInitializerToDecl - Adds the initializer Init to the 5270 /// declaration dcl. If DirectInit is true, this is C++ direct 5271 /// initialization rather than copy initialization. 5272 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 5273 bool DirectInit, bool TypeMayContainAuto) { 5274 // If there is no declaration, there was an error parsing it. Just ignore 5275 // the initializer. 5276 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 5277 return; 5278 5279 // Check for self-references within variable initializers. 5280 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) { 5281 // Variables declared within a function/method body are handled 5282 // by a dataflow analysis. 5283 if (!vd->hasLocalStorage() && !vd->isStaticLocal()) 5284 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init); 5285 } 5286 else { 5287 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init); 5288 } 5289 5290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 5291 // With declarators parsed the way they are, the parser cannot 5292 // distinguish between a normal initializer and a pure-specifier. 5293 // Thus this grotesque test. 5294 IntegerLiteral *IL; 5295 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 5296 Context.getCanonicalType(IL->getType()) == Context.IntTy) 5297 CheckPureMethod(Method, Init->getSourceRange()); 5298 else { 5299 Diag(Method->getLocation(), diag::err_member_function_initialization) 5300 << Method->getDeclName() << Init->getSourceRange(); 5301 Method->setInvalidDecl(); 5302 } 5303 return; 5304 } 5305 5306 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 5307 if (!VDecl) { 5308 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 5309 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 5310 RealDecl->setInvalidDecl(); 5311 return; 5312 } 5313 5314 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 5315 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 5316 TypeSourceInfo *DeducedType = 0; 5317 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 5318 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 5319 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 5320 << Init->getSourceRange(); 5321 if (!DeducedType) { 5322 RealDecl->setInvalidDecl(); 5323 return; 5324 } 5325 VDecl->setTypeSourceInfo(DeducedType); 5326 VDecl->setType(DeducedType->getType()); 5327 5328 // In ARC, infer lifetime. 5329 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 5330 VDecl->setInvalidDecl(); 5331 5332 // If this is a redeclaration, check that the type we just deduced matches 5333 // the previously declared type. 5334 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 5335 MergeVarDeclTypes(VDecl, Old); 5336 } 5337 5338 5339 // A definition must end up with a complete type, which means it must be 5340 // complete with the restriction that an array type might be completed by the 5341 // initializer; note that later code assumes this restriction. 5342 QualType BaseDeclType = VDecl->getType(); 5343 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 5344 BaseDeclType = Array->getElementType(); 5345 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 5346 diag::err_typecheck_decl_incomplete_type)) { 5347 RealDecl->setInvalidDecl(); 5348 return; 5349 } 5350 5351 // The variable can not have an abstract class type. 5352 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 5353 diag::err_abstract_type_in_decl, 5354 AbstractVariableType)) 5355 VDecl->setInvalidDecl(); 5356 5357 const VarDecl *Def; 5358 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 5359 Diag(VDecl->getLocation(), diag::err_redefinition) 5360 << VDecl->getDeclName(); 5361 Diag(Def->getLocation(), diag::note_previous_definition); 5362 VDecl->setInvalidDecl(); 5363 return; 5364 } 5365 5366 const VarDecl* PrevInit = 0; 5367 if (getLangOptions().CPlusPlus) { 5368 // C++ [class.static.data]p4 5369 // If a static data member is of const integral or const 5370 // enumeration type, its declaration in the class definition can 5371 // specify a constant-initializer which shall be an integral 5372 // constant expression (5.19). In that case, the member can appear 5373 // in integral constant expressions. The member shall still be 5374 // defined in a namespace scope if it is used in the program and the 5375 // namespace scope definition shall not contain an initializer. 5376 // 5377 // We already performed a redefinition check above, but for static 5378 // data members we also need to check whether there was an in-class 5379 // declaration with an initializer. 5380 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 5381 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 5382 Diag(PrevInit->getLocation(), diag::note_previous_definition); 5383 return; 5384 } 5385 5386 if (VDecl->hasLocalStorage()) 5387 getCurFunction()->setHasBranchProtectedScope(); 5388 5389 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 5390 VDecl->setInvalidDecl(); 5391 return; 5392 } 5393 } 5394 5395 // Capture the variable that is being initialized and the style of 5396 // initialization. 5397 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 5398 5399 // FIXME: Poor source location information. 5400 InitializationKind Kind 5401 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(), 5402 Init->getLocStart(), 5403 Init->getLocEnd()) 5404 : InitializationKind::CreateCopy(VDecl->getLocation(), 5405 Init->getLocStart()); 5406 5407 // Get the decls type and save a reference for later, since 5408 // CheckInitializerTypes may change it. 5409 QualType DclT = VDecl->getType(), SavT = DclT; 5410 if (VDecl->isLocalVarDecl()) { 5411 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 5412 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 5413 VDecl->setInvalidDecl(); 5414 } else if (!VDecl->isInvalidDecl()) { 5415 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5416 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5417 MultiExprArg(*this, &Init, 1), 5418 &DclT); 5419 if (Result.isInvalid()) { 5420 VDecl->setInvalidDecl(); 5421 return; 5422 } 5423 5424 Init = Result.takeAs<Expr>(); 5425 5426 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 5427 // Don't check invalid declarations to avoid emitting useless diagnostics. 5428 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 5429 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4. 5430 CheckForConstantInitializer(Init, DclT); 5431 } 5432 } 5433 } else if (VDecl->isStaticDataMember() && 5434 VDecl->getLexicalDeclContext()->isRecord()) { 5435 // This is an in-class initialization for a static data member, e.g., 5436 // 5437 // struct S { 5438 // static const int value = 17; 5439 // }; 5440 5441 // Try to perform the initialization regardless. 5442 if (!VDecl->isInvalidDecl()) { 5443 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5444 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5445 MultiExprArg(*this, &Init, 1), 5446 &DclT); 5447 if (Result.isInvalid()) { 5448 VDecl->setInvalidDecl(); 5449 return; 5450 } 5451 5452 Init = Result.takeAs<Expr>(); 5453 } 5454 5455 // C++ [class.mem]p4: 5456 // A member-declarator can contain a constant-initializer only 5457 // if it declares a static member (9.4) of const integral or 5458 // const enumeration type, see 9.4.2. 5459 QualType T = VDecl->getType(); 5460 5461 // Do nothing on dependent types. 5462 if (T->isDependentType()) { 5463 5464 // Require constness. 5465 } else if (!T.isConstQualified()) { 5466 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 5467 << Init->getSourceRange(); 5468 VDecl->setInvalidDecl(); 5469 5470 // We allow integer constant expressions in all cases. 5471 } else if (T->isIntegralOrEnumerationType()) { 5472 // Check whether the expression is a constant expression. 5473 SourceLocation Loc; 5474 if (Init->isValueDependent()) 5475 ; // Nothing to check. 5476 else if (Init->isIntegerConstantExpr(Context, &Loc)) 5477 ; // Ok, it's an ICE! 5478 else if (Init->isEvaluatable(Context)) { 5479 // If we can constant fold the initializer through heroics, accept it, 5480 // but report this as a use of an extension for -pedantic. 5481 Diag(Loc, diag::ext_in_class_initializer_non_constant) 5482 << Init->getSourceRange(); 5483 } else { 5484 // Otherwise, this is some crazy unknown case. Report the issue at the 5485 // location provided by the isIntegerConstantExpr failed check. 5486 Diag(Loc, diag::err_in_class_initializer_non_constant) 5487 << Init->getSourceRange(); 5488 VDecl->setInvalidDecl(); 5489 } 5490 5491 // We allow floating-point constants as an extension in C++03, and 5492 // C++0x has far more complicated rules that we don't really 5493 // implement fully. 5494 } else { 5495 bool Allowed = false; 5496 if (getLangOptions().CPlusPlus0x) { 5497 Allowed = T->isLiteralType(); 5498 } else if (T->isFloatingType()) { // also permits complex, which is ok 5499 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 5500 << T << Init->getSourceRange(); 5501 Allowed = true; 5502 } 5503 5504 if (!Allowed) { 5505 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 5506 << T << Init->getSourceRange(); 5507 VDecl->setInvalidDecl(); 5508 5509 // TODO: there are probably expressions that pass here that shouldn't. 5510 } else if (!Init->isValueDependent() && 5511 !Init->isConstantInitializer(Context, false)) { 5512 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 5513 << Init->getSourceRange(); 5514 VDecl->setInvalidDecl(); 5515 } 5516 } 5517 } else if (VDecl->isFileVarDecl()) { 5518 if (VDecl->getStorageClassAsWritten() == SC_Extern && 5519 (!getLangOptions().CPlusPlus || 5520 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 5521 Diag(VDecl->getLocation(), diag::warn_extern_init); 5522 if (!VDecl->isInvalidDecl()) { 5523 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5524 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5525 MultiExprArg(*this, &Init, 1), 5526 &DclT); 5527 if (Result.isInvalid()) { 5528 VDecl->setInvalidDecl(); 5529 return; 5530 } 5531 5532 Init = Result.takeAs<Expr>(); 5533 } 5534 5535 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 5536 // Don't check invalid declarations to avoid emitting useless diagnostics. 5537 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 5538 // C99 6.7.8p4. All file scoped initializers need to be constant. 5539 CheckForConstantInitializer(Init, DclT); 5540 } 5541 } 5542 // If the type changed, it means we had an incomplete type that was 5543 // completed by the initializer. For example: 5544 // int ary[] = { 1, 3, 5 }; 5545 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 5546 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 5547 VDecl->setType(DclT); 5548 Init->setType(DclT); 5549 } 5550 5551 5552 // If this variable is a local declaration with record type, make sure it 5553 // doesn't have a flexible member initialization. We only support this as a 5554 // global/static definition. 5555 if (VDecl->hasLocalStorage()) 5556 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>()) 5557 if (RT->getDecl()->hasFlexibleArrayMember()) { 5558 // Check whether the initializer tries to initialize the flexible 5559 // array member itself to anything other than an empty initializer list. 5560 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 5561 unsigned Index = std::distance(RT->getDecl()->field_begin(), 5562 RT->getDecl()->field_end()) - 1; 5563 if (Index < ILE->getNumInits() && 5564 !(isa<InitListExpr>(ILE->getInit(Index)) && 5565 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) { 5566 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable); 5567 VDecl->setInvalidDecl(); 5568 } 5569 } 5570 } 5571 5572 // Check any implicit conversions within the expression. 5573 CheckImplicitConversions(Init, VDecl->getLocation()); 5574 5575 if (!VDecl->isInvalidDecl()) 5576 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 5577 5578 Init = MaybeCreateExprWithCleanups(Init); 5579 // Attach the initializer to the decl. 5580 VDecl->setInit(Init); 5581 5582 CheckCompleteVariableDeclaration(VDecl); 5583 } 5584 5585 /// ActOnInitializerError - Given that there was an error parsing an 5586 /// initializer for the given declaration, try to return to some form 5587 /// of sanity. 5588 void Sema::ActOnInitializerError(Decl *D) { 5589 // Our main concern here is re-establishing invariants like "a 5590 // variable's type is either dependent or complete". 5591 if (!D || D->isInvalidDecl()) return; 5592 5593 VarDecl *VD = dyn_cast<VarDecl>(D); 5594 if (!VD) return; 5595 5596 // Auto types are meaningless if we can't make sense of the initializer. 5597 if (ParsingInitForAutoVars.count(D)) { 5598 D->setInvalidDecl(); 5599 return; 5600 } 5601 5602 QualType Ty = VD->getType(); 5603 if (Ty->isDependentType()) return; 5604 5605 // Require a complete type. 5606 if (RequireCompleteType(VD->getLocation(), 5607 Context.getBaseElementType(Ty), 5608 diag::err_typecheck_decl_incomplete_type)) { 5609 VD->setInvalidDecl(); 5610 return; 5611 } 5612 5613 // Require an abstract type. 5614 if (RequireNonAbstractType(VD->getLocation(), Ty, 5615 diag::err_abstract_type_in_decl, 5616 AbstractVariableType)) { 5617 VD->setInvalidDecl(); 5618 return; 5619 } 5620 5621 // Don't bother complaining about constructors or destructors, 5622 // though. 5623 } 5624 5625 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 5626 bool TypeMayContainAuto) { 5627 // If there is no declaration, there was an error parsing it. Just ignore it. 5628 if (RealDecl == 0) 5629 return; 5630 5631 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 5632 QualType Type = Var->getType(); 5633 5634 // C++0x [dcl.spec.auto]p3 5635 if (TypeMayContainAuto && Type->getContainedAutoType()) { 5636 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 5637 << Var->getDeclName() << Type; 5638 Var->setInvalidDecl(); 5639 return; 5640 } 5641 5642 switch (Var->isThisDeclarationADefinition()) { 5643 case VarDecl::Definition: 5644 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 5645 break; 5646 5647 // We have an out-of-line definition of a static data member 5648 // that has an in-class initializer, so we type-check this like 5649 // a declaration. 5650 // 5651 // Fall through 5652 5653 case VarDecl::DeclarationOnly: 5654 // It's only a declaration. 5655 5656 // Block scope. C99 6.7p7: If an identifier for an object is 5657 // declared with no linkage (C99 6.2.2p6), the type for the 5658 // object shall be complete. 5659 if (!Type->isDependentType() && Var->isLocalVarDecl() && 5660 !Var->getLinkage() && !Var->isInvalidDecl() && 5661 RequireCompleteType(Var->getLocation(), Type, 5662 diag::err_typecheck_decl_incomplete_type)) 5663 Var->setInvalidDecl(); 5664 5665 // Make sure that the type is not abstract. 5666 if (!Type->isDependentType() && !Var->isInvalidDecl() && 5667 RequireNonAbstractType(Var->getLocation(), Type, 5668 diag::err_abstract_type_in_decl, 5669 AbstractVariableType)) 5670 Var->setInvalidDecl(); 5671 return; 5672 5673 case VarDecl::TentativeDefinition: 5674 // File scope. C99 6.9.2p2: A declaration of an identifier for an 5675 // object that has file scope without an initializer, and without a 5676 // storage-class specifier or with the storage-class specifier "static", 5677 // constitutes a tentative definition. Note: A tentative definition with 5678 // external linkage is valid (C99 6.2.2p5). 5679 if (!Var->isInvalidDecl()) { 5680 if (const IncompleteArrayType *ArrayT 5681 = Context.getAsIncompleteArrayType(Type)) { 5682 if (RequireCompleteType(Var->getLocation(), 5683 ArrayT->getElementType(), 5684 diag::err_illegal_decl_array_incomplete_type)) 5685 Var->setInvalidDecl(); 5686 } else if (Var->getStorageClass() == SC_Static) { 5687 // C99 6.9.2p3: If the declaration of an identifier for an object is 5688 // a tentative definition and has internal linkage (C99 6.2.2p3), the 5689 // declared type shall not be an incomplete type. 5690 // NOTE: code such as the following 5691 // static struct s; 5692 // struct s { int a; }; 5693 // is accepted by gcc. Hence here we issue a warning instead of 5694 // an error and we do not invalidate the static declaration. 5695 // NOTE: to avoid multiple warnings, only check the first declaration. 5696 if (Var->getPreviousDeclaration() == 0) 5697 RequireCompleteType(Var->getLocation(), Type, 5698 diag::ext_typecheck_decl_incomplete_type); 5699 } 5700 } 5701 5702 // Record the tentative definition; we're done. 5703 if (!Var->isInvalidDecl()) 5704 TentativeDefinitions.push_back(Var); 5705 return; 5706 } 5707 5708 // Provide a specific diagnostic for uninitialized variable 5709 // definitions with incomplete array type. 5710 if (Type->isIncompleteArrayType()) { 5711 Diag(Var->getLocation(), 5712 diag::err_typecheck_incomplete_array_needs_initializer); 5713 Var->setInvalidDecl(); 5714 return; 5715 } 5716 5717 // Provide a specific diagnostic for uninitialized variable 5718 // definitions with reference type. 5719 if (Type->isReferenceType()) { 5720 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 5721 << Var->getDeclName() 5722 << SourceRange(Var->getLocation(), Var->getLocation()); 5723 Var->setInvalidDecl(); 5724 return; 5725 } 5726 5727 // Do not attempt to type-check the default initializer for a 5728 // variable with dependent type. 5729 if (Type->isDependentType()) 5730 return; 5731 5732 if (Var->isInvalidDecl()) 5733 return; 5734 5735 if (RequireCompleteType(Var->getLocation(), 5736 Context.getBaseElementType(Type), 5737 diag::err_typecheck_decl_incomplete_type)) { 5738 Var->setInvalidDecl(); 5739 return; 5740 } 5741 5742 // The variable can not have an abstract class type. 5743 if (RequireNonAbstractType(Var->getLocation(), Type, 5744 diag::err_abstract_type_in_decl, 5745 AbstractVariableType)) { 5746 Var->setInvalidDecl(); 5747 return; 5748 } 5749 5750 // Check for jumps past the implicit initializer. C++0x 5751 // clarifies that this applies to a "variable with automatic 5752 // storage duration", not a "local variable". 5753 // C++0x [stmt.dcl]p3 5754 // A program that jumps from a point where a variable with automatic 5755 // storage duration is not in scope to a point where it is in scope is 5756 // ill-formed unless the variable has scalar type, class type with a 5757 // trivial default constructor and a trivial destructor, a cv-qualified 5758 // version of one of these types, or an array of one of the preceding 5759 // types and is declared without an initializer. 5760 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) { 5761 if (const RecordType *Record 5762 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 5763 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 5764 if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) || 5765 (getLangOptions().CPlusPlus0x && 5766 (!CXXRecord->hasTrivialDefaultConstructor() || 5767 !CXXRecord->hasTrivialDestructor()))) 5768 getCurFunction()->setHasBranchProtectedScope(); 5769 } 5770 } 5771 5772 // C++03 [dcl.init]p9: 5773 // If no initializer is specified for an object, and the 5774 // object is of (possibly cv-qualified) non-POD class type (or 5775 // array thereof), the object shall be default-initialized; if 5776 // the object is of const-qualified type, the underlying class 5777 // type shall have a user-declared default 5778 // constructor. Otherwise, if no initializer is specified for 5779 // a non- static object, the object and its subobjects, if 5780 // any, have an indeterminate initial value); if the object 5781 // or any of its subobjects are of const-qualified type, the 5782 // program is ill-formed. 5783 // C++0x [dcl.init]p11: 5784 // If no initializer is specified for an object, the object is 5785 // default-initialized; [...]. 5786 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 5787 InitializationKind Kind 5788 = InitializationKind::CreateDefault(Var->getLocation()); 5789 5790 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 5791 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 5792 MultiExprArg(*this, 0, 0)); 5793 if (Init.isInvalid()) 5794 Var->setInvalidDecl(); 5795 else if (Init.get()) 5796 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 5797 5798 CheckCompleteVariableDeclaration(Var); 5799 } 5800 } 5801 5802 void Sema::ActOnCXXForRangeDecl(Decl *D) { 5803 VarDecl *VD = dyn_cast<VarDecl>(D); 5804 if (!VD) { 5805 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 5806 D->setInvalidDecl(); 5807 return; 5808 } 5809 5810 VD->setCXXForRangeDecl(true); 5811 5812 // for-range-declaration cannot be given a storage class specifier. 5813 int Error = -1; 5814 switch (VD->getStorageClassAsWritten()) { 5815 case SC_None: 5816 break; 5817 case SC_Extern: 5818 Error = 0; 5819 break; 5820 case SC_Static: 5821 Error = 1; 5822 break; 5823 case SC_PrivateExtern: 5824 Error = 2; 5825 break; 5826 case SC_Auto: 5827 Error = 3; 5828 break; 5829 case SC_Register: 5830 Error = 4; 5831 break; 5832 } 5833 // FIXME: constexpr isn't allowed here. 5834 //if (DS.isConstexprSpecified()) 5835 // Error = 5; 5836 if (Error != -1) { 5837 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 5838 << VD->getDeclName() << Error; 5839 D->setInvalidDecl(); 5840 } 5841 } 5842 5843 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 5844 if (var->isInvalidDecl()) return; 5845 5846 // In ARC, don't allow jumps past the implicit initialization of a 5847 // local retaining variable. 5848 if (getLangOptions().ObjCAutoRefCount && 5849 var->hasLocalStorage()) { 5850 switch (var->getType().getObjCLifetime()) { 5851 case Qualifiers::OCL_None: 5852 case Qualifiers::OCL_ExplicitNone: 5853 case Qualifiers::OCL_Autoreleasing: 5854 break; 5855 5856 case Qualifiers::OCL_Weak: 5857 case Qualifiers::OCL_Strong: 5858 getCurFunction()->setHasBranchProtectedScope(); 5859 break; 5860 } 5861 } 5862 5863 // All the following checks are C++ only. 5864 if (!getLangOptions().CPlusPlus) return; 5865 5866 QualType baseType = Context.getBaseElementType(var->getType()); 5867 if (baseType->isDependentType()) return; 5868 5869 // __block variables might require us to capture a copy-initializer. 5870 if (var->hasAttr<BlocksAttr>()) { 5871 // It's currently invalid to ever have a __block variable with an 5872 // array type; should we diagnose that here? 5873 5874 // Regardless, we don't want to ignore array nesting when 5875 // constructing this copy. 5876 QualType type = var->getType(); 5877 5878 if (type->isStructureOrClassType()) { 5879 SourceLocation poi = var->getLocation(); 5880 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi); 5881 ExprResult result = 5882 PerformCopyInitialization( 5883 InitializedEntity::InitializeBlock(poi, type, false), 5884 poi, Owned(varRef)); 5885 if (!result.isInvalid()) { 5886 result = MaybeCreateExprWithCleanups(result); 5887 Expr *init = result.takeAs<Expr>(); 5888 Context.setBlockVarCopyInits(var, init); 5889 } 5890 } 5891 } 5892 5893 // Check for global constructors. 5894 if (!var->getDeclContext()->isDependentContext() && 5895 var->hasGlobalStorage() && 5896 !var->isStaticLocal() && 5897 var->getInit() && 5898 !var->getInit()->isConstantInitializer(Context, 5899 baseType->isReferenceType())) 5900 Diag(var->getLocation(), diag::warn_global_constructor) 5901 << var->getInit()->getSourceRange(); 5902 5903 // Require the destructor. 5904 if (const RecordType *recordType = baseType->getAs<RecordType>()) 5905 FinalizeVarWithDestructor(var, recordType); 5906 } 5907 5908 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 5909 /// any semantic actions necessary after any initializer has been attached. 5910 void 5911 Sema::FinalizeDeclaration(Decl *ThisDecl) { 5912 // Note that we are no longer parsing the initializer for this declaration. 5913 ParsingInitForAutoVars.erase(ThisDecl); 5914 } 5915 5916 Sema::DeclGroupPtrTy 5917 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 5918 Decl **Group, unsigned NumDecls) { 5919 llvm::SmallVector<Decl*, 8> Decls; 5920 5921 if (DS.isTypeSpecOwned()) 5922 Decls.push_back(DS.getRepAsDecl()); 5923 5924 for (unsigned i = 0; i != NumDecls; ++i) 5925 if (Decl *D = Group[i]) 5926 Decls.push_back(D); 5927 5928 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 5929 DS.getTypeSpecType() == DeclSpec::TST_auto); 5930 } 5931 5932 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 5933 /// group, performing any necessary semantic checking. 5934 Sema::DeclGroupPtrTy 5935 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 5936 bool TypeMayContainAuto) { 5937 // C++0x [dcl.spec.auto]p7: 5938 // If the type deduced for the template parameter U is not the same in each 5939 // deduction, the program is ill-formed. 5940 // FIXME: When initializer-list support is added, a distinction is needed 5941 // between the deduced type U and the deduced type which 'auto' stands for. 5942 // auto a = 0, b = { 1, 2, 3 }; 5943 // is legal because the deduced type U is 'int' in both cases. 5944 if (TypeMayContainAuto && NumDecls > 1) { 5945 QualType Deduced; 5946 CanQualType DeducedCanon; 5947 VarDecl *DeducedDecl = 0; 5948 for (unsigned i = 0; i != NumDecls; ++i) { 5949 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 5950 AutoType *AT = D->getType()->getContainedAutoType(); 5951 // Don't reissue diagnostics when instantiating a template. 5952 if (AT && D->isInvalidDecl()) 5953 break; 5954 if (AT && AT->isDeduced()) { 5955 QualType U = AT->getDeducedType(); 5956 CanQualType UCanon = Context.getCanonicalType(U); 5957 if (Deduced.isNull()) { 5958 Deduced = U; 5959 DeducedCanon = UCanon; 5960 DeducedDecl = D; 5961 } else if (DeducedCanon != UCanon) { 5962 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 5963 diag::err_auto_different_deductions) 5964 << Deduced << DeducedDecl->getDeclName() 5965 << U << D->getDeclName() 5966 << DeducedDecl->getInit()->getSourceRange() 5967 << D->getInit()->getSourceRange(); 5968 D->setInvalidDecl(); 5969 break; 5970 } 5971 } 5972 } 5973 } 5974 } 5975 5976 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 5977 } 5978 5979 5980 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 5981 /// to introduce parameters into function prototype scope. 5982 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 5983 const DeclSpec &DS = D.getDeclSpec(); 5984 5985 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 5986 VarDecl::StorageClass StorageClass = SC_None; 5987 VarDecl::StorageClass StorageClassAsWritten = SC_None; 5988 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 5989 StorageClass = SC_Register; 5990 StorageClassAsWritten = SC_Register; 5991 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 5992 Diag(DS.getStorageClassSpecLoc(), 5993 diag::err_invalid_storage_class_in_func_decl); 5994 D.getMutableDeclSpec().ClearStorageClassSpecs(); 5995 } 5996 5997 if (D.getDeclSpec().isThreadSpecified()) 5998 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5999 6000 DiagnoseFunctionSpecifiers(D); 6001 6002 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6003 QualType parmDeclType = TInfo->getType(); 6004 6005 if (getLangOptions().CPlusPlus) { 6006 // Check that there are no default arguments inside the type of this 6007 // parameter. 6008 CheckExtraCXXDefaultArguments(D); 6009 6010 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 6011 if (D.getCXXScopeSpec().isSet()) { 6012 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 6013 << D.getCXXScopeSpec().getRange(); 6014 D.getCXXScopeSpec().clear(); 6015 } 6016 } 6017 6018 // Ensure we have a valid name 6019 IdentifierInfo *II = 0; 6020 if (D.hasName()) { 6021 II = D.getIdentifier(); 6022 if (!II) { 6023 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 6024 << GetNameForDeclarator(D).getName().getAsString(); 6025 D.setInvalidType(true); 6026 } 6027 } 6028 6029 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 6030 if (II) { 6031 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 6032 ForRedeclaration); 6033 LookupName(R, S); 6034 if (R.isSingleResult()) { 6035 NamedDecl *PrevDecl = R.getFoundDecl(); 6036 if (PrevDecl->isTemplateParameter()) { 6037 // Maybe we will complain about the shadowed template parameter. 6038 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6039 // Just pretend that we didn't see the previous declaration. 6040 PrevDecl = 0; 6041 } else if (S->isDeclScope(PrevDecl)) { 6042 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 6043 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6044 6045 // Recover by removing the name 6046 II = 0; 6047 D.SetIdentifier(0, D.getIdentifierLoc()); 6048 D.setInvalidType(true); 6049 } 6050 } 6051 } 6052 6053 // Temporarily put parameter variables in the translation unit, not 6054 // the enclosing context. This prevents them from accidentally 6055 // looking like class members in C++. 6056 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 6057 D.getSourceRange().getBegin(), 6058 D.getIdentifierLoc(), II, 6059 parmDeclType, TInfo, 6060 StorageClass, StorageClassAsWritten); 6061 6062 if (D.isInvalidType()) 6063 New->setInvalidDecl(); 6064 6065 assert(S->isFunctionPrototypeScope()); 6066 assert(S->getFunctionPrototypeDepth() >= 1); 6067 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 6068 S->getNextFunctionPrototypeIndex()); 6069 6070 // Add the parameter declaration into this scope. 6071 S->AddDecl(New); 6072 if (II) 6073 IdResolver.AddDecl(New); 6074 6075 ProcessDeclAttributes(S, New, D); 6076 6077 if (New->hasAttr<BlocksAttr>()) { 6078 Diag(New->getLocation(), diag::err_block_on_nonlocal); 6079 } 6080 return New; 6081 } 6082 6083 /// \brief Synthesizes a variable for a parameter arising from a 6084 /// typedef. 6085 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 6086 SourceLocation Loc, 6087 QualType T) { 6088 /* FIXME: setting StartLoc == Loc. 6089 Would it be worth to modify callers so as to provide proper source 6090 location for the unnamed parameters, embedding the parameter's type? */ 6091 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 6092 T, Context.getTrivialTypeSourceInfo(T, Loc), 6093 SC_None, SC_None, 0); 6094 Param->setImplicit(); 6095 return Param; 6096 } 6097 6098 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 6099 ParmVarDecl * const *ParamEnd) { 6100 // Don't diagnose unused-parameter errors in template instantiations; we 6101 // will already have done so in the template itself. 6102 if (!ActiveTemplateInstantiations.empty()) 6103 return; 6104 6105 for (; Param != ParamEnd; ++Param) { 6106 if (!(*Param)->isUsed() && (*Param)->getDeclName() && 6107 !(*Param)->hasAttr<UnusedAttr>()) { 6108 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 6109 << (*Param)->getDeclName(); 6110 } 6111 } 6112 } 6113 6114 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 6115 ParmVarDecl * const *ParamEnd, 6116 QualType ReturnTy, 6117 NamedDecl *D) { 6118 if (LangOpts.NumLargeByValueCopy == 0) // No check. 6119 return; 6120 6121 // Warn if the return value is pass-by-value and larger than the specified 6122 // threshold. 6123 if (ReturnTy.isPODType(Context)) { 6124 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 6125 if (Size > LangOpts.NumLargeByValueCopy) 6126 Diag(D->getLocation(), diag::warn_return_value_size) 6127 << D->getDeclName() << Size; 6128 } 6129 6130 // Warn if any parameter is pass-by-value and larger than the specified 6131 // threshold. 6132 for (; Param != ParamEnd; ++Param) { 6133 QualType T = (*Param)->getType(); 6134 if (!T.isPODType(Context)) 6135 continue; 6136 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 6137 if (Size > LangOpts.NumLargeByValueCopy) 6138 Diag((*Param)->getLocation(), diag::warn_parameter_size) 6139 << (*Param)->getDeclName() << Size; 6140 } 6141 } 6142 6143 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 6144 SourceLocation NameLoc, IdentifierInfo *Name, 6145 QualType T, TypeSourceInfo *TSInfo, 6146 VarDecl::StorageClass StorageClass, 6147 VarDecl::StorageClass StorageClassAsWritten) { 6148 // In ARC, infer a lifetime qualifier for appropriate parameter types. 6149 if (getLangOptions().ObjCAutoRefCount && 6150 T.getObjCLifetime() == Qualifiers::OCL_None && 6151 T->isObjCLifetimeType()) { 6152 6153 Qualifiers::ObjCLifetime lifetime; 6154 6155 // Special cases for arrays: 6156 // - if it's const, use __unsafe_unretained 6157 // - otherwise, it's an error 6158 if (T->isArrayType()) { 6159 if (!T.isConstQualified()) { 6160 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 6161 << TSInfo->getTypeLoc().getSourceRange(); 6162 } 6163 lifetime = Qualifiers::OCL_ExplicitNone; 6164 } else { 6165 lifetime = T->getObjCARCImplicitLifetime(); 6166 } 6167 T = Context.getLifetimeQualifiedType(T, lifetime); 6168 } 6169 6170 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 6171 Context.getAdjustedParameterType(T), 6172 TSInfo, 6173 StorageClass, StorageClassAsWritten, 6174 0); 6175 6176 // Parameters can not be abstract class types. 6177 // For record types, this is done by the AbstractClassUsageDiagnoser once 6178 // the class has been completely parsed. 6179 if (!CurContext->isRecord() && 6180 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 6181 AbstractParamType)) 6182 New->setInvalidDecl(); 6183 6184 // Parameter declarators cannot be interface types. All ObjC objects are 6185 // passed by reference. 6186 if (T->isObjCObjectType()) { 6187 Diag(NameLoc, 6188 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T; 6189 New->setInvalidDecl(); 6190 } 6191 6192 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 6193 // duration shall not be qualified by an address-space qualifier." 6194 // Since all parameters have automatic store duration, they can not have 6195 // an address space. 6196 if (T.getAddressSpace() != 0) { 6197 Diag(NameLoc, diag::err_arg_with_address_space); 6198 New->setInvalidDecl(); 6199 } 6200 6201 return New; 6202 } 6203 6204 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 6205 SourceLocation LocAfterDecls) { 6206 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6207 6208 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 6209 // for a K&R function. 6210 if (!FTI.hasPrototype) { 6211 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 6212 --i; 6213 if (FTI.ArgInfo[i].Param == 0) { 6214 llvm::SmallString<256> Code; 6215 llvm::raw_svector_ostream(Code) << " int " 6216 << FTI.ArgInfo[i].Ident->getName() 6217 << ";\n"; 6218 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 6219 << FTI.ArgInfo[i].Ident 6220 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 6221 6222 // Implicitly declare the argument as type 'int' for lack of a better 6223 // type. 6224 AttributeFactory attrs; 6225 DeclSpec DS(attrs); 6226 const char* PrevSpec; // unused 6227 unsigned DiagID; // unused 6228 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 6229 PrevSpec, DiagID); 6230 Declarator ParamD(DS, Declarator::KNRTypeListContext); 6231 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 6232 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 6233 } 6234 } 6235 } 6236 } 6237 6238 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 6239 Declarator &D) { 6240 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 6241 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 6242 Scope *ParentScope = FnBodyScope->getParent(); 6243 6244 Decl *DP = HandleDeclarator(ParentScope, D, 6245 MultiTemplateParamsArg(*this), 6246 /*IsFunctionDefinition=*/true); 6247 return ActOnStartOfFunctionDef(FnBodyScope, DP); 6248 } 6249 6250 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 6251 // Don't warn about invalid declarations. 6252 if (FD->isInvalidDecl()) 6253 return false; 6254 6255 // Or declarations that aren't global. 6256 if (!FD->isGlobal()) 6257 return false; 6258 6259 // Don't warn about C++ member functions. 6260 if (isa<CXXMethodDecl>(FD)) 6261 return false; 6262 6263 // Don't warn about 'main'. 6264 if (FD->isMain()) 6265 return false; 6266 6267 // Don't warn about inline functions. 6268 if (FD->isInlined()) 6269 return false; 6270 6271 // Don't warn about function templates. 6272 if (FD->getDescribedFunctionTemplate()) 6273 return false; 6274 6275 // Don't warn about function template specializations. 6276 if (FD->isFunctionTemplateSpecialization()) 6277 return false; 6278 6279 bool MissingPrototype = true; 6280 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 6281 Prev; Prev = Prev->getPreviousDeclaration()) { 6282 // Ignore any declarations that occur in function or method 6283 // scope, because they aren't visible from the header. 6284 if (Prev->getDeclContext()->isFunctionOrMethod()) 6285 continue; 6286 6287 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 6288 break; 6289 } 6290 6291 return MissingPrototype; 6292 } 6293 6294 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 6295 // Don't complain if we're in GNU89 mode and the previous definition 6296 // was an extern inline function. 6297 const FunctionDecl *Definition; 6298 if (FD->isDefined(Definition) && 6299 !canRedefineFunction(Definition, getLangOptions())) { 6300 if (getLangOptions().GNUMode && Definition->isInlineSpecified() && 6301 Definition->getStorageClass() == SC_Extern) 6302 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 6303 << FD->getDeclName() << getLangOptions().CPlusPlus; 6304 else 6305 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 6306 Diag(Definition->getLocation(), diag::note_previous_definition); 6307 } 6308 } 6309 6310 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 6311 // Clear the last template instantiation error context. 6312 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 6313 6314 if (!D) 6315 return D; 6316 FunctionDecl *FD = 0; 6317 6318 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 6319 FD = FunTmpl->getTemplatedDecl(); 6320 else 6321 FD = cast<FunctionDecl>(D); 6322 6323 // Enter a new function scope 6324 PushFunctionScope(); 6325 6326 // See if this is a redefinition. 6327 if (!FD->isLateTemplateParsed()) 6328 CheckForFunctionRedefinition(FD); 6329 6330 // Builtin functions cannot be defined. 6331 if (unsigned BuiltinID = FD->getBuiltinID()) { 6332 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 6333 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 6334 FD->setInvalidDecl(); 6335 } 6336 } 6337 6338 // The return type of a function definition must be complete 6339 // (C99 6.9.1p3, C++ [dcl.fct]p6). 6340 QualType ResultType = FD->getResultType(); 6341 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 6342 !FD->isInvalidDecl() && 6343 RequireCompleteType(FD->getLocation(), ResultType, 6344 diag::err_func_def_incomplete_result)) 6345 FD->setInvalidDecl(); 6346 6347 // GNU warning -Wmissing-prototypes: 6348 // Warn if a global function is defined without a previous 6349 // prototype declaration. This warning is issued even if the 6350 // definition itself provides a prototype. The aim is to detect 6351 // global functions that fail to be declared in header files. 6352 if (ShouldWarnAboutMissingPrototype(FD)) 6353 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 6354 6355 if (FnBodyScope) 6356 PushDeclContext(FnBodyScope, FD); 6357 6358 // Check the validity of our function parameters 6359 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 6360 /*CheckParameterNames=*/true); 6361 6362 // Introduce our parameters into the function scope 6363 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 6364 ParmVarDecl *Param = FD->getParamDecl(p); 6365 Param->setOwningFunction(FD); 6366 6367 // If this has an identifier, add it to the scope stack. 6368 if (Param->getIdentifier() && FnBodyScope) { 6369 CheckShadow(FnBodyScope, Param); 6370 6371 PushOnScopeChains(Param, FnBodyScope); 6372 } 6373 } 6374 6375 // Checking attributes of current function definition 6376 // dllimport attribute. 6377 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 6378 if (DA && (!FD->getAttr<DLLExportAttr>())) { 6379 // dllimport attribute cannot be directly applied to definition. 6380 // Microsoft accepts dllimport for functions defined within class scope. 6381 if (!DA->isInherited() && 6382 !(LangOpts.Microsoft && FD->getLexicalDeclContext()->isRecord())) { 6383 Diag(FD->getLocation(), 6384 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 6385 << "dllimport"; 6386 FD->setInvalidDecl(); 6387 return FD; 6388 } 6389 6390 // Visual C++ appears to not think this is an issue, so only issue 6391 // a warning when Microsoft extensions are disabled. 6392 if (!LangOpts.Microsoft) { 6393 // If a symbol previously declared dllimport is later defined, the 6394 // attribute is ignored in subsequent references, and a warning is 6395 // emitted. 6396 Diag(FD->getLocation(), 6397 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6398 << FD->getName() << "dllimport"; 6399 } 6400 } 6401 return FD; 6402 } 6403 6404 /// \brief Given the set of return statements within a function body, 6405 /// compute the variables that are subject to the named return value 6406 /// optimization. 6407 /// 6408 /// Each of the variables that is subject to the named return value 6409 /// optimization will be marked as NRVO variables in the AST, and any 6410 /// return statement that has a marked NRVO variable as its NRVO candidate can 6411 /// use the named return value optimization. 6412 /// 6413 /// This function applies a very simplistic algorithm for NRVO: if every return 6414 /// statement in the function has the same NRVO candidate, that candidate is 6415 /// the NRVO variable. 6416 /// 6417 /// FIXME: Employ a smarter algorithm that accounts for multiple return 6418 /// statements and the lifetimes of the NRVO candidates. We should be able to 6419 /// find a maximal set of NRVO variables. 6420 static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 6421 ReturnStmt **Returns = Scope->Returns.data(); 6422 6423 const VarDecl *NRVOCandidate = 0; 6424 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 6425 if (!Returns[I]->getNRVOCandidate()) 6426 return; 6427 6428 if (!NRVOCandidate) 6429 NRVOCandidate = Returns[I]->getNRVOCandidate(); 6430 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 6431 return; 6432 } 6433 6434 if (NRVOCandidate) 6435 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 6436 } 6437 6438 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 6439 return ActOnFinishFunctionBody(D, move(BodyArg), false); 6440 } 6441 6442 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 6443 bool IsInstantiation) { 6444 FunctionDecl *FD = 0; 6445 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 6446 if (FunTmpl) 6447 FD = FunTmpl->getTemplatedDecl(); 6448 else 6449 FD = dyn_cast_or_null<FunctionDecl>(dcl); 6450 6451 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 6452 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 6453 6454 if (FD) { 6455 FD->setBody(Body); 6456 if (FD->isMain()) { 6457 // C and C++ allow for main to automagically return 0. 6458 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6459 FD->setHasImplicitReturnZero(true); 6460 WP.disableCheckFallThrough(); 6461 } else if (FD->hasAttr<NakedAttr>()) { 6462 // If the function is marked 'naked', don't complain about missing return 6463 // statements. 6464 WP.disableCheckFallThrough(); 6465 } 6466 6467 // MSVC permits the use of pure specifier (=0) on function definition, 6468 // defined at class scope, warn about this non standard construct. 6469 if (getLangOptions().Microsoft && FD->isPure()) 6470 Diag(FD->getLocation(), diag::warn_pure_function_definition); 6471 6472 if (!FD->isInvalidDecl()) { 6473 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 6474 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 6475 FD->getResultType(), FD); 6476 6477 // If this is a constructor, we need a vtable. 6478 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 6479 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 6480 6481 ComputeNRVO(Body, getCurFunction()); 6482 } 6483 6484 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 6485 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 6486 assert(MD == getCurMethodDecl() && "Method parsing confused"); 6487 MD->setBody(Body); 6488 if (Body) 6489 MD->setEndLoc(Body->getLocEnd()); 6490 if (!MD->isInvalidDecl()) { 6491 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 6492 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 6493 MD->getResultType(), MD); 6494 } 6495 } else { 6496 return 0; 6497 } 6498 6499 // Verify and clean out per-function state. 6500 if (Body) { 6501 // C++ constructors that have function-try-blocks can't have return 6502 // statements in the handlers of that block. (C++ [except.handle]p14) 6503 // Verify this. 6504 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 6505 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 6506 6507 // Verify that that gotos and switch cases don't jump into scopes illegally. 6508 // Verify that that gotos and switch cases don't jump into scopes illegally. 6509 if (getCurFunction()->NeedsScopeChecking() && 6510 !dcl->isInvalidDecl() && 6511 !hasAnyUnrecoverableErrorsInThisFunction()) 6512 DiagnoseInvalidJumps(Body); 6513 6514 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 6515 if (!Destructor->getParent()->isDependentType()) 6516 CheckDestructor(Destructor); 6517 6518 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 6519 Destructor->getParent()); 6520 } 6521 6522 // If any errors have occurred, clear out any temporaries that may have 6523 // been leftover. This ensures that these temporaries won't be picked up for 6524 // deletion in some later function. 6525 if (PP.getDiagnostics().hasErrorOccurred() || 6526 PP.getDiagnostics().getSuppressAllDiagnostics()) { 6527 ExprTemporaries.clear(); 6528 ExprNeedsCleanups = false; 6529 } else if (!isa<FunctionTemplateDecl>(dcl)) { 6530 // Since the body is valid, issue any analysis-based warnings that are 6531 // enabled. 6532 ActivePolicy = &WP; 6533 } 6534 6535 assert(ExprTemporaries.empty() && "Leftover temporaries in function"); 6536 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 6537 } 6538 6539 if (!IsInstantiation) 6540 PopDeclContext(); 6541 6542 PopFunctionOrBlockScope(ActivePolicy, dcl); 6543 6544 // If any errors have occurred, clear out any temporaries that may have 6545 // been leftover. This ensures that these temporaries won't be picked up for 6546 // deletion in some later function. 6547 if (getDiagnostics().hasErrorOccurred()) { 6548 ExprTemporaries.clear(); 6549 ExprNeedsCleanups = false; 6550 } 6551 6552 return dcl; 6553 } 6554 6555 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 6556 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 6557 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 6558 IdentifierInfo &II, Scope *S) { 6559 // Before we produce a declaration for an implicitly defined 6560 // function, see whether there was a locally-scoped declaration of 6561 // this name as a function or variable. If so, use that 6562 // (non-visible) declaration, and complain about it. 6563 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 6564 = LocallyScopedExternalDecls.find(&II); 6565 if (Pos != LocallyScopedExternalDecls.end()) { 6566 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 6567 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 6568 return Pos->second; 6569 } 6570 6571 // Extension in C99. Legal in C90, but warn about it. 6572 if (II.getName().startswith("__builtin_")) 6573 Diag(Loc, diag::warn_builtin_unknown) << &II; 6574 else if (getLangOptions().C99) 6575 Diag(Loc, diag::ext_implicit_function_decl) << &II; 6576 else 6577 Diag(Loc, diag::warn_implicit_function_decl) << &II; 6578 6579 // Set a Declarator for the implicit definition: int foo(); 6580 const char *Dummy; 6581 AttributeFactory attrFactory; 6582 DeclSpec DS(attrFactory); 6583 unsigned DiagID; 6584 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 6585 (void)Error; // Silence warning. 6586 assert(!Error && "Error setting up implicit decl!"); 6587 Declarator D(DS, Declarator::BlockContext); 6588 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 6589 0, 0, true, SourceLocation(), 6590 SourceLocation(), 6591 EST_None, SourceLocation(), 6592 0, 0, 0, 0, Loc, Loc, D), 6593 DS.getAttributes(), 6594 SourceLocation()); 6595 D.SetIdentifier(&II, Loc); 6596 6597 // Insert this function into translation-unit scope. 6598 6599 DeclContext *PrevDC = CurContext; 6600 CurContext = Context.getTranslationUnitDecl(); 6601 6602 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 6603 FD->setImplicit(); 6604 6605 CurContext = PrevDC; 6606 6607 AddKnownFunctionAttributes(FD); 6608 6609 return FD; 6610 } 6611 6612 /// \brief Adds any function attributes that we know a priori based on 6613 /// the declaration of this function. 6614 /// 6615 /// These attributes can apply both to implicitly-declared builtins 6616 /// (like __builtin___printf_chk) or to library-declared functions 6617 /// like NSLog or printf. 6618 /// 6619 /// We need to check for duplicate attributes both here and where user-written 6620 /// attributes are applied to declarations. 6621 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 6622 if (FD->isInvalidDecl()) 6623 return; 6624 6625 // If this is a built-in function, map its builtin attributes to 6626 // actual attributes. 6627 if (unsigned BuiltinID = FD->getBuiltinID()) { 6628 // Handle printf-formatting attributes. 6629 unsigned FormatIdx; 6630 bool HasVAListArg; 6631 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 6632 if (!FD->getAttr<FormatAttr>()) 6633 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6634 "printf", FormatIdx+1, 6635 HasVAListArg ? 0 : FormatIdx+2)); 6636 } 6637 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 6638 HasVAListArg)) { 6639 if (!FD->getAttr<FormatAttr>()) 6640 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6641 "scanf", FormatIdx+1, 6642 HasVAListArg ? 0 : FormatIdx+2)); 6643 } 6644 6645 // Mark const if we don't care about errno and that is the only 6646 // thing preventing the function from being const. This allows 6647 // IRgen to use LLVM intrinsics for such functions. 6648 if (!getLangOptions().MathErrno && 6649 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 6650 if (!FD->getAttr<ConstAttr>()) 6651 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 6652 } 6653 6654 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 6655 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 6656 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 6657 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 6658 } 6659 6660 IdentifierInfo *Name = FD->getIdentifier(); 6661 if (!Name) 6662 return; 6663 if ((!getLangOptions().CPlusPlus && 6664 FD->getDeclContext()->isTranslationUnit()) || 6665 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 6666 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 6667 LinkageSpecDecl::lang_c)) { 6668 // Okay: this could be a libc/libm/Objective-C function we know 6669 // about. 6670 } else 6671 return; 6672 6673 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 6674 // FIXME: NSLog and NSLogv should be target specific 6675 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 6676 // FIXME: We known better than our headers. 6677 const_cast<FormatAttr *>(Format)->setType(Context, "printf"); 6678 } else 6679 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6680 "printf", 1, 6681 Name->isStr("NSLogv") ? 0 : 2)); 6682 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 6683 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 6684 // target-specific builtins, perhaps? 6685 if (!FD->getAttr<FormatAttr>()) 6686 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6687 "printf", 2, 6688 Name->isStr("vasprintf") ? 0 : 3)); 6689 } 6690 } 6691 6692 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 6693 TypeSourceInfo *TInfo) { 6694 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 6695 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 6696 6697 if (!TInfo) { 6698 assert(D.isInvalidType() && "no declarator info for valid type"); 6699 TInfo = Context.getTrivialTypeSourceInfo(T); 6700 } 6701 6702 // Scope manipulation handled by caller. 6703 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 6704 D.getSourceRange().getBegin(), 6705 D.getIdentifierLoc(), 6706 D.getIdentifier(), 6707 TInfo); 6708 6709 // Bail out immediately if we have an invalid declaration. 6710 if (D.isInvalidType()) { 6711 NewTD->setInvalidDecl(); 6712 return NewTD; 6713 } 6714 6715 // C++ [dcl.typedef]p8: 6716 // If the typedef declaration defines an unnamed class (or 6717 // enum), the first typedef-name declared by the declaration 6718 // to be that class type (or enum type) is used to denote the 6719 // class type (or enum type) for linkage purposes only. 6720 // We need to check whether the type was declared in the declaration. 6721 switch (D.getDeclSpec().getTypeSpecType()) { 6722 case TST_enum: 6723 case TST_struct: 6724 case TST_union: 6725 case TST_class: { 6726 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 6727 6728 // Do nothing if the tag is not anonymous or already has an 6729 // associated typedef (from an earlier typedef in this decl group). 6730 if (tagFromDeclSpec->getIdentifier()) break; 6731 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 6732 6733 // A well-formed anonymous tag must always be a TUK_Definition. 6734 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 6735 6736 // The type must match the tag exactly; no qualifiers allowed. 6737 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 6738 break; 6739 6740 // Otherwise, set this is the anon-decl typedef for the tag. 6741 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 6742 break; 6743 } 6744 6745 default: 6746 break; 6747 } 6748 6749 return NewTD; 6750 } 6751 6752 6753 /// \brief Determine whether a tag with a given kind is acceptable 6754 /// as a redeclaration of the given tag declaration. 6755 /// 6756 /// \returns true if the new tag kind is acceptable, false otherwise. 6757 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 6758 TagTypeKind NewTag, bool isDefinition, 6759 SourceLocation NewTagLoc, 6760 const IdentifierInfo &Name) { 6761 // C++ [dcl.type.elab]p3: 6762 // The class-key or enum keyword present in the 6763 // elaborated-type-specifier shall agree in kind with the 6764 // declaration to which the name in the elaborated-type-specifier 6765 // refers. This rule also applies to the form of 6766 // elaborated-type-specifier that declares a class-name or 6767 // friend class since it can be construed as referring to the 6768 // definition of the class. Thus, in any 6769 // elaborated-type-specifier, the enum keyword shall be used to 6770 // refer to an enumeration (7.2), the union class-key shall be 6771 // used to refer to a union (clause 9), and either the class or 6772 // struct class-key shall be used to refer to a class (clause 9) 6773 // declared using the class or struct class-key. 6774 TagTypeKind OldTag = Previous->getTagKind(); 6775 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct)) 6776 if (OldTag == NewTag) 6777 return true; 6778 6779 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 6780 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 6781 // Warn about the struct/class tag mismatch. 6782 bool isTemplate = false; 6783 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 6784 isTemplate = Record->getDescribedClassTemplate(); 6785 6786 if (!ActiveTemplateInstantiations.empty()) { 6787 // In a template instantiation, do not offer fix-its for tag mismatches 6788 // since they usually mess up the template instead of fixing the problem. 6789 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 6790 << (NewTag == TTK_Class) << isTemplate << &Name; 6791 return true; 6792 } 6793 6794 if (isDefinition) { 6795 // On definitions, check previous tags and issue a fix-it for each 6796 // one that doesn't match the current tag. 6797 if (Previous->getDefinition()) { 6798 // Don't suggest fix-its for redefinitions. 6799 return true; 6800 } 6801 6802 bool previousMismatch = false; 6803 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 6804 E(Previous->redecls_end()); I != E; ++I) { 6805 if (I->getTagKind() != NewTag) { 6806 if (!previousMismatch) { 6807 previousMismatch = true; 6808 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 6809 << (NewTag == TTK_Class) << isTemplate << &Name; 6810 } 6811 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 6812 << (NewTag == TTK_Class) 6813 << FixItHint::CreateReplacement(I->getInnerLocStart(), 6814 NewTag == TTK_Class? 6815 "class" : "struct"); 6816 } 6817 } 6818 return true; 6819 } 6820 6821 // Check for a previous definition. If current tag and definition 6822 // are same type, do nothing. If no definition, but disagree with 6823 // with previous tag type, give a warning, but no fix-it. 6824 const TagDecl *Redecl = Previous->getDefinition() ? 6825 Previous->getDefinition() : Previous; 6826 if (Redecl->getTagKind() == NewTag) { 6827 return true; 6828 } 6829 6830 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 6831 << (NewTag == TTK_Class) 6832 << isTemplate << &Name; 6833 Diag(Redecl->getLocation(), diag::note_previous_use); 6834 6835 // If there is a previous defintion, suggest a fix-it. 6836 if (Previous->getDefinition()) { 6837 Diag(NewTagLoc, diag::note_struct_class_suggestion) 6838 << (Redecl->getTagKind() == TTK_Class) 6839 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 6840 Redecl->getTagKind() == TTK_Class? "class" : "struct"); 6841 } 6842 6843 return true; 6844 } 6845 return false; 6846 } 6847 6848 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 6849 /// former case, Name will be non-null. In the later case, Name will be null. 6850 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 6851 /// reference/declaration/definition of a tag. 6852 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 6853 SourceLocation KWLoc, CXXScopeSpec &SS, 6854 IdentifierInfo *Name, SourceLocation NameLoc, 6855 AttributeList *Attr, AccessSpecifier AS, 6856 MultiTemplateParamsArg TemplateParameterLists, 6857 bool &OwnedDecl, bool &IsDependent, 6858 bool ScopedEnum, bool ScopedEnumUsesClassTag, 6859 TypeResult UnderlyingType) { 6860 // If this is not a definition, it must have a name. 6861 assert((Name != 0 || TUK == TUK_Definition) && 6862 "Nameless record must be a definition!"); 6863 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 6864 6865 OwnedDecl = false; 6866 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 6867 6868 // FIXME: Check explicit specializations more carefully. 6869 bool isExplicitSpecialization = false; 6870 bool Invalid = false; 6871 6872 // We only need to do this matching if we have template parameters 6873 // or a scope specifier, which also conveniently avoids this work 6874 // for non-C++ cases. 6875 if (TemplateParameterLists.size() > 0 || 6876 (SS.isNotEmpty() && TUK != TUK_Reference)) { 6877 if (TemplateParameterList *TemplateParams 6878 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 6879 TemplateParameterLists.get(), 6880 TemplateParameterLists.size(), 6881 TUK == TUK_Friend, 6882 isExplicitSpecialization, 6883 Invalid)) { 6884 if (TemplateParams->size() > 0) { 6885 // This is a declaration or definition of a class template (which may 6886 // be a member of another template). 6887 6888 if (Invalid) 6889 return 0; 6890 6891 OwnedDecl = false; 6892 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 6893 SS, Name, NameLoc, Attr, 6894 TemplateParams, AS, 6895 TemplateParameterLists.size() - 1, 6896 (TemplateParameterList**) TemplateParameterLists.release()); 6897 return Result.get(); 6898 } else { 6899 // The "template<>" header is extraneous. 6900 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 6901 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 6902 isExplicitSpecialization = true; 6903 } 6904 } 6905 } 6906 6907 // Figure out the underlying type if this a enum declaration. We need to do 6908 // this early, because it's needed to detect if this is an incompatible 6909 // redeclaration. 6910 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 6911 6912 if (Kind == TTK_Enum) { 6913 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 6914 // No underlying type explicitly specified, or we failed to parse the 6915 // type, default to int. 6916 EnumUnderlying = Context.IntTy.getTypePtr(); 6917 else if (UnderlyingType.get()) { 6918 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 6919 // integral type; any cv-qualification is ignored. 6920 TypeSourceInfo *TI = 0; 6921 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI); 6922 EnumUnderlying = TI; 6923 6924 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 6925 6926 if (!T->isDependentType() && !T->isIntegralType(Context)) { 6927 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 6928 << T; 6929 // Recover by falling back to int. 6930 EnumUnderlying = Context.IntTy.getTypePtr(); 6931 } 6932 6933 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI, 6934 UPPC_FixedUnderlyingType)) 6935 EnumUnderlying = Context.IntTy.getTypePtr(); 6936 6937 } else if (getLangOptions().Microsoft) 6938 // Microsoft enums are always of int type. 6939 EnumUnderlying = Context.IntTy.getTypePtr(); 6940 } 6941 6942 DeclContext *SearchDC = CurContext; 6943 DeclContext *DC = CurContext; 6944 bool isStdBadAlloc = false; 6945 6946 RedeclarationKind Redecl = ForRedeclaration; 6947 if (TUK == TUK_Friend || TUK == TUK_Reference) 6948 Redecl = NotForRedeclaration; 6949 6950 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 6951 6952 if (Name && SS.isNotEmpty()) { 6953 // We have a nested-name tag ('struct foo::bar'). 6954 6955 // Check for invalid 'foo::'. 6956 if (SS.isInvalid()) { 6957 Name = 0; 6958 goto CreateNewDecl; 6959 } 6960 6961 // If this is a friend or a reference to a class in a dependent 6962 // context, don't try to make a decl for it. 6963 if (TUK == TUK_Friend || TUK == TUK_Reference) { 6964 DC = computeDeclContext(SS, false); 6965 if (!DC) { 6966 IsDependent = true; 6967 return 0; 6968 } 6969 } else { 6970 DC = computeDeclContext(SS, true); 6971 if (!DC) { 6972 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 6973 << SS.getRange(); 6974 return 0; 6975 } 6976 } 6977 6978 if (RequireCompleteDeclContext(SS, DC)) 6979 return 0; 6980 6981 SearchDC = DC; 6982 // Look-up name inside 'foo::'. 6983 LookupQualifiedName(Previous, DC); 6984 6985 if (Previous.isAmbiguous()) 6986 return 0; 6987 6988 if (Previous.empty()) { 6989 // Name lookup did not find anything. However, if the 6990 // nested-name-specifier refers to the current instantiation, 6991 // and that current instantiation has any dependent base 6992 // classes, we might find something at instantiation time: treat 6993 // this as a dependent elaborated-type-specifier. 6994 // But this only makes any sense for reference-like lookups. 6995 if (Previous.wasNotFoundInCurrentInstantiation() && 6996 (TUK == TUK_Reference || TUK == TUK_Friend)) { 6997 IsDependent = true; 6998 return 0; 6999 } 7000 7001 // A tag 'foo::bar' must already exist. 7002 Diag(NameLoc, diag::err_not_tag_in_scope) 7003 << Kind << Name << DC << SS.getRange(); 7004 Name = 0; 7005 Invalid = true; 7006 goto CreateNewDecl; 7007 } 7008 } else if (Name) { 7009 // If this is a named struct, check to see if there was a previous forward 7010 // declaration or definition. 7011 // FIXME: We're looking into outer scopes here, even when we 7012 // shouldn't be. Doing so can result in ambiguities that we 7013 // shouldn't be diagnosing. 7014 LookupName(Previous, S); 7015 7016 if (Previous.isAmbiguous() && 7017 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 7018 LookupResult::Filter F = Previous.makeFilter(); 7019 while (F.hasNext()) { 7020 NamedDecl *ND = F.next(); 7021 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 7022 F.erase(); 7023 } 7024 F.done(); 7025 } 7026 7027 // Note: there used to be some attempt at recovery here. 7028 if (Previous.isAmbiguous()) 7029 return 0; 7030 7031 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 7032 // FIXME: This makes sure that we ignore the contexts associated 7033 // with C structs, unions, and enums when looking for a matching 7034 // tag declaration or definition. See the similar lookup tweak 7035 // in Sema::LookupName; is there a better way to deal with this? 7036 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 7037 SearchDC = SearchDC->getParent(); 7038 } 7039 } else if (S->isFunctionPrototypeScope()) { 7040 // If this is an enum declaration in function prototype scope, set its 7041 // initial context to the translation unit. 7042 SearchDC = Context.getTranslationUnitDecl(); 7043 } 7044 7045 if (Previous.isSingleResult() && 7046 Previous.getFoundDecl()->isTemplateParameter()) { 7047 // Maybe we will complain about the shadowed template parameter. 7048 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 7049 // Just pretend that we didn't see the previous declaration. 7050 Previous.clear(); 7051 } 7052 7053 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 7054 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 7055 // This is a declaration of or a reference to "std::bad_alloc". 7056 isStdBadAlloc = true; 7057 7058 if (Previous.empty() && StdBadAlloc) { 7059 // std::bad_alloc has been implicitly declared (but made invisible to 7060 // name lookup). Fill in this implicit declaration as the previous 7061 // declaration, so that the declarations get chained appropriately. 7062 Previous.addDecl(getStdBadAlloc()); 7063 } 7064 } 7065 7066 // If we didn't find a previous declaration, and this is a reference 7067 // (or friend reference), move to the correct scope. In C++, we 7068 // also need to do a redeclaration lookup there, just in case 7069 // there's a shadow friend decl. 7070 if (Name && Previous.empty() && 7071 (TUK == TUK_Reference || TUK == TUK_Friend)) { 7072 if (Invalid) goto CreateNewDecl; 7073 assert(SS.isEmpty()); 7074 7075 if (TUK == TUK_Reference) { 7076 // C++ [basic.scope.pdecl]p5: 7077 // -- for an elaborated-type-specifier of the form 7078 // 7079 // class-key identifier 7080 // 7081 // if the elaborated-type-specifier is used in the 7082 // decl-specifier-seq or parameter-declaration-clause of a 7083 // function defined in namespace scope, the identifier is 7084 // declared as a class-name in the namespace that contains 7085 // the declaration; otherwise, except as a friend 7086 // declaration, the identifier is declared in the smallest 7087 // non-class, non-function-prototype scope that contains the 7088 // declaration. 7089 // 7090 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 7091 // C structs and unions. 7092 // 7093 // It is an error in C++ to declare (rather than define) an enum 7094 // type, including via an elaborated type specifier. We'll 7095 // diagnose that later; for now, declare the enum in the same 7096 // scope as we would have picked for any other tag type. 7097 // 7098 // GNU C also supports this behavior as part of its incomplete 7099 // enum types extension, while GNU C++ does not. 7100 // 7101 // Find the context where we'll be declaring the tag. 7102 // FIXME: We would like to maintain the current DeclContext as the 7103 // lexical context, 7104 while (SearchDC->isRecord() || SearchDC->isTransparentContext()) 7105 SearchDC = SearchDC->getParent(); 7106 7107 // Find the scope where we'll be declaring the tag. 7108 while (S->isClassScope() || 7109 (getLangOptions().CPlusPlus && 7110 S->isFunctionPrototypeScope()) || 7111 ((S->getFlags() & Scope::DeclScope) == 0) || 7112 (S->getEntity() && 7113 ((DeclContext *)S->getEntity())->isTransparentContext())) 7114 S = S->getParent(); 7115 } else { 7116 assert(TUK == TUK_Friend); 7117 // C++ [namespace.memdef]p3: 7118 // If a friend declaration in a non-local class first declares a 7119 // class or function, the friend class or function is a member of 7120 // the innermost enclosing namespace. 7121 SearchDC = SearchDC->getEnclosingNamespaceContext(); 7122 } 7123 7124 // In C++, we need to do a redeclaration lookup to properly 7125 // diagnose some problems. 7126 if (getLangOptions().CPlusPlus) { 7127 Previous.setRedeclarationKind(ForRedeclaration); 7128 LookupQualifiedName(Previous, SearchDC); 7129 } 7130 } 7131 7132 if (!Previous.empty()) { 7133 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 7134 7135 // It's okay to have a tag decl in the same scope as a typedef 7136 // which hides a tag decl in the same scope. Finding this 7137 // insanity with a redeclaration lookup can only actually happen 7138 // in C++. 7139 // 7140 // This is also okay for elaborated-type-specifiers, which is 7141 // technically forbidden by the current standard but which is 7142 // okay according to the likely resolution of an open issue; 7143 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 7144 if (getLangOptions().CPlusPlus) { 7145 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7146 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 7147 TagDecl *Tag = TT->getDecl(); 7148 if (Tag->getDeclName() == Name && 7149 Tag->getDeclContext()->getRedeclContext() 7150 ->Equals(TD->getDeclContext()->getRedeclContext())) { 7151 PrevDecl = Tag; 7152 Previous.clear(); 7153 Previous.addDecl(Tag); 7154 Previous.resolveKind(); 7155 } 7156 } 7157 } 7158 } 7159 7160 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 7161 // If this is a use of a previous tag, or if the tag is already declared 7162 // in the same scope (so that the definition/declaration completes or 7163 // rementions the tag), reuse the decl. 7164 if (TUK == TUK_Reference || TUK == TUK_Friend || 7165 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 7166 // Make sure that this wasn't declared as an enum and now used as a 7167 // struct or something similar. 7168 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 7169 TUK == TUK_Definition, KWLoc, 7170 *Name)) { 7171 bool SafeToContinue 7172 = (PrevTagDecl->getTagKind() != TTK_Enum && 7173 Kind != TTK_Enum); 7174 if (SafeToContinue) 7175 Diag(KWLoc, diag::err_use_with_wrong_tag) 7176 << Name 7177 << FixItHint::CreateReplacement(SourceRange(KWLoc), 7178 PrevTagDecl->getKindName()); 7179 else 7180 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 7181 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7182 7183 if (SafeToContinue) 7184 Kind = PrevTagDecl->getTagKind(); 7185 else { 7186 // Recover by making this an anonymous redefinition. 7187 Name = 0; 7188 Previous.clear(); 7189 Invalid = true; 7190 } 7191 } 7192 7193 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 7194 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 7195 7196 // All conflicts with previous declarations are recovered by 7197 // returning the previous declaration. 7198 if (ScopedEnum != PrevEnum->isScoped()) { 7199 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch) 7200 << PrevEnum->isScoped(); 7201 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7202 return PrevTagDecl; 7203 } 7204 else if (EnumUnderlying && PrevEnum->isFixed()) { 7205 QualType T; 7206 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 7207 T = TI->getType(); 7208 else 7209 T = QualType(EnumUnderlying.get<const Type*>(), 0); 7210 7211 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) { 7212 Diag(NameLoc.isValid() ? NameLoc : KWLoc, 7213 diag::err_enum_redeclare_type_mismatch) 7214 << T 7215 << PrevEnum->getIntegerType(); 7216 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7217 return PrevTagDecl; 7218 } 7219 } 7220 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) { 7221 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch) 7222 << PrevEnum->isFixed(); 7223 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7224 return PrevTagDecl; 7225 } 7226 } 7227 7228 if (!Invalid) { 7229 // If this is a use, just return the declaration we found. 7230 7231 // FIXME: In the future, return a variant or some other clue 7232 // for the consumer of this Decl to know it doesn't own it. 7233 // For our current ASTs this shouldn't be a problem, but will 7234 // need to be changed with DeclGroups. 7235 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 7236 getLangOptions().Microsoft)) || TUK == TUK_Friend) 7237 return PrevTagDecl; 7238 7239 // Diagnose attempts to redefine a tag. 7240 if (TUK == TUK_Definition) { 7241 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 7242 // If we're defining a specialization and the previous definition 7243 // is from an implicit instantiation, don't emit an error 7244 // here; we'll catch this in the general case below. 7245 if (!isExplicitSpecialization || 7246 !isa<CXXRecordDecl>(Def) || 7247 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 7248 == TSK_ExplicitSpecialization) { 7249 Diag(NameLoc, diag::err_redefinition) << Name; 7250 Diag(Def->getLocation(), diag::note_previous_definition); 7251 // If this is a redefinition, recover by making this 7252 // struct be anonymous, which will make any later 7253 // references get the previous definition. 7254 Name = 0; 7255 Previous.clear(); 7256 Invalid = true; 7257 } 7258 } else { 7259 // If the type is currently being defined, complain 7260 // about a nested redefinition. 7261 const TagType *Tag 7262 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 7263 if (Tag->isBeingDefined()) { 7264 Diag(NameLoc, diag::err_nested_redefinition) << Name; 7265 Diag(PrevTagDecl->getLocation(), 7266 diag::note_previous_definition); 7267 Name = 0; 7268 Previous.clear(); 7269 Invalid = true; 7270 } 7271 } 7272 7273 // Okay, this is definition of a previously declared or referenced 7274 // tag PrevDecl. We're going to create a new Decl for it. 7275 } 7276 } 7277 // If we get here we have (another) forward declaration or we 7278 // have a definition. Just create a new decl. 7279 7280 } else { 7281 // If we get here, this is a definition of a new tag type in a nested 7282 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 7283 // new decl/type. We set PrevDecl to NULL so that the entities 7284 // have distinct types. 7285 Previous.clear(); 7286 } 7287 // If we get here, we're going to create a new Decl. If PrevDecl 7288 // is non-NULL, it's a definition of the tag declared by 7289 // PrevDecl. If it's NULL, we have a new definition. 7290 7291 7292 // Otherwise, PrevDecl is not a tag, but was found with tag 7293 // lookup. This is only actually possible in C++, where a few 7294 // things like templates still live in the tag namespace. 7295 } else { 7296 assert(getLangOptions().CPlusPlus); 7297 7298 // Use a better diagnostic if an elaborated-type-specifier 7299 // found the wrong kind of type on the first 7300 // (non-redeclaration) lookup. 7301 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 7302 !Previous.isForRedeclaration()) { 7303 unsigned Kind = 0; 7304 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 7305 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 7306 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 7307 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 7308 Diag(PrevDecl->getLocation(), diag::note_declared_at); 7309 Invalid = true; 7310 7311 // Otherwise, only diagnose if the declaration is in scope. 7312 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 7313 isExplicitSpecialization)) { 7314 // do nothing 7315 7316 // Diagnose implicit declarations introduced by elaborated types. 7317 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 7318 unsigned Kind = 0; 7319 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 7320 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 7321 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 7322 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 7323 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 7324 Invalid = true; 7325 7326 // Otherwise it's a declaration. Call out a particularly common 7327 // case here. 7328 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7329 unsigned Kind = 0; 7330 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 7331 Diag(NameLoc, diag::err_tag_definition_of_typedef) 7332 << Name << Kind << TND->getUnderlyingType(); 7333 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 7334 Invalid = true; 7335 7336 // Otherwise, diagnose. 7337 } else { 7338 // The tag name clashes with something else in the target scope, 7339 // issue an error and recover by making this tag be anonymous. 7340 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 7341 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7342 Name = 0; 7343 Invalid = true; 7344 } 7345 7346 // The existing declaration isn't relevant to us; we're in a 7347 // new scope, so clear out the previous declaration. 7348 Previous.clear(); 7349 } 7350 } 7351 7352 CreateNewDecl: 7353 7354 TagDecl *PrevDecl = 0; 7355 if (Previous.isSingleResult()) 7356 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 7357 7358 // If there is an identifier, use the location of the identifier as the 7359 // location of the decl, otherwise use the location of the struct/union 7360 // keyword. 7361 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 7362 7363 // Otherwise, create a new declaration. If there is a previous 7364 // declaration of the same entity, the two will be linked via 7365 // PrevDecl. 7366 TagDecl *New; 7367 7368 bool IsForwardReference = false; 7369 if (Kind == TTK_Enum) { 7370 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 7371 // enum X { A, B, C } D; D should chain to X. 7372 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 7373 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 7374 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 7375 // If this is an undefined enum, warn. 7376 if (TUK != TUK_Definition && !Invalid) { 7377 TagDecl *Def; 7378 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) { 7379 // C++0x: 7.2p2: opaque-enum-declaration. 7380 // Conflicts are diagnosed above. Do nothing. 7381 } 7382 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 7383 Diag(Loc, diag::ext_forward_ref_enum_def) 7384 << New; 7385 Diag(Def->getLocation(), diag::note_previous_definition); 7386 } else { 7387 unsigned DiagID = diag::ext_forward_ref_enum; 7388 if (getLangOptions().Microsoft) 7389 DiagID = diag::ext_ms_forward_ref_enum; 7390 else if (getLangOptions().CPlusPlus) 7391 DiagID = diag::err_forward_ref_enum; 7392 Diag(Loc, DiagID); 7393 7394 // If this is a forward-declared reference to an enumeration, make a 7395 // note of it; we won't actually be introducing the declaration into 7396 // the declaration context. 7397 if (TUK == TUK_Reference) 7398 IsForwardReference = true; 7399 } 7400 } 7401 7402 if (EnumUnderlying) { 7403 EnumDecl *ED = cast<EnumDecl>(New); 7404 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 7405 ED->setIntegerTypeSourceInfo(TI); 7406 else 7407 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 7408 ED->setPromotionType(ED->getIntegerType()); 7409 } 7410 7411 } else { 7412 // struct/union/class 7413 7414 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 7415 // struct X { int A; } D; D should chain to X. 7416 if (getLangOptions().CPlusPlus) { 7417 // FIXME: Look for a way to use RecordDecl for simple structs. 7418 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 7419 cast_or_null<CXXRecordDecl>(PrevDecl)); 7420 7421 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 7422 StdBadAlloc = cast<CXXRecordDecl>(New); 7423 } else 7424 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 7425 cast_or_null<RecordDecl>(PrevDecl)); 7426 } 7427 7428 // Maybe add qualifier info. 7429 if (SS.isNotEmpty()) { 7430 if (SS.isSet()) { 7431 New->setQualifierInfo(SS.getWithLocInContext(Context)); 7432 if (TemplateParameterLists.size() > 0) { 7433 New->setTemplateParameterListsInfo(Context, 7434 TemplateParameterLists.size(), 7435 (TemplateParameterList**) TemplateParameterLists.release()); 7436 } 7437 } 7438 else 7439 Invalid = true; 7440 } 7441 7442 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 7443 // Add alignment attributes if necessary; these attributes are checked when 7444 // the ASTContext lays out the structure. 7445 // 7446 // It is important for implementing the correct semantics that this 7447 // happen here (in act on tag decl). The #pragma pack stack is 7448 // maintained as a result of parser callbacks which can occur at 7449 // many points during the parsing of a struct declaration (because 7450 // the #pragma tokens are effectively skipped over during the 7451 // parsing of the struct). 7452 AddAlignmentAttributesForRecord(RD); 7453 7454 AddMsStructLayoutForRecord(RD); 7455 } 7456 7457 // If this is a specialization of a member class (of a class template), 7458 // check the specialization. 7459 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 7460 Invalid = true; 7461 7462 if (Invalid) 7463 New->setInvalidDecl(); 7464 7465 if (Attr) 7466 ProcessDeclAttributeList(S, New, Attr); 7467 7468 // If we're declaring or defining a tag in function prototype scope 7469 // in C, note that this type can only be used within the function. 7470 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 7471 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 7472 7473 // Set the lexical context. If the tag has a C++ scope specifier, the 7474 // lexical context will be different from the semantic context. 7475 New->setLexicalDeclContext(CurContext); 7476 7477 // Mark this as a friend decl if applicable. 7478 // In Microsoft mode, a friend declaration also acts as a forward 7479 // declaration so we always pass true to setObjectOfFriendDecl to make 7480 // the tag name visible. 7481 if (TUK == TUK_Friend) 7482 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 7483 getLangOptions().Microsoft); 7484 7485 // Set the access specifier. 7486 if (!Invalid && SearchDC->isRecord()) 7487 SetMemberAccessSpecifier(New, PrevDecl, AS); 7488 7489 if (TUK == TUK_Definition) 7490 New->startDefinition(); 7491 7492 // If this has an identifier, add it to the scope stack. 7493 if (TUK == TUK_Friend) { 7494 // We might be replacing an existing declaration in the lookup tables; 7495 // if so, borrow its access specifier. 7496 if (PrevDecl) 7497 New->setAccess(PrevDecl->getAccess()); 7498 7499 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 7500 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 7501 if (Name) // can be null along some error paths 7502 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 7503 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 7504 } else if (Name) { 7505 S = getNonFieldDeclScope(S); 7506 PushOnScopeChains(New, S, !IsForwardReference); 7507 if (IsForwardReference) 7508 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 7509 7510 } else { 7511 CurContext->addDecl(New); 7512 } 7513 7514 // If this is the C FILE type, notify the AST context. 7515 if (IdentifierInfo *II = New->getIdentifier()) 7516 if (!New->isInvalidDecl() && 7517 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7518 II->isStr("FILE")) 7519 Context.setFILEDecl(New); 7520 7521 OwnedDecl = true; 7522 return New; 7523 } 7524 7525 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 7526 AdjustDeclIfTemplate(TagD); 7527 TagDecl *Tag = cast<TagDecl>(TagD); 7528 7529 // Enter the tag context. 7530 PushDeclContext(S, Tag); 7531 } 7532 7533 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 7534 SourceLocation FinalLoc, 7535 SourceLocation LBraceLoc) { 7536 AdjustDeclIfTemplate(TagD); 7537 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 7538 7539 FieldCollector->StartClass(); 7540 7541 if (!Record->getIdentifier()) 7542 return; 7543 7544 if (FinalLoc.isValid()) 7545 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 7546 7547 // C++ [class]p2: 7548 // [...] The class-name is also inserted into the scope of the 7549 // class itself; this is known as the injected-class-name. For 7550 // purposes of access checking, the injected-class-name is treated 7551 // as if it were a public member name. 7552 CXXRecordDecl *InjectedClassName 7553 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 7554 Record->getLocStart(), Record->getLocation(), 7555 Record->getIdentifier(), 7556 /*PrevDecl=*/0, 7557 /*DelayTypeCreation=*/true); 7558 Context.getTypeDeclType(InjectedClassName, Record); 7559 InjectedClassName->setImplicit(); 7560 InjectedClassName->setAccess(AS_public); 7561 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 7562 InjectedClassName->setDescribedClassTemplate(Template); 7563 PushOnScopeChains(InjectedClassName, S); 7564 assert(InjectedClassName->isInjectedClassName() && 7565 "Broken injected-class-name"); 7566 } 7567 7568 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 7569 SourceLocation RBraceLoc) { 7570 AdjustDeclIfTemplate(TagD); 7571 TagDecl *Tag = cast<TagDecl>(TagD); 7572 Tag->setRBraceLoc(RBraceLoc); 7573 7574 if (isa<CXXRecordDecl>(Tag)) 7575 FieldCollector->FinishClass(); 7576 7577 // Exit this scope of this tag's definition. 7578 PopDeclContext(); 7579 7580 // Notify the consumer that we've defined a tag. 7581 Consumer.HandleTagDeclDefinition(Tag); 7582 } 7583 7584 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 7585 AdjustDeclIfTemplate(TagD); 7586 TagDecl *Tag = cast<TagDecl>(TagD); 7587 Tag->setInvalidDecl(); 7588 7589 // We're undoing ActOnTagStartDefinition here, not 7590 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 7591 // the FieldCollector. 7592 7593 PopDeclContext(); 7594 } 7595 7596 // Note that FieldName may be null for anonymous bitfields. 7597 bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 7598 QualType FieldTy, const Expr *BitWidth, 7599 bool *ZeroWidth) { 7600 // Default to true; that shouldn't confuse checks for emptiness 7601 if (ZeroWidth) 7602 *ZeroWidth = true; 7603 7604 // C99 6.7.2.1p4 - verify the field type. 7605 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 7606 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 7607 // Handle incomplete types with specific error. 7608 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 7609 return true; 7610 if (FieldName) 7611 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 7612 << FieldName << FieldTy << BitWidth->getSourceRange(); 7613 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 7614 << FieldTy << BitWidth->getSourceRange(); 7615 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 7616 UPPC_BitFieldWidth)) 7617 return true; 7618 7619 // If the bit-width is type- or value-dependent, don't try to check 7620 // it now. 7621 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 7622 return false; 7623 7624 llvm::APSInt Value; 7625 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 7626 return true; 7627 7628 if (Value != 0 && ZeroWidth) 7629 *ZeroWidth = false; 7630 7631 // Zero-width bitfield is ok for anonymous field. 7632 if (Value == 0 && FieldName) 7633 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 7634 7635 if (Value.isSigned() && Value.isNegative()) { 7636 if (FieldName) 7637 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 7638 << FieldName << Value.toString(10); 7639 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 7640 << Value.toString(10); 7641 } 7642 7643 if (!FieldTy->isDependentType()) { 7644 uint64_t TypeSize = Context.getTypeSize(FieldTy); 7645 if (Value.getZExtValue() > TypeSize) { 7646 if (!getLangOptions().CPlusPlus) { 7647 if (FieldName) 7648 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 7649 << FieldName << (unsigned)Value.getZExtValue() 7650 << (unsigned)TypeSize; 7651 7652 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 7653 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 7654 } 7655 7656 if (FieldName) 7657 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 7658 << FieldName << (unsigned)Value.getZExtValue() 7659 << (unsigned)TypeSize; 7660 else 7661 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 7662 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 7663 } 7664 } 7665 7666 return false; 7667 } 7668 7669 /// ActOnField - Each field of a C struct/union is passed into this in order 7670 /// to create a FieldDecl object for it. 7671 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 7672 Declarator &D, ExprTy *BitfieldWidth) { 7673 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 7674 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 7675 /*HasInit=*/false, AS_public); 7676 return Res; 7677 } 7678 7679 /// HandleField - Analyze a field of a C struct or a C++ data member. 7680 /// 7681 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 7682 SourceLocation DeclStart, 7683 Declarator &D, Expr *BitWidth, bool HasInit, 7684 AccessSpecifier AS) { 7685 IdentifierInfo *II = D.getIdentifier(); 7686 SourceLocation Loc = DeclStart; 7687 if (II) Loc = D.getIdentifierLoc(); 7688 7689 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7690 QualType T = TInfo->getType(); 7691 if (getLangOptions().CPlusPlus) { 7692 CheckExtraCXXDefaultArguments(D); 7693 7694 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 7695 UPPC_DataMemberType)) { 7696 D.setInvalidType(); 7697 T = Context.IntTy; 7698 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 7699 } 7700 } 7701 7702 DiagnoseFunctionSpecifiers(D); 7703 7704 if (D.getDeclSpec().isThreadSpecified()) 7705 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 7706 7707 // Check to see if this name was declared as a member previously 7708 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 7709 LookupName(Previous, S); 7710 assert((Previous.empty() || Previous.isOverloadedResult() || 7711 Previous.isSingleResult()) 7712 && "Lookup of member name should be either overloaded, single or null"); 7713 7714 // If the name is overloaded then get any declaration else get the single result 7715 NamedDecl *PrevDecl = Previous.isOverloadedResult() ? 7716 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>(); 7717 7718 if (PrevDecl && PrevDecl->isTemplateParameter()) { 7719 // Maybe we will complain about the shadowed template parameter. 7720 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 7721 // Just pretend that we didn't see the previous declaration. 7722 PrevDecl = 0; 7723 } 7724 7725 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 7726 PrevDecl = 0; 7727 7728 bool Mutable 7729 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 7730 SourceLocation TSSL = D.getSourceRange().getBegin(); 7731 FieldDecl *NewFD 7732 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit, 7733 TSSL, AS, PrevDecl, &D); 7734 7735 if (NewFD->isInvalidDecl()) 7736 Record->setInvalidDecl(); 7737 7738 if (NewFD->isInvalidDecl() && PrevDecl) { 7739 // Don't introduce NewFD into scope; there's already something 7740 // with the same name in the same scope. 7741 } else if (II) { 7742 PushOnScopeChains(NewFD, S); 7743 } else 7744 Record->addDecl(NewFD); 7745 7746 return NewFD; 7747 } 7748 7749 /// \brief Build a new FieldDecl and check its well-formedness. 7750 /// 7751 /// This routine builds a new FieldDecl given the fields name, type, 7752 /// record, etc. \p PrevDecl should refer to any previous declaration 7753 /// with the same name and in the same scope as the field to be 7754 /// created. 7755 /// 7756 /// \returns a new FieldDecl. 7757 /// 7758 /// \todo The Declarator argument is a hack. It will be removed once 7759 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 7760 TypeSourceInfo *TInfo, 7761 RecordDecl *Record, SourceLocation Loc, 7762 bool Mutable, Expr *BitWidth, bool HasInit, 7763 SourceLocation TSSL, 7764 AccessSpecifier AS, NamedDecl *PrevDecl, 7765 Declarator *D) { 7766 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7767 bool InvalidDecl = false; 7768 if (D) InvalidDecl = D->isInvalidType(); 7769 7770 // If we receive a broken type, recover by assuming 'int' and 7771 // marking this declaration as invalid. 7772 if (T.isNull()) { 7773 InvalidDecl = true; 7774 T = Context.IntTy; 7775 } 7776 7777 QualType EltTy = Context.getBaseElementType(T); 7778 if (!EltTy->isDependentType() && 7779 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 7780 // Fields of incomplete type force their record to be invalid. 7781 Record->setInvalidDecl(); 7782 InvalidDecl = true; 7783 } 7784 7785 // C99 6.7.2.1p8: A member of a structure or union may have any type other 7786 // than a variably modified type. 7787 if (!InvalidDecl && T->isVariablyModifiedType()) { 7788 bool SizeIsNegative; 7789 llvm::APSInt Oversized; 7790 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 7791 SizeIsNegative, 7792 Oversized); 7793 if (!FixedTy.isNull()) { 7794 Diag(Loc, diag::warn_illegal_constant_array_size); 7795 T = FixedTy; 7796 } else { 7797 if (SizeIsNegative) 7798 Diag(Loc, diag::err_typecheck_negative_array_size); 7799 else if (Oversized.getBoolValue()) 7800 Diag(Loc, diag::err_array_too_large) 7801 << Oversized.toString(10); 7802 else 7803 Diag(Loc, diag::err_typecheck_field_variable_size); 7804 InvalidDecl = true; 7805 } 7806 } 7807 7808 // Fields can not have abstract class types 7809 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 7810 diag::err_abstract_type_in_decl, 7811 AbstractFieldType)) 7812 InvalidDecl = true; 7813 7814 bool ZeroWidth = false; 7815 // If this is declared as a bit-field, check the bit-field. 7816 if (!InvalidDecl && BitWidth && 7817 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 7818 InvalidDecl = true; 7819 BitWidth = 0; 7820 ZeroWidth = false; 7821 } 7822 7823 // Check that 'mutable' is consistent with the type of the declaration. 7824 if (!InvalidDecl && Mutable) { 7825 unsigned DiagID = 0; 7826 if (T->isReferenceType()) 7827 DiagID = diag::err_mutable_reference; 7828 else if (T.isConstQualified()) 7829 DiagID = diag::err_mutable_const; 7830 7831 if (DiagID) { 7832 SourceLocation ErrLoc = Loc; 7833 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 7834 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 7835 Diag(ErrLoc, DiagID); 7836 Mutable = false; 7837 InvalidDecl = true; 7838 } 7839 } 7840 7841 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 7842 BitWidth, Mutable, HasInit); 7843 if (InvalidDecl) 7844 NewFD->setInvalidDecl(); 7845 7846 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 7847 Diag(Loc, diag::err_duplicate_member) << II; 7848 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 7849 NewFD->setInvalidDecl(); 7850 } 7851 7852 if (!InvalidDecl && getLangOptions().CPlusPlus) { 7853 if (Record->isUnion()) { 7854 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 7855 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 7856 if (RDecl->getDefinition()) { 7857 // C++ [class.union]p1: An object of a class with a non-trivial 7858 // constructor, a non-trivial copy constructor, a non-trivial 7859 // destructor, or a non-trivial copy assignment operator 7860 // cannot be a member of a union, nor can an array of such 7861 // objects. 7862 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(NewFD)) 7863 NewFD->setInvalidDecl(); 7864 } 7865 } 7866 7867 // C++ [class.union]p1: If a union contains a member of reference type, 7868 // the program is ill-formed. 7869 if (EltTy->isReferenceType()) { 7870 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 7871 << NewFD->getDeclName() << EltTy; 7872 NewFD->setInvalidDecl(); 7873 } 7874 } 7875 } 7876 7877 // FIXME: We need to pass in the attributes given an AST 7878 // representation, not a parser representation. 7879 if (D) 7880 // FIXME: What to pass instead of TUScope? 7881 ProcessDeclAttributes(TUScope, NewFD, *D); 7882 7883 // In auto-retain/release, infer strong retension for fields of 7884 // retainable type. 7885 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 7886 NewFD->setInvalidDecl(); 7887 7888 if (T.isObjCGCWeak()) 7889 Diag(Loc, diag::warn_attribute_weak_on_field); 7890 7891 NewFD->setAccess(AS); 7892 return NewFD; 7893 } 7894 7895 bool Sema::CheckNontrivialField(FieldDecl *FD) { 7896 assert(FD); 7897 assert(getLangOptions().CPlusPlus && "valid check only for C++"); 7898 7899 if (FD->isInvalidDecl()) 7900 return true; 7901 7902 QualType EltTy = Context.getBaseElementType(FD->getType()); 7903 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 7904 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 7905 if (RDecl->getDefinition()) { 7906 // We check for copy constructors before constructors 7907 // because otherwise we'll never get complaints about 7908 // copy constructors. 7909 7910 CXXSpecialMember member = CXXInvalid; 7911 if (!RDecl->hasTrivialCopyConstructor()) 7912 member = CXXCopyConstructor; 7913 else if (!RDecl->hasTrivialDefaultConstructor()) 7914 member = CXXDefaultConstructor; 7915 else if (!RDecl->hasTrivialCopyAssignment()) 7916 member = CXXCopyAssignment; 7917 else if (!RDecl->hasTrivialDestructor()) 7918 member = CXXDestructor; 7919 7920 if (member != CXXInvalid) { 7921 if (getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) { 7922 // Objective-C++ ARC: it is an error to have a non-trivial field of 7923 // a union. However, system headers in Objective-C programs 7924 // occasionally have Objective-C lifetime objects within unions, 7925 // and rather than cause the program to fail, we make those 7926 // members unavailable. 7927 SourceLocation Loc = FD->getLocation(); 7928 if (getSourceManager().isInSystemHeader(Loc)) { 7929 if (!FD->hasAttr<UnavailableAttr>()) 7930 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 7931 "this system field has retaining ownership")); 7932 return false; 7933 } 7934 } 7935 7936 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member) 7937 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 7938 DiagnoseNontrivial(RT, member); 7939 return true; 7940 } 7941 } 7942 } 7943 7944 return false; 7945 } 7946 7947 /// DiagnoseNontrivial - Given that a class has a non-trivial 7948 /// special member, figure out why. 7949 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 7950 QualType QT(T, 0U); 7951 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 7952 7953 // Check whether the member was user-declared. 7954 switch (member) { 7955 case CXXInvalid: 7956 break; 7957 7958 case CXXDefaultConstructor: 7959 if (RD->hasUserDeclaredConstructor()) { 7960 typedef CXXRecordDecl::ctor_iterator ctor_iter; 7961 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 7962 const FunctionDecl *body = 0; 7963 ci->hasBody(body); 7964 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) { 7965 SourceLocation CtorLoc = ci->getLocation(); 7966 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 7967 return; 7968 } 7969 } 7970 7971 assert(0 && "found no user-declared constructors"); 7972 return; 7973 } 7974 break; 7975 7976 case CXXCopyConstructor: 7977 if (RD->hasUserDeclaredCopyConstructor()) { 7978 SourceLocation CtorLoc = 7979 RD->getCopyConstructor(0)->getLocation(); 7980 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 7981 return; 7982 } 7983 break; 7984 7985 case CXXMoveConstructor: 7986 if (RD->hasUserDeclaredMoveConstructor()) { 7987 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation(); 7988 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 7989 return; 7990 } 7991 break; 7992 7993 case CXXCopyAssignment: 7994 if (RD->hasUserDeclaredCopyAssignment()) { 7995 // FIXME: this should use the location of the copy 7996 // assignment, not the type. 7997 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 7998 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 7999 return; 8000 } 8001 break; 8002 8003 case CXXMoveAssignment: 8004 if (RD->hasUserDeclaredMoveAssignment()) { 8005 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation(); 8006 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 8007 return; 8008 } 8009 break; 8010 8011 case CXXDestructor: 8012 if (RD->hasUserDeclaredDestructor()) { 8013 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 8014 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8015 return; 8016 } 8017 break; 8018 } 8019 8020 typedef CXXRecordDecl::base_class_iterator base_iter; 8021 8022 // Virtual bases and members inhibit trivial copying/construction, 8023 // but not trivial destruction. 8024 if (member != CXXDestructor) { 8025 // Check for virtual bases. vbases includes indirect virtual bases, 8026 // so we just iterate through the direct bases. 8027 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 8028 if (bi->isVirtual()) { 8029 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8030 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 8031 return; 8032 } 8033 8034 // Check for virtual methods. 8035 typedef CXXRecordDecl::method_iterator meth_iter; 8036 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 8037 ++mi) { 8038 if (mi->isVirtual()) { 8039 SourceLocation MLoc = mi->getSourceRange().getBegin(); 8040 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 8041 return; 8042 } 8043 } 8044 } 8045 8046 bool (CXXRecordDecl::*hasTrivial)() const; 8047 switch (member) { 8048 case CXXDefaultConstructor: 8049 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break; 8050 case CXXCopyConstructor: 8051 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 8052 case CXXCopyAssignment: 8053 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 8054 case CXXDestructor: 8055 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 8056 default: 8057 assert(0 && "unexpected special member"); return; 8058 } 8059 8060 // Check for nontrivial bases (and recurse). 8061 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 8062 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 8063 assert(BaseRT && "Don't know how to handle dependent bases"); 8064 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 8065 if (!(BaseRecTy->*hasTrivial)()) { 8066 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8067 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 8068 DiagnoseNontrivial(BaseRT, member); 8069 return; 8070 } 8071 } 8072 8073 // Check for nontrivial members (and recurse). 8074 typedef RecordDecl::field_iterator field_iter; 8075 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 8076 ++fi) { 8077 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 8078 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 8079 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 8080 8081 if (!(EltRD->*hasTrivial)()) { 8082 SourceLocation FLoc = (*fi)->getLocation(); 8083 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 8084 DiagnoseNontrivial(EltRT, member); 8085 return; 8086 } 8087 } 8088 8089 if (EltTy->isObjCLifetimeType()) { 8090 switch (EltTy.getObjCLifetime()) { 8091 case Qualifiers::OCL_None: 8092 case Qualifiers::OCL_ExplicitNone: 8093 break; 8094 8095 case Qualifiers::OCL_Autoreleasing: 8096 case Qualifiers::OCL_Weak: 8097 case Qualifiers::OCL_Strong: 8098 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership) 8099 << QT << EltTy.getObjCLifetime(); 8100 return; 8101 } 8102 } 8103 } 8104 8105 assert(0 && "found no explanation for non-trivial member"); 8106 } 8107 8108 /// TranslateIvarVisibility - Translate visibility from a token ID to an 8109 /// AST enum value. 8110 static ObjCIvarDecl::AccessControl 8111 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 8112 switch (ivarVisibility) { 8113 default: assert(0 && "Unknown visitibility kind"); 8114 case tok::objc_private: return ObjCIvarDecl::Private; 8115 case tok::objc_public: return ObjCIvarDecl::Public; 8116 case tok::objc_protected: return ObjCIvarDecl::Protected; 8117 case tok::objc_package: return ObjCIvarDecl::Package; 8118 } 8119 } 8120 8121 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 8122 /// in order to create an IvarDecl object for it. 8123 Decl *Sema::ActOnIvar(Scope *S, 8124 SourceLocation DeclStart, 8125 Decl *IntfDecl, 8126 Declarator &D, ExprTy *BitfieldWidth, 8127 tok::ObjCKeywordKind Visibility) { 8128 8129 IdentifierInfo *II = D.getIdentifier(); 8130 Expr *BitWidth = (Expr*)BitfieldWidth; 8131 SourceLocation Loc = DeclStart; 8132 if (II) Loc = D.getIdentifierLoc(); 8133 8134 // FIXME: Unnamed fields can be handled in various different ways, for 8135 // example, unnamed unions inject all members into the struct namespace! 8136 8137 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8138 QualType T = TInfo->getType(); 8139 8140 if (BitWidth) { 8141 // 6.7.2.1p3, 6.7.2.1p4 8142 if (VerifyBitField(Loc, II, T, BitWidth)) { 8143 D.setInvalidType(); 8144 BitWidth = 0; 8145 } 8146 } else { 8147 // Not a bitfield. 8148 8149 // validate II. 8150 8151 } 8152 if (T->isReferenceType()) { 8153 Diag(Loc, diag::err_ivar_reference_type); 8154 D.setInvalidType(); 8155 } 8156 // C99 6.7.2.1p8: A member of a structure or union may have any type other 8157 // than a variably modified type. 8158 else if (T->isVariablyModifiedType()) { 8159 Diag(Loc, diag::err_typecheck_ivar_variable_size); 8160 D.setInvalidType(); 8161 } 8162 8163 // Get the visibility (access control) for this ivar. 8164 ObjCIvarDecl::AccessControl ac = 8165 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 8166 : ObjCIvarDecl::None; 8167 // Must set ivar's DeclContext to its enclosing interface. 8168 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl); 8169 ObjCContainerDecl *EnclosingContext; 8170 if (ObjCImplementationDecl *IMPDecl = 8171 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 8172 if (!LangOpts.ObjCNonFragileABI2) { 8173 // Case of ivar declared in an implementation. Context is that of its class. 8174 EnclosingContext = IMPDecl->getClassInterface(); 8175 assert(EnclosingContext && "Implementation has no class interface!"); 8176 } 8177 else 8178 EnclosingContext = EnclosingDecl; 8179 } else { 8180 if (ObjCCategoryDecl *CDecl = 8181 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8182 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 8183 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 8184 return 0; 8185 } 8186 } 8187 EnclosingContext = EnclosingDecl; 8188 } 8189 8190 // Construct the decl. 8191 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 8192 DeclStart, Loc, II, T, 8193 TInfo, ac, (Expr *)BitfieldWidth); 8194 8195 if (II) { 8196 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 8197 ForRedeclaration); 8198 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 8199 && !isa<TagDecl>(PrevDecl)) { 8200 Diag(Loc, diag::err_duplicate_member) << II; 8201 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8202 NewID->setInvalidDecl(); 8203 } 8204 } 8205 8206 // Process attributes attached to the ivar. 8207 ProcessDeclAttributes(S, NewID, D); 8208 8209 if (D.isInvalidType()) 8210 NewID->setInvalidDecl(); 8211 8212 // In ARC, infer 'retaining' for ivars of retainable type. 8213 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 8214 NewID->setInvalidDecl(); 8215 8216 if (II) { 8217 // FIXME: When interfaces are DeclContexts, we'll need to add 8218 // these to the interface. 8219 S->AddDecl(NewID); 8220 IdResolver.AddDecl(NewID); 8221 } 8222 8223 return NewID; 8224 } 8225 8226 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 8227 /// class and class extensions. For every class @interface and class 8228 /// extension @interface, if the last ivar is a bitfield of any type, 8229 /// then add an implicit `char :0` ivar to the end of that interface. 8230 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl, 8231 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) { 8232 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty()) 8233 return; 8234 8235 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 8236 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 8237 8238 if (!Ivar->isBitField()) 8239 return; 8240 uint64_t BitFieldSize = 8241 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue(); 8242 if (BitFieldSize == 0) 8243 return; 8244 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl); 8245 if (!ID) { 8246 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8247 if (!CD->IsClassExtension()) 8248 return; 8249 } 8250 // No need to add this to end of @implementation. 8251 else 8252 return; 8253 } 8254 // All conditions are met. Add a new bitfield to the tail end of ivars. 8255 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0); 8256 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc); 8257 8258 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl), 8259 DeclLoc, DeclLoc, 0, 8260 Context.CharTy, 8261 Context.CreateTypeSourceInfo(Context.CharTy), 8262 ObjCIvarDecl::Private, BW, 8263 true); 8264 AllIvarDecls.push_back(Ivar); 8265 } 8266 8267 void Sema::ActOnFields(Scope* S, 8268 SourceLocation RecLoc, Decl *EnclosingDecl, 8269 Decl **Fields, unsigned NumFields, 8270 SourceLocation LBrac, SourceLocation RBrac, 8271 AttributeList *Attr) { 8272 assert(EnclosingDecl && "missing record or interface decl"); 8273 8274 // If the decl this is being inserted into is invalid, then it may be a 8275 // redeclaration or some other bogus case. Don't try to add fields to it. 8276 if (EnclosingDecl->isInvalidDecl()) { 8277 // FIXME: Deallocate fields? 8278 return; 8279 } 8280 8281 8282 // Verify that all the fields are okay. 8283 unsigned NumNamedMembers = 0; 8284 llvm::SmallVector<FieldDecl*, 32> RecFields; 8285 8286 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 8287 bool ARCErrReported = false; 8288 for (unsigned i = 0; i != NumFields; ++i) { 8289 FieldDecl *FD = cast<FieldDecl>(Fields[i]); 8290 8291 // Get the type for the field. 8292 const Type *FDTy = FD->getType().getTypePtr(); 8293 8294 if (!FD->isAnonymousStructOrUnion()) { 8295 // Remember all fields written by the user. 8296 RecFields.push_back(FD); 8297 } 8298 8299 // If the field is already invalid for some reason, don't emit more 8300 // diagnostics about it. 8301 if (FD->isInvalidDecl()) { 8302 EnclosingDecl->setInvalidDecl(); 8303 continue; 8304 } 8305 8306 // C99 6.7.2.1p2: 8307 // A structure or union shall not contain a member with 8308 // incomplete or function type (hence, a structure shall not 8309 // contain an instance of itself, but may contain a pointer to 8310 // an instance of itself), except that the last member of a 8311 // structure with more than one named member may have incomplete 8312 // array type; such a structure (and any union containing, 8313 // possibly recursively, a member that is such a structure) 8314 // shall not be a member of a structure or an element of an 8315 // array. 8316 if (FDTy->isFunctionType()) { 8317 // Field declared as a function. 8318 Diag(FD->getLocation(), diag::err_field_declared_as_function) 8319 << FD->getDeclName(); 8320 FD->setInvalidDecl(); 8321 EnclosingDecl->setInvalidDecl(); 8322 continue; 8323 } else if (FDTy->isIncompleteArrayType() && Record && 8324 ((i == NumFields - 1 && !Record->isUnion()) || 8325 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) && 8326 (i == NumFields - 1 || Record->isUnion())))) { 8327 // Flexible array member. 8328 // Microsoft and g++ is more permissive regarding flexible array. 8329 // It will accept flexible array in union and also 8330 // as the sole element of a struct/class. 8331 if (getLangOptions().Microsoft) { 8332 if (Record->isUnion()) 8333 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 8334 << FD->getDeclName(); 8335 else if (NumFields == 1) 8336 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 8337 << FD->getDeclName() << Record->getTagKind(); 8338 } else if (getLangOptions().CPlusPlus) { 8339 if (Record->isUnion()) 8340 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 8341 << FD->getDeclName(); 8342 else if (NumFields == 1) 8343 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 8344 << FD->getDeclName() << Record->getTagKind(); 8345 } else if (NumNamedMembers < 1) { 8346 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 8347 << FD->getDeclName(); 8348 FD->setInvalidDecl(); 8349 EnclosingDecl->setInvalidDecl(); 8350 continue; 8351 } 8352 if (!FD->getType()->isDependentType() && 8353 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 8354 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 8355 << FD->getDeclName() << FD->getType(); 8356 FD->setInvalidDecl(); 8357 EnclosingDecl->setInvalidDecl(); 8358 continue; 8359 } 8360 // Okay, we have a legal flexible array member at the end of the struct. 8361 if (Record) 8362 Record->setHasFlexibleArrayMember(true); 8363 } else if (!FDTy->isDependentType() && 8364 RequireCompleteType(FD->getLocation(), FD->getType(), 8365 diag::err_field_incomplete)) { 8366 // Incomplete type 8367 FD->setInvalidDecl(); 8368 EnclosingDecl->setInvalidDecl(); 8369 continue; 8370 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 8371 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 8372 // If this is a member of a union, then entire union becomes "flexible". 8373 if (Record && Record->isUnion()) { 8374 Record->setHasFlexibleArrayMember(true); 8375 } else { 8376 // If this is a struct/class and this is not the last element, reject 8377 // it. Note that GCC supports variable sized arrays in the middle of 8378 // structures. 8379 if (i != NumFields-1) 8380 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 8381 << FD->getDeclName() << FD->getType(); 8382 else { 8383 // We support flexible arrays at the end of structs in 8384 // other structs as an extension. 8385 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 8386 << FD->getDeclName(); 8387 if (Record) 8388 Record->setHasFlexibleArrayMember(true); 8389 } 8390 } 8391 } 8392 if (Record && FDTTy->getDecl()->hasObjectMember()) 8393 Record->setHasObjectMember(true); 8394 } else if (FDTy->isObjCObjectType()) { 8395 /// A field cannot be an Objective-c object 8396 Diag(FD->getLocation(), diag::err_statically_allocated_object); 8397 FD->setInvalidDecl(); 8398 EnclosingDecl->setInvalidDecl(); 8399 continue; 8400 } 8401 else if (!getLangOptions().CPlusPlus) { 8402 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) { 8403 // It's an error in ARC if a field has lifetime. 8404 // We don't want to report this in a system header, though, 8405 // so we just make the field unavailable. 8406 // FIXME: that's really not sufficient; we need to make the type 8407 // itself invalid to, say, initialize or copy. 8408 QualType T = FD->getType(); 8409 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 8410 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 8411 SourceLocation loc = FD->getLocation(); 8412 if (getSourceManager().isInSystemHeader(loc)) { 8413 if (!FD->hasAttr<UnavailableAttr>()) { 8414 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 8415 "this system field has retaining ownership")); 8416 } 8417 } else { 8418 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct); 8419 } 8420 ARCErrReported = true; 8421 } 8422 } 8423 else if (getLangOptions().ObjC1 && 8424 getLangOptions().getGCMode() != LangOptions::NonGC && 8425 Record && !Record->hasObjectMember()) { 8426 if (FD->getType()->isObjCObjectPointerType() || 8427 FD->getType().isObjCGCStrong()) 8428 Record->setHasObjectMember(true); 8429 else if (Context.getAsArrayType(FD->getType())) { 8430 QualType BaseType = Context.getBaseElementType(FD->getType()); 8431 if (BaseType->isRecordType() && 8432 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 8433 Record->setHasObjectMember(true); 8434 else if (BaseType->isObjCObjectPointerType() || 8435 BaseType.isObjCGCStrong()) 8436 Record->setHasObjectMember(true); 8437 } 8438 } 8439 } 8440 // Keep track of the number of named members. 8441 if (FD->getIdentifier()) 8442 ++NumNamedMembers; 8443 } 8444 8445 // Okay, we successfully defined 'Record'. 8446 if (Record) { 8447 bool Completed = false; 8448 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 8449 if (!CXXRecord->isInvalidDecl()) { 8450 // Set access bits correctly on the directly-declared conversions. 8451 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions(); 8452 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 8453 I != E; ++I) 8454 Convs->setAccess(I, (*I)->getAccess()); 8455 8456 if (!CXXRecord->isDependentType()) { 8457 // Objective-C Automatic Reference Counting: 8458 // If a class has a non-static data member of Objective-C pointer 8459 // type (or array thereof), it is a non-POD type and its 8460 // default constructor (if any), copy constructor, copy assignment 8461 // operator, and destructor are non-trivial. 8462 // 8463 // This rule is also handled by CXXRecordDecl::completeDefinition(). 8464 // However, here we check whether this particular class is only 8465 // non-POD because of the presence of an Objective-C pointer member. 8466 // If so, objects of this type cannot be shared between code compiled 8467 // with instant objects and code compiled with manual retain/release. 8468 if (getLangOptions().ObjCAutoRefCount && 8469 CXXRecord->hasObjectMember() && 8470 CXXRecord->getLinkage() == ExternalLinkage) { 8471 if (CXXRecord->isPOD()) { 8472 Diag(CXXRecord->getLocation(), 8473 diag::warn_arc_non_pod_class_with_object_member) 8474 << CXXRecord; 8475 } else { 8476 // FIXME: Fix-Its would be nice here, but finding a good location 8477 // for them is going to be tricky. 8478 if (CXXRecord->hasTrivialCopyConstructor()) 8479 Diag(CXXRecord->getLocation(), 8480 diag::warn_arc_trivial_member_function_with_object_member) 8481 << CXXRecord << 0; 8482 if (CXXRecord->hasTrivialCopyAssignment()) 8483 Diag(CXXRecord->getLocation(), 8484 diag::warn_arc_trivial_member_function_with_object_member) 8485 << CXXRecord << 1; 8486 if (CXXRecord->hasTrivialDestructor()) 8487 Diag(CXXRecord->getLocation(), 8488 diag::warn_arc_trivial_member_function_with_object_member) 8489 << CXXRecord << 2; 8490 } 8491 } 8492 8493 // Adjust user-defined destructor exception spec. 8494 if (getLangOptions().CPlusPlus0x && 8495 CXXRecord->hasUserDeclaredDestructor()) 8496 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 8497 8498 // Add any implicitly-declared members to this class. 8499 AddImplicitlyDeclaredMembersToClass(CXXRecord); 8500 8501 // If we have virtual base classes, we may end up finding multiple 8502 // final overriders for a given virtual function. Check for this 8503 // problem now. 8504 if (CXXRecord->getNumVBases()) { 8505 CXXFinalOverriderMap FinalOverriders; 8506 CXXRecord->getFinalOverriders(FinalOverriders); 8507 8508 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 8509 MEnd = FinalOverriders.end(); 8510 M != MEnd; ++M) { 8511 for (OverridingMethods::iterator SO = M->second.begin(), 8512 SOEnd = M->second.end(); 8513 SO != SOEnd; ++SO) { 8514 assert(SO->second.size() > 0 && 8515 "Virtual function without overridding functions?"); 8516 if (SO->second.size() == 1) 8517 continue; 8518 8519 // C++ [class.virtual]p2: 8520 // In a derived class, if a virtual member function of a base 8521 // class subobject has more than one final overrider the 8522 // program is ill-formed. 8523 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 8524 << (NamedDecl *)M->first << Record; 8525 Diag(M->first->getLocation(), 8526 diag::note_overridden_virtual_function); 8527 for (OverridingMethods::overriding_iterator 8528 OM = SO->second.begin(), 8529 OMEnd = SO->second.end(); 8530 OM != OMEnd; ++OM) 8531 Diag(OM->Method->getLocation(), diag::note_final_overrider) 8532 << (NamedDecl *)M->first << OM->Method->getParent(); 8533 8534 Record->setInvalidDecl(); 8535 } 8536 } 8537 CXXRecord->completeDefinition(&FinalOverriders); 8538 Completed = true; 8539 } 8540 } 8541 } 8542 } 8543 8544 if (!Completed) 8545 Record->completeDefinition(); 8546 8547 // Now that the record is complete, do any delayed exception spec checks 8548 // we were missing. 8549 while (!DelayedDestructorExceptionSpecChecks.empty()) { 8550 const CXXDestructorDecl *Dtor = 8551 DelayedDestructorExceptionSpecChecks.back().first; 8552 if (Dtor->getParent() != Record) 8553 break; 8554 8555 assert(!Dtor->getParent()->isDependentType() && 8556 "Should not ever add destructors of templates into the list."); 8557 CheckOverridingFunctionExceptionSpec(Dtor, 8558 DelayedDestructorExceptionSpecChecks.back().second); 8559 DelayedDestructorExceptionSpecChecks.pop_back(); 8560 } 8561 8562 } else { 8563 ObjCIvarDecl **ClsFields = 8564 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 8565 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 8566 ID->setLocEnd(RBrac); 8567 // Add ivar's to class's DeclContext. 8568 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 8569 ClsFields[i]->setLexicalDeclContext(ID); 8570 ID->addDecl(ClsFields[i]); 8571 } 8572 // Must enforce the rule that ivars in the base classes may not be 8573 // duplicates. 8574 if (ID->getSuperClass()) 8575 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 8576 } else if (ObjCImplementationDecl *IMPDecl = 8577 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 8578 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 8579 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 8580 // Ivar declared in @implementation never belongs to the implementation. 8581 // Only it is in implementation's lexical context. 8582 ClsFields[I]->setLexicalDeclContext(IMPDecl); 8583 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 8584 } else if (ObjCCategoryDecl *CDecl = 8585 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8586 // case of ivars in class extension; all other cases have been 8587 // reported as errors elsewhere. 8588 // FIXME. Class extension does not have a LocEnd field. 8589 // CDecl->setLocEnd(RBrac); 8590 // Add ivar's to class extension's DeclContext. 8591 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 8592 ClsFields[i]->setLexicalDeclContext(CDecl); 8593 CDecl->addDecl(ClsFields[i]); 8594 } 8595 } 8596 } 8597 8598 if (Attr) 8599 ProcessDeclAttributeList(S, Record, Attr); 8600 8601 // If there's a #pragma GCC visibility in scope, and this isn't a subclass, 8602 // set the visibility of this record. 8603 if (Record && !Record->getDeclContext()->isRecord()) 8604 AddPushedVisibilityAttribute(Record); 8605 } 8606 8607 /// \brief Determine whether the given integral value is representable within 8608 /// the given type T. 8609 static bool isRepresentableIntegerValue(ASTContext &Context, 8610 llvm::APSInt &Value, 8611 QualType T) { 8612 assert(T->isIntegralType(Context) && "Integral type required!"); 8613 unsigned BitWidth = Context.getIntWidth(T); 8614 8615 if (Value.isUnsigned() || Value.isNonNegative()) { 8616 if (T->isSignedIntegerOrEnumerationType()) 8617 --BitWidth; 8618 return Value.getActiveBits() <= BitWidth; 8619 } 8620 return Value.getMinSignedBits() <= BitWidth; 8621 } 8622 8623 // \brief Given an integral type, return the next larger integral type 8624 // (or a NULL type of no such type exists). 8625 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 8626 // FIXME: Int128/UInt128 support, which also needs to be introduced into 8627 // enum checking below. 8628 assert(T->isIntegralType(Context) && "Integral type required!"); 8629 const unsigned NumTypes = 4; 8630 QualType SignedIntegralTypes[NumTypes] = { 8631 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 8632 }; 8633 QualType UnsignedIntegralTypes[NumTypes] = { 8634 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 8635 Context.UnsignedLongLongTy 8636 }; 8637 8638 unsigned BitWidth = Context.getTypeSize(T); 8639 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 8640 : UnsignedIntegralTypes; 8641 for (unsigned I = 0; I != NumTypes; ++I) 8642 if (Context.getTypeSize(Types[I]) > BitWidth) 8643 return Types[I]; 8644 8645 return QualType(); 8646 } 8647 8648 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 8649 EnumConstantDecl *LastEnumConst, 8650 SourceLocation IdLoc, 8651 IdentifierInfo *Id, 8652 Expr *Val) { 8653 unsigned IntWidth = Context.Target.getIntWidth(); 8654 llvm::APSInt EnumVal(IntWidth); 8655 QualType EltTy; 8656 8657 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 8658 Val = 0; 8659 8660 if (Val) { 8661 if (Enum->isDependentType() || Val->isTypeDependent()) 8662 EltTy = Context.DependentTy; 8663 else { 8664 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 8665 SourceLocation ExpLoc; 8666 if (!Val->isValueDependent() && 8667 VerifyIntegerConstantExpression(Val, &EnumVal)) { 8668 Val = 0; 8669 } else { 8670 if (!getLangOptions().CPlusPlus) { 8671 // C99 6.7.2.2p2: 8672 // The expression that defines the value of an enumeration constant 8673 // shall be an integer constant expression that has a value 8674 // representable as an int. 8675 8676 // Complain if the value is not representable in an int. 8677 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 8678 Diag(IdLoc, diag::ext_enum_value_not_int) 8679 << EnumVal.toString(10) << Val->getSourceRange() 8680 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 8681 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 8682 // Force the type of the expression to 'int'. 8683 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 8684 } 8685 } 8686 8687 if (Enum->isFixed()) { 8688 EltTy = Enum->getIntegerType(); 8689 8690 // C++0x [dcl.enum]p5: 8691 // ... if the initializing value of an enumerator cannot be 8692 // represented by the underlying type, the program is ill-formed. 8693 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 8694 if (getLangOptions().Microsoft) { 8695 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 8696 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 8697 } else 8698 Diag(IdLoc, diag::err_enumerator_too_large) 8699 << EltTy; 8700 } else 8701 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 8702 } 8703 else { 8704 // C++0x [dcl.enum]p5: 8705 // If the underlying type is not fixed, the type of each enumerator 8706 // is the type of its initializing value: 8707 // - If an initializer is specified for an enumerator, the 8708 // initializing value has the same type as the expression. 8709 EltTy = Val->getType(); 8710 } 8711 } 8712 } 8713 } 8714 8715 if (!Val) { 8716 if (Enum->isDependentType()) 8717 EltTy = Context.DependentTy; 8718 else if (!LastEnumConst) { 8719 // C++0x [dcl.enum]p5: 8720 // If the underlying type is not fixed, the type of each enumerator 8721 // is the type of its initializing value: 8722 // - If no initializer is specified for the first enumerator, the 8723 // initializing value has an unspecified integral type. 8724 // 8725 // GCC uses 'int' for its unspecified integral type, as does 8726 // C99 6.7.2.2p3. 8727 if (Enum->isFixed()) { 8728 EltTy = Enum->getIntegerType(); 8729 } 8730 else { 8731 EltTy = Context.IntTy; 8732 } 8733 } else { 8734 // Assign the last value + 1. 8735 EnumVal = LastEnumConst->getInitVal(); 8736 ++EnumVal; 8737 EltTy = LastEnumConst->getType(); 8738 8739 // Check for overflow on increment. 8740 if (EnumVal < LastEnumConst->getInitVal()) { 8741 // C++0x [dcl.enum]p5: 8742 // If the underlying type is not fixed, the type of each enumerator 8743 // is the type of its initializing value: 8744 // 8745 // - Otherwise the type of the initializing value is the same as 8746 // the type of the initializing value of the preceding enumerator 8747 // unless the incremented value is not representable in that type, 8748 // in which case the type is an unspecified integral type 8749 // sufficient to contain the incremented value. If no such type 8750 // exists, the program is ill-formed. 8751 QualType T = getNextLargerIntegralType(Context, EltTy); 8752 if (T.isNull() || Enum->isFixed()) { 8753 // There is no integral type larger enough to represent this 8754 // value. Complain, then allow the value to wrap around. 8755 EnumVal = LastEnumConst->getInitVal(); 8756 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 8757 ++EnumVal; 8758 if (Enum->isFixed()) 8759 // When the underlying type is fixed, this is ill-formed. 8760 Diag(IdLoc, diag::err_enumerator_wrapped) 8761 << EnumVal.toString(10) 8762 << EltTy; 8763 else 8764 Diag(IdLoc, diag::warn_enumerator_too_large) 8765 << EnumVal.toString(10); 8766 } else { 8767 EltTy = T; 8768 } 8769 8770 // Retrieve the last enumerator's value, extent that type to the 8771 // type that is supposed to be large enough to represent the incremented 8772 // value, then increment. 8773 EnumVal = LastEnumConst->getInitVal(); 8774 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 8775 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 8776 ++EnumVal; 8777 8778 // If we're not in C++, diagnose the overflow of enumerator values, 8779 // which in C99 means that the enumerator value is not representable in 8780 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 8781 // permits enumerator values that are representable in some larger 8782 // integral type. 8783 if (!getLangOptions().CPlusPlus && !T.isNull()) 8784 Diag(IdLoc, diag::warn_enum_value_overflow); 8785 } else if (!getLangOptions().CPlusPlus && 8786 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 8787 // Enforce C99 6.7.2.2p2 even when we compute the next value. 8788 Diag(IdLoc, diag::ext_enum_value_not_int) 8789 << EnumVal.toString(10) << 1; 8790 } 8791 } 8792 } 8793 8794 if (!EltTy->isDependentType()) { 8795 // Make the enumerator value match the signedness and size of the 8796 // enumerator's type. 8797 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 8798 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 8799 } 8800 8801 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 8802 Val, EnumVal); 8803 } 8804 8805 8806 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 8807 SourceLocation IdLoc, IdentifierInfo *Id, 8808 AttributeList *Attr, 8809 SourceLocation EqualLoc, ExprTy *val) { 8810 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 8811 EnumConstantDecl *LastEnumConst = 8812 cast_or_null<EnumConstantDecl>(lastEnumConst); 8813 Expr *Val = static_cast<Expr*>(val); 8814 8815 // The scope passed in may not be a decl scope. Zip up the scope tree until 8816 // we find one that is. 8817 S = getNonFieldDeclScope(S); 8818 8819 // Verify that there isn't already something declared with this name in this 8820 // scope. 8821 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 8822 ForRedeclaration); 8823 if (PrevDecl && PrevDecl->isTemplateParameter()) { 8824 // Maybe we will complain about the shadowed template parameter. 8825 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 8826 // Just pretend that we didn't see the previous declaration. 8827 PrevDecl = 0; 8828 } 8829 8830 if (PrevDecl) { 8831 // When in C++, we may get a TagDecl with the same name; in this case the 8832 // enum constant will 'hide' the tag. 8833 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 8834 "Received TagDecl when not in C++!"); 8835 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 8836 if (isa<EnumConstantDecl>(PrevDecl)) 8837 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 8838 else 8839 Diag(IdLoc, diag::err_redefinition) << Id; 8840 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8841 return 0; 8842 } 8843 } 8844 8845 // C++ [class.mem]p13: 8846 // If T is the name of a class, then each of the following shall have a 8847 // name different from T: 8848 // - every enumerator of every member of class T that is an enumerated 8849 // type 8850 if (CXXRecordDecl *Record 8851 = dyn_cast<CXXRecordDecl>( 8852 TheEnumDecl->getDeclContext()->getRedeclContext())) 8853 if (Record->getIdentifier() && Record->getIdentifier() == Id) 8854 Diag(IdLoc, diag::err_member_name_of_class) << Id; 8855 8856 EnumConstantDecl *New = 8857 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 8858 8859 if (New) { 8860 // Process attributes. 8861 if (Attr) ProcessDeclAttributeList(S, New, Attr); 8862 8863 // Register this decl in the current scope stack. 8864 New->setAccess(TheEnumDecl->getAccess()); 8865 PushOnScopeChains(New, S); 8866 } 8867 8868 return New; 8869 } 8870 8871 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 8872 SourceLocation RBraceLoc, Decl *EnumDeclX, 8873 Decl **Elements, unsigned NumElements, 8874 Scope *S, AttributeList *Attr) { 8875 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 8876 QualType EnumType = Context.getTypeDeclType(Enum); 8877 8878 if (Attr) 8879 ProcessDeclAttributeList(S, Enum, Attr); 8880 8881 if (Enum->isDependentType()) { 8882 for (unsigned i = 0; i != NumElements; ++i) { 8883 EnumConstantDecl *ECD = 8884 cast_or_null<EnumConstantDecl>(Elements[i]); 8885 if (!ECD) continue; 8886 8887 ECD->setType(EnumType); 8888 } 8889 8890 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 8891 return; 8892 } 8893 8894 // TODO: If the result value doesn't fit in an int, it must be a long or long 8895 // long value. ISO C does not support this, but GCC does as an extension, 8896 // emit a warning. 8897 unsigned IntWidth = Context.Target.getIntWidth(); 8898 unsigned CharWidth = Context.Target.getCharWidth(); 8899 unsigned ShortWidth = Context.Target.getShortWidth(); 8900 8901 // Verify that all the values are okay, compute the size of the values, and 8902 // reverse the list. 8903 unsigned NumNegativeBits = 0; 8904 unsigned NumPositiveBits = 0; 8905 8906 // Keep track of whether all elements have type int. 8907 bool AllElementsInt = true; 8908 8909 for (unsigned i = 0; i != NumElements; ++i) { 8910 EnumConstantDecl *ECD = 8911 cast_or_null<EnumConstantDecl>(Elements[i]); 8912 if (!ECD) continue; // Already issued a diagnostic. 8913 8914 const llvm::APSInt &InitVal = ECD->getInitVal(); 8915 8916 // Keep track of the size of positive and negative values. 8917 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 8918 NumPositiveBits = std::max(NumPositiveBits, 8919 (unsigned)InitVal.getActiveBits()); 8920 else 8921 NumNegativeBits = std::max(NumNegativeBits, 8922 (unsigned)InitVal.getMinSignedBits()); 8923 8924 // Keep track of whether every enum element has type int (very commmon). 8925 if (AllElementsInt) 8926 AllElementsInt = ECD->getType() == Context.IntTy; 8927 } 8928 8929 // Figure out the type that should be used for this enum. 8930 QualType BestType; 8931 unsigned BestWidth; 8932 8933 // C++0x N3000 [conv.prom]p3: 8934 // An rvalue of an unscoped enumeration type whose underlying 8935 // type is not fixed can be converted to an rvalue of the first 8936 // of the following types that can represent all the values of 8937 // the enumeration: int, unsigned int, long int, unsigned long 8938 // int, long long int, or unsigned long long int. 8939 // C99 6.4.4.3p2: 8940 // An identifier declared as an enumeration constant has type int. 8941 // The C99 rule is modified by a gcc extension 8942 QualType BestPromotionType; 8943 8944 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 8945 // -fshort-enums is the equivalent to specifying the packed attribute on all 8946 // enum definitions. 8947 if (LangOpts.ShortEnums) 8948 Packed = true; 8949 8950 if (Enum->isFixed()) { 8951 BestType = BestPromotionType = Enum->getIntegerType(); 8952 // We don't need to set BestWidth, because BestType is going to be the type 8953 // of the enumerators, but we do anyway because otherwise some compilers 8954 // warn that it might be used uninitialized. 8955 BestWidth = CharWidth; 8956 } 8957 else if (NumNegativeBits) { 8958 // If there is a negative value, figure out the smallest integer type (of 8959 // int/long/longlong) that fits. 8960 // If it's packed, check also if it fits a char or a short. 8961 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 8962 BestType = Context.SignedCharTy; 8963 BestWidth = CharWidth; 8964 } else if (Packed && NumNegativeBits <= ShortWidth && 8965 NumPositiveBits < ShortWidth) { 8966 BestType = Context.ShortTy; 8967 BestWidth = ShortWidth; 8968 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 8969 BestType = Context.IntTy; 8970 BestWidth = IntWidth; 8971 } else { 8972 BestWidth = Context.Target.getLongWidth(); 8973 8974 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 8975 BestType = Context.LongTy; 8976 } else { 8977 BestWidth = Context.Target.getLongLongWidth(); 8978 8979 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 8980 Diag(Enum->getLocation(), diag::warn_enum_too_large); 8981 BestType = Context.LongLongTy; 8982 } 8983 } 8984 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 8985 } else { 8986 // If there is no negative value, figure out the smallest type that fits 8987 // all of the enumerator values. 8988 // If it's packed, check also if it fits a char or a short. 8989 if (Packed && NumPositiveBits <= CharWidth) { 8990 BestType = Context.UnsignedCharTy; 8991 BestPromotionType = Context.IntTy; 8992 BestWidth = CharWidth; 8993 } else if (Packed && NumPositiveBits <= ShortWidth) { 8994 BestType = Context.UnsignedShortTy; 8995 BestPromotionType = Context.IntTy; 8996 BestWidth = ShortWidth; 8997 } else if (NumPositiveBits <= IntWidth) { 8998 BestType = Context.UnsignedIntTy; 8999 BestWidth = IntWidth; 9000 BestPromotionType 9001 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9002 ? Context.UnsignedIntTy : Context.IntTy; 9003 } else if (NumPositiveBits <= 9004 (BestWidth = Context.Target.getLongWidth())) { 9005 BestType = Context.UnsignedLongTy; 9006 BestPromotionType 9007 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9008 ? Context.UnsignedLongTy : Context.LongTy; 9009 } else { 9010 BestWidth = Context.Target.getLongLongWidth(); 9011 assert(NumPositiveBits <= BestWidth && 9012 "How could an initializer get larger than ULL?"); 9013 BestType = Context.UnsignedLongLongTy; 9014 BestPromotionType 9015 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9016 ? Context.UnsignedLongLongTy : Context.LongLongTy; 9017 } 9018 } 9019 9020 // Loop over all of the enumerator constants, changing their types to match 9021 // the type of the enum if needed. 9022 for (unsigned i = 0; i != NumElements; ++i) { 9023 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 9024 if (!ECD) continue; // Already issued a diagnostic. 9025 9026 // Standard C says the enumerators have int type, but we allow, as an 9027 // extension, the enumerators to be larger than int size. If each 9028 // enumerator value fits in an int, type it as an int, otherwise type it the 9029 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 9030 // that X has type 'int', not 'unsigned'. 9031 9032 // Determine whether the value fits into an int. 9033 llvm::APSInt InitVal = ECD->getInitVal(); 9034 9035 // If it fits into an integer type, force it. Otherwise force it to match 9036 // the enum decl type. 9037 QualType NewTy; 9038 unsigned NewWidth; 9039 bool NewSign; 9040 if (!getLangOptions().CPlusPlus && 9041 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 9042 NewTy = Context.IntTy; 9043 NewWidth = IntWidth; 9044 NewSign = true; 9045 } else if (ECD->getType() == BestType) { 9046 // Already the right type! 9047 if (getLangOptions().CPlusPlus) 9048 // C++ [dcl.enum]p4: Following the closing brace of an 9049 // enum-specifier, each enumerator has the type of its 9050 // enumeration. 9051 ECD->setType(EnumType); 9052 continue; 9053 } else { 9054 NewTy = BestType; 9055 NewWidth = BestWidth; 9056 NewSign = BestType->isSignedIntegerOrEnumerationType(); 9057 } 9058 9059 // Adjust the APSInt value. 9060 InitVal = InitVal.extOrTrunc(NewWidth); 9061 InitVal.setIsSigned(NewSign); 9062 ECD->setInitVal(InitVal); 9063 9064 // Adjust the Expr initializer and type. 9065 if (ECD->getInitExpr() && 9066 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 9067 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 9068 CK_IntegralCast, 9069 ECD->getInitExpr(), 9070 /*base paths*/ 0, 9071 VK_RValue)); 9072 if (getLangOptions().CPlusPlus) 9073 // C++ [dcl.enum]p4: Following the closing brace of an 9074 // enum-specifier, each enumerator has the type of its 9075 // enumeration. 9076 ECD->setType(EnumType); 9077 else 9078 ECD->setType(NewTy); 9079 } 9080 9081 Enum->completeDefinition(BestType, BestPromotionType, 9082 NumPositiveBits, NumNegativeBits); 9083 } 9084 9085 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 9086 SourceLocation StartLoc, 9087 SourceLocation EndLoc) { 9088 StringLiteral *AsmString = cast<StringLiteral>(expr); 9089 9090 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 9091 AsmString, StartLoc, 9092 EndLoc); 9093 CurContext->addDecl(New); 9094 return New; 9095 } 9096 9097 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 9098 SourceLocation PragmaLoc, 9099 SourceLocation NameLoc) { 9100 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 9101 9102 if (PrevDecl) { 9103 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 9104 } else { 9105 (void)WeakUndeclaredIdentifiers.insert( 9106 std::pair<IdentifierInfo*,WeakInfo> 9107 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 9108 } 9109 } 9110 9111 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 9112 IdentifierInfo* AliasName, 9113 SourceLocation PragmaLoc, 9114 SourceLocation NameLoc, 9115 SourceLocation AliasNameLoc) { 9116 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 9117 LookupOrdinaryName); 9118 WeakInfo W = WeakInfo(Name, NameLoc); 9119 9120 if (PrevDecl) { 9121 if (!PrevDecl->hasAttr<AliasAttr>()) 9122 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 9123 DeclApplyPragmaWeak(TUScope, ND, W); 9124 } else { 9125 (void)WeakUndeclaredIdentifiers.insert( 9126 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 9127 } 9128 } 9129