SemaDecl.cpp revision 7b1fdbda2757cc4a7f25664475be44119d7f8e59
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 "Sema.h" 15#include "SemaInherit.h" 16#include "clang/AST/APValue.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/Analysis/CFG.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/DeclTemplate.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/StmtCXX.h" 24#include "clang/AST/StmtObjC.h" 25#include "clang/Parse/DeclSpec.h" 26#include "clang/Basic/TargetInfo.h" 27#include "clang/Basic/SourceManager.h" 28// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 29#include "clang/Lex/Preprocessor.h" 30#include "clang/Lex/HeaderSearch.h" 31#include "llvm/ADT/BitVector.h" 32#include "llvm/ADT/SmallSet.h" 33#include "llvm/ADT/STLExtras.h" 34#include <algorithm> 35#include <functional> 36#include <queue> 37using namespace clang; 38 39/// getDeclName - Return a pretty name for the specified decl if possible, or 40/// an empty string if not. This is used for pretty crash reporting. 41std::string Sema::getDeclName(DeclPtrTy d) { 42 Decl *D = d.getAs<Decl>(); 43 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D)) 44 return DN->getQualifiedNameAsString(); 45 return ""; 46} 47 48Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) { 49 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>())); 50} 51 52/// \brief If the identifier refers to a type name within this scope, 53/// return the declaration of that type. 54/// 55/// This routine performs ordinary name lookup of the identifier II 56/// within the given scope, with optional C++ scope specifier SS, to 57/// determine whether the name refers to a type. If so, returns an 58/// opaque pointer (actually a QualType) corresponding to that 59/// type. Otherwise, returns NULL. 60/// 61/// If name lookup results in an ambiguity, this routine will complain 62/// and then return NULL. 63Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 64 Scope *S, const CXXScopeSpec *SS) { 65 // C++ [temp.res]p3: 66 // A qualified-id that refers to a type and in which the 67 // nested-name-specifier depends on a template-parameter (14.6.2) 68 // shall be prefixed by the keyword typename to indicate that the 69 // qualified-id denotes a type, forming an 70 // elaborated-type-specifier (7.1.5.3). 71 // 72 // We therefore do not perform any name lookup if the result would 73 // refer to a member of an unknown specialization. 74 if (SS && isUnknownSpecialization(*SS)) 75 return 0; 76 77 LookupResult Result 78 = LookupParsedName(S, SS, &II, LookupOrdinaryName, false, false); 79 80 NamedDecl *IIDecl = 0; 81 switch (Result.getKind()) { 82 case LookupResult::NotFound: 83 case LookupResult::FoundOverloaded: 84 return 0; 85 86 case LookupResult::AmbiguousBaseSubobjectTypes: 87 case LookupResult::AmbiguousBaseSubobjects: 88 case LookupResult::AmbiguousReference: { 89 // Look to see if we have a type anywhere in the list of results. 90 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 91 Res != ResEnd; ++Res) { 92 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 93 if (!IIDecl || 94 (*Res)->getLocation().getRawEncoding() < 95 IIDecl->getLocation().getRawEncoding()) 96 IIDecl = *Res; 97 } 98 } 99 100 if (!IIDecl) { 101 // None of the entities we found is a type, so there is no way 102 // to even assume that the result is a type. In this case, don't 103 // complain about the ambiguity. The parser will either try to 104 // perform this lookup again (e.g., as an object name), which 105 // will produce the ambiguity, or will complain that it expected 106 // a type name. 107 Result.Destroy(); 108 return 0; 109 } 110 111 // We found a type within the ambiguous lookup; diagnose the 112 // ambiguity and then return that type. This might be the right 113 // answer, or it might not be, but it suppresses any attempt to 114 // perform the name lookup again. 115 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc); 116 break; 117 } 118 119 case LookupResult::Found: 120 IIDecl = Result.getAsDecl(); 121 break; 122 } 123 124 if (IIDecl) { 125 QualType T; 126 127 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 128 // Check whether we can use this type 129 (void)DiagnoseUseOfDecl(IIDecl, NameLoc); 130 131 if (getLangOptions().CPlusPlus) { 132 // C++ [temp.local]p2: 133 // Within the scope of a class template specialization or 134 // partial specialization, when the injected-class-name is 135 // not followed by a <, it is equivalent to the 136 // injected-class-name followed by the template-argument s 137 // of the class template specialization or partial 138 // specialization enclosed in <>. 139 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) 140 if (RD->isInjectedClassName()) 141 if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate()) 142 T = Template->getInjectedClassNameType(Context); 143 } 144 145 if (T.isNull()) 146 T = Context.getTypeDeclType(TD); 147 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 148 // Check whether we can use this interface. 149 (void)DiagnoseUseOfDecl(IIDecl, NameLoc); 150 151 T = Context.getObjCInterfaceType(IDecl); 152 } else 153 return 0; 154 155 if (SS) 156 T = getQualifiedNameType(*SS, T); 157 158 return T.getAsOpaquePtr(); 159 } 160 161 return 0; 162} 163 164/// isTagName() - This method is called *for error recovery purposes only* 165/// to determine if the specified name is a valid tag name ("struct foo"). If 166/// so, this returns the TST for the tag corresponding to it (TST_enum, 167/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 168/// where the user forgot to specify the tag. 169DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 170 // Do a tag name lookup in this scope. 171 LookupResult R = LookupName(S, &II, LookupTagName, false, false); 172 if (R.getKind() == LookupResult::Found) 173 if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) { 174 switch (TD->getTagKind()) { 175 case TagDecl::TK_struct: return DeclSpec::TST_struct; 176 case TagDecl::TK_union: return DeclSpec::TST_union; 177 case TagDecl::TK_class: return DeclSpec::TST_class; 178 case TagDecl::TK_enum: return DeclSpec::TST_enum; 179 } 180 } 181 182 return DeclSpec::TST_unspecified; 183} 184 185 186 187DeclContext *Sema::getContainingDC(DeclContext *DC) { 188 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 189 // A C++ out-of-line method will return to the file declaration context. 190 if (MD->isOutOfLine()) 191 return MD->getLexicalDeclContext(); 192 193 // A C++ inline method is parsed *after* the topmost class it was declared 194 // in is fully parsed (it's "complete"). 195 // The parsing of a C++ inline method happens at the declaration context of 196 // the topmost (non-nested) class it is lexically declared in. 197 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record."); 198 DC = MD->getParent(); 199 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 200 DC = RD; 201 202 // Return the declaration context of the topmost class the inline method is 203 // declared in. 204 return DC; 205 } 206 207 if (isa<ObjCMethodDecl>(DC)) 208 return Context.getTranslationUnitDecl(); 209 210 return DC->getLexicalParent(); 211} 212 213void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 214 assert(getContainingDC(DC) == CurContext && 215 "The next DeclContext should be lexically contained in the current one."); 216 CurContext = DC; 217 S->setEntity(DC); 218} 219 220void Sema::PopDeclContext() { 221 assert(CurContext && "DeclContext imbalance!"); 222 223 CurContext = getContainingDC(CurContext); 224} 225 226/// EnterDeclaratorContext - Used when we must lookup names in the context 227/// of a declarator's nested name specifier. 228void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 229 assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?"); 230 PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity()); 231 CurContext = DC; 232 assert(CurContext && "No context?"); 233 S->setEntity(CurContext); 234} 235 236void Sema::ExitDeclaratorContext(Scope *S) { 237 S->setEntity(PreDeclaratorDC); 238 PreDeclaratorDC = 0; 239 240 // Reset CurContext to the nearest enclosing context. 241 while (!S->getEntity() && S->getParent()) 242 S = S->getParent(); 243 CurContext = static_cast<DeclContext*>(S->getEntity()); 244 assert(CurContext && "No context?"); 245} 246 247/// \brief Determine whether we allow overloading of the function 248/// PrevDecl with another declaration. 249/// 250/// This routine determines whether overloading is possible, not 251/// whether some new function is actually an overload. It will return 252/// true in C++ (where we can always provide overloads) or, as an 253/// extension, in C when the previous function is already an 254/// overloaded function declaration or has the "overloadable" 255/// attribute. 256static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) { 257 if (Context.getLangOptions().CPlusPlus) 258 return true; 259 260 if (isa<OverloadedFunctionDecl>(PrevDecl)) 261 return true; 262 263 return PrevDecl->getAttr<OverloadableAttr>() != 0; 264} 265 266/// Add this decl to the scope shadowed decl chains. 267void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) { 268 // Move up the scope chain until we find the nearest enclosing 269 // non-transparent context. The declaration will be introduced into this 270 // scope. 271 while (S->getEntity() && 272 ((DeclContext *)S->getEntity())->isTransparentContext()) 273 S = S->getParent(); 274 275 S->AddDecl(DeclPtrTy::make(D)); 276 277 // Add scoped declarations into their context, so that they can be 278 // found later. Declarations without a context won't be inserted 279 // into any context. 280 CurContext->addDecl(D); 281 282 // C++ [basic.scope]p4: 283 // -- exactly one declaration shall declare a class name or 284 // enumeration name that is not a typedef name and the other 285 // declarations shall all refer to the same object or 286 // enumerator, or all refer to functions and function templates; 287 // in this case the class name or enumeration name is hidden. 288 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 289 // We are pushing the name of a tag (enum or class). 290 if (CurContext->getLookupContext() 291 == TD->getDeclContext()->getLookupContext()) { 292 // We're pushing the tag into the current context, which might 293 // require some reshuffling in the identifier resolver. 294 IdentifierResolver::iterator 295 I = IdResolver.begin(TD->getDeclName()), 296 IEnd = IdResolver.end(); 297 if (I != IEnd && isDeclInScope(*I, CurContext, S)) { 298 NamedDecl *PrevDecl = *I; 299 for (; I != IEnd && isDeclInScope(*I, CurContext, S); 300 PrevDecl = *I, ++I) { 301 if (TD->declarationReplaces(*I)) { 302 // This is a redeclaration. Remove it from the chain and 303 // break out, so that we'll add in the shadowed 304 // declaration. 305 S->RemoveDecl(DeclPtrTy::make(*I)); 306 if (PrevDecl == *I) { 307 IdResolver.RemoveDecl(*I); 308 IdResolver.AddDecl(TD); 309 return; 310 } else { 311 IdResolver.RemoveDecl(*I); 312 break; 313 } 314 } 315 } 316 317 // There is already a declaration with the same name in the same 318 // scope, which is not a tag declaration. It must be found 319 // before we find the new declaration, so insert the new 320 // declaration at the end of the chain. 321 IdResolver.AddShadowedDecl(TD, PrevDecl); 322 323 return; 324 } 325 } 326 } else if ((isa<FunctionDecl>(D) && 327 AllowOverloadingOfFunction(D, Context)) || 328 isa<FunctionTemplateDecl>(D)) { 329 // We are pushing the name of a function or function template, 330 // which might be an overloaded name. 331 IdentifierResolver::iterator Redecl 332 = std::find_if(IdResolver.begin(D->getDeclName()), 333 IdResolver.end(), 334 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces), 335 D)); 336 if (Redecl != IdResolver.end() && 337 S->isDeclScope(DeclPtrTy::make(*Redecl))) { 338 // There is already a declaration of a function on our 339 // IdResolver chain. Replace it with this declaration. 340 S->RemoveDecl(DeclPtrTy::make(*Redecl)); 341 IdResolver.RemoveDecl(*Redecl); 342 } 343 } else if (isa<ObjCInterfaceDecl>(D)) { 344 // We're pushing an Objective-C interface into the current 345 // context. If there is already an alias declaration, remove it first. 346 for (IdentifierResolver::iterator 347 I = IdResolver.begin(D->getDeclName()), IEnd = IdResolver.end(); 348 I != IEnd; ++I) { 349 if (isa<ObjCCompatibleAliasDecl>(*I)) { 350 S->RemoveDecl(DeclPtrTy::make(*I)); 351 IdResolver.RemoveDecl(*I); 352 break; 353 } 354 } 355 } 356 357 IdResolver.AddDecl(D); 358} 359 360void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 361 if (S->decl_empty()) return; 362 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 363 "Scope shouldn't contain decls!"); 364 365 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 366 I != E; ++I) { 367 Decl *TmpD = (*I).getAs<Decl>(); 368 assert(TmpD && "This decl didn't get pushed??"); 369 370 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 371 NamedDecl *D = cast<NamedDecl>(TmpD); 372 373 if (!D->getDeclName()) continue; 374 375 // Remove this name from our lexical scope. 376 IdResolver.RemoveDecl(D); 377 } 378} 379 380/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 381/// return 0 if one not found. 382ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 383 // The third "scope" argument is 0 since we aren't enabling lazy built-in 384 // creation from this context. 385 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName); 386 387 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 388} 389 390/// getNonFieldDeclScope - Retrieves the innermost scope, starting 391/// from S, where a non-field would be declared. This routine copes 392/// with the difference between C and C++ scoping rules in structs and 393/// unions. For example, the following code is well-formed in C but 394/// ill-formed in C++: 395/// @code 396/// struct S6 { 397/// enum { BAR } e; 398/// }; 399/// 400/// void test_S6() { 401/// struct S6 a; 402/// a.e = BAR; 403/// } 404/// @endcode 405/// For the declaration of BAR, this routine will return a different 406/// scope. The scope S will be the scope of the unnamed enumeration 407/// within S6. In C++, this routine will return the scope associated 408/// with S6, because the enumeration's scope is a transparent 409/// context but structures can contain non-field names. In C, this 410/// routine will return the translation unit scope, since the 411/// enumeration's scope is a transparent context and structures cannot 412/// contain non-field names. 413Scope *Sema::getNonFieldDeclScope(Scope *S) { 414 while (((S->getFlags() & Scope::DeclScope) == 0) || 415 (S->getEntity() && 416 ((DeclContext *)S->getEntity())->isTransparentContext()) || 417 (S->isClassScope() && !getLangOptions().CPlusPlus)) 418 S = S->getParent(); 419 return S; 420} 421 422void Sema::InitBuiltinVaListType() { 423 if (!Context.getBuiltinVaListType().isNull()) 424 return; 425 426 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 427 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName); 428 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 429 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 430} 431 432/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 433/// file scope. lazily create a decl for it. ForRedeclaration is true 434/// if we're creating this built-in in anticipation of redeclaring the 435/// built-in. 436NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 437 Scope *S, bool ForRedeclaration, 438 SourceLocation Loc) { 439 Builtin::ID BID = (Builtin::ID)bid; 440 441 if (Context.BuiltinInfo.hasVAListUse(BID)) 442 InitBuiltinVaListType(); 443 444 ASTContext::GetBuiltinTypeError Error; 445 QualType R = Context.GetBuiltinType(BID, Error); 446 switch (Error) { 447 case ASTContext::GE_None: 448 // Okay 449 break; 450 451 case ASTContext::GE_Missing_stdio: 452 if (ForRedeclaration) 453 Diag(Loc, diag::err_implicit_decl_requires_stdio) 454 << Context.BuiltinInfo.GetName(BID); 455 return 0; 456 457 case ASTContext::GE_Missing_setjmp: 458 if (ForRedeclaration) 459 Diag(Loc, diag::err_implicit_decl_requires_setjmp) 460 << Context.BuiltinInfo.GetName(BID); 461 return 0; 462 } 463 464 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 465 Diag(Loc, diag::ext_implicit_lib_function_decl) 466 << Context.BuiltinInfo.GetName(BID) 467 << R; 468 if (Context.BuiltinInfo.getHeaderName(BID) && 469 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl) 470 != Diagnostic::Ignored) 471 Diag(Loc, diag::note_please_include_header) 472 << Context.BuiltinInfo.getHeaderName(BID) 473 << Context.BuiltinInfo.GetName(BID); 474 } 475 476 FunctionDecl *New = FunctionDecl::Create(Context, 477 Context.getTranslationUnitDecl(), 478 Loc, II, R, 479 FunctionDecl::Extern, false, 480 /*hasPrototype=*/true); 481 New->setImplicit(); 482 483 // Create Decl objects for each parameter, adding them to the 484 // FunctionDecl. 485 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 486 llvm::SmallVector<ParmVarDecl*, 16> Params; 487 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 488 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 489 FT->getArgType(i), VarDecl::None, 0)); 490 New->setParams(Context, Params.data(), Params.size()); 491 } 492 493 AddKnownFunctionAttributes(New); 494 495 // TUScope is the translation-unit scope to insert this function into. 496 // FIXME: This is hideous. We need to teach PushOnScopeChains to 497 // relate Scopes to DeclContexts, and probably eliminate CurContext 498 // entirely, but we're not there yet. 499 DeclContext *SavedContext = CurContext; 500 CurContext = Context.getTranslationUnitDecl(); 501 PushOnScopeChains(New, TUScope); 502 CurContext = SavedContext; 503 return New; 504} 505 506/// GetStdNamespace - This method gets the C++ "std" namespace. This is where 507/// everything from the standard library is defined. 508NamespaceDecl *Sema::GetStdNamespace() { 509 if (!StdNamespace) { 510 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std"); 511 DeclContext *Global = Context.getTranslationUnitDecl(); 512 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName); 513 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std); 514 } 515 return StdNamespace; 516} 517 518/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the 519/// same name and scope as a previous declaration 'Old'. Figure out 520/// how to resolve this situation, merging decls or emitting 521/// diagnostics as appropriate. If there was an error, set New to be invalid. 522/// 523void Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) { 524 // If either decl is known invalid already, set the new one to be invalid and 525 // don't bother doing any merging checks. 526 if (New->isInvalidDecl() || OldD->isInvalidDecl()) 527 return New->setInvalidDecl(); 528 529 // Allow multiple definitions for ObjC built-in typedefs. 530 // FIXME: Verify the underlying types are equivalent! 531 if (getLangOptions().ObjC1) { 532 const IdentifierInfo *TypeID = New->getIdentifier(); 533 switch (TypeID->getLength()) { 534 default: break; 535 case 2: 536 if (!TypeID->isStr("id")) 537 break; 538 // Install the built-in type for 'id', ignoring the current definition. 539 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 540 return; 541 case 5: 542 if (!TypeID->isStr("Class")) 543 break; 544 // Install the built-in type for 'Class', ignoring the current definition. 545 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 546 return; 547 case 3: 548 if (!TypeID->isStr("SEL")) 549 break; 550 Context.setObjCSelType(Context.getTypeDeclType(New)); 551 return; 552 case 8: 553 if (!TypeID->isStr("Protocol")) 554 break; 555 Context.setObjCProtoType(New->getUnderlyingType()); 556 return; 557 } 558 // Fall through - the typedef name was not a builtin type. 559 } 560 // Verify the old decl was also a type. 561 TypeDecl *Old = dyn_cast<TypeDecl>(OldD); 562 if (!Old) { 563 Diag(New->getLocation(), diag::err_redefinition_different_kind) 564 << New->getDeclName(); 565 if (OldD->getLocation().isValid()) 566 Diag(OldD->getLocation(), diag::note_previous_definition); 567 return New->setInvalidDecl(); 568 } 569 570 // Determine the "old" type we'll use for checking and diagnostics. 571 QualType OldType; 572 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old)) 573 OldType = OldTypedef->getUnderlyingType(); 574 else 575 OldType = Context.getTypeDeclType(Old); 576 577 // If the typedef types are not identical, reject them in all languages and 578 // with any extensions enabled. 579 580 if (OldType != New->getUnderlyingType() && 581 Context.getCanonicalType(OldType) != 582 Context.getCanonicalType(New->getUnderlyingType())) { 583 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 584 << New->getUnderlyingType() << OldType; 585 if (Old->getLocation().isValid()) 586 Diag(Old->getLocation(), diag::note_previous_definition); 587 return New->setInvalidDecl(); 588 } 589 590 if (getLangOptions().Microsoft) 591 return; 592 593 // C++ [dcl.typedef]p2: 594 // In a given non-class scope, a typedef specifier can be used to 595 // redefine the name of any type declared in that scope to refer 596 // to the type to which it already refers. 597 if (getLangOptions().CPlusPlus) { 598 if (!isa<CXXRecordDecl>(CurContext)) 599 return; 600 Diag(New->getLocation(), diag::err_redefinition) 601 << New->getDeclName(); 602 Diag(Old->getLocation(), diag::note_previous_definition); 603 return New->setInvalidDecl(); 604 } 605 606 // If we have a redefinition of a typedef in C, emit a warning. This warning 607 // is normally mapped to an error, but can be controlled with 608 // -Wtypedef-redefinition. If either the original or the redefinition is 609 // in a system header, don't emit this for compatibility with GCC. 610 if (PP.getDiagnostics().getSuppressSystemWarnings() && 611 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 612 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 613 return; 614 615 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 616 << New->getDeclName(); 617 Diag(Old->getLocation(), diag::note_previous_definition); 618 return; 619} 620 621/// DeclhasAttr - returns true if decl Declaration already has the target 622/// attribute. 623static bool 624DeclHasAttr(const Decl *decl, const Attr *target) { 625 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 626 if (attr->getKind() == target->getKind()) 627 return true; 628 629 return false; 630} 631 632/// MergeAttributes - append attributes from the Old decl to the New one. 633static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) { 634 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) { 635 if (!DeclHasAttr(New, attr) && attr->isMerged()) { 636 Attr *NewAttr = attr->clone(C); 637 NewAttr->setInherited(true); 638 New->addAttr(NewAttr); 639 } 640 } 641} 642 643/// Used in MergeFunctionDecl to keep track of function parameters in 644/// C. 645struct GNUCompatibleParamWarning { 646 ParmVarDecl *OldParm; 647 ParmVarDecl *NewParm; 648 QualType PromotedType; 649}; 650 651/// MergeFunctionDecl - We just parsed a function 'New' from 652/// declarator D which has the same name and scope as a previous 653/// declaration 'Old'. Figure out how to resolve this situation, 654/// merging decls or emitting diagnostics as appropriate. 655/// 656/// In C++, New and Old must be declarations that are not 657/// overloaded. Use IsOverload to determine whether New and Old are 658/// overloaded, and to select the Old declaration that New should be 659/// merged with. 660/// 661/// Returns true if there was an error, false otherwise. 662bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 663 assert(!isa<OverloadedFunctionDecl>(OldD) && 664 "Cannot merge with an overloaded function declaration"); 665 666 // Verify the old decl was also a function. 667 FunctionDecl *Old = 0; 668 if (FunctionTemplateDecl *OldFunctionTemplate 669 = dyn_cast<FunctionTemplateDecl>(OldD)) 670 Old = OldFunctionTemplate->getTemplatedDecl(); 671 else 672 Old = dyn_cast<FunctionDecl>(OldD); 673 if (!Old) { 674 Diag(New->getLocation(), diag::err_redefinition_different_kind) 675 << New->getDeclName(); 676 Diag(OldD->getLocation(), diag::note_previous_definition); 677 return true; 678 } 679 680 // Determine whether the previous declaration was a definition, 681 // implicit declaration, or a declaration. 682 diag::kind PrevDiag; 683 if (Old->isThisDeclarationADefinition()) 684 PrevDiag = diag::note_previous_definition; 685 else if (Old->isImplicit()) 686 PrevDiag = diag::note_previous_implicit_declaration; 687 else 688 PrevDiag = diag::note_previous_declaration; 689 690 QualType OldQType = Context.getCanonicalType(Old->getType()); 691 QualType NewQType = Context.getCanonicalType(New->getType()); 692 693 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 694 New->getStorageClass() == FunctionDecl::Static && 695 Old->getStorageClass() != FunctionDecl::Static) { 696 Diag(New->getLocation(), diag::err_static_non_static) 697 << New; 698 Diag(Old->getLocation(), PrevDiag); 699 return true; 700 } 701 702 if (getLangOptions().CPlusPlus) { 703 // (C++98 13.1p2): 704 // Certain function declarations cannot be overloaded: 705 // -- Function declarations that differ only in the return type 706 // cannot be overloaded. 707 QualType OldReturnType 708 = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 709 QualType NewReturnType 710 = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 711 if (OldReturnType != NewReturnType) { 712 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 713 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 714 return true; 715 } 716 717 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 718 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 719 if (OldMethod && NewMethod && 720 NewMethod->getLexicalDeclContext()->isRecord()) { 721 // -- Member function declarations with the same name and the 722 // same parameter types cannot be overloaded if any of them 723 // is a static member function declaration. 724 if (OldMethod->isStatic() || NewMethod->isStatic()) { 725 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 726 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 727 return true; 728 } 729 730 // C++ [class.mem]p1: 731 // [...] A member shall not be declared twice in the 732 // member-specification, except that a nested class or member 733 // class template can be declared and then later defined. 734 unsigned NewDiag; 735 if (isa<CXXConstructorDecl>(OldMethod)) 736 NewDiag = diag::err_constructor_redeclared; 737 else if (isa<CXXDestructorDecl>(NewMethod)) 738 NewDiag = diag::err_destructor_redeclared; 739 else if (isa<CXXConversionDecl>(NewMethod)) 740 NewDiag = diag::err_conv_function_redeclared; 741 else 742 NewDiag = diag::err_member_redeclared; 743 744 Diag(New->getLocation(), NewDiag); 745 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 746 } 747 748 // (C++98 8.3.5p3): 749 // All declarations for a function shall agree exactly in both the 750 // return type and the parameter-type-list. 751 if (OldQType == NewQType) 752 return MergeCompatibleFunctionDecls(New, Old); 753 754 // Fall through for conflicting redeclarations and redefinitions. 755 } 756 757 // C: Function types need to be compatible, not identical. This handles 758 // duplicate function decls like "void f(int); void f(enum X);" properly. 759 if (!getLangOptions().CPlusPlus && 760 Context.typesAreCompatible(OldQType, NewQType)) { 761 const FunctionType *OldFuncType = OldQType->getAsFunctionType(); 762 const FunctionType *NewFuncType = NewQType->getAsFunctionType(); 763 const FunctionProtoType *OldProto = 0; 764 if (isa<FunctionNoProtoType>(NewFuncType) && 765 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 766 // The old declaration provided a function prototype, but the 767 // new declaration does not. Merge in the prototype. 768 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 769 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 770 OldProto->arg_type_end()); 771 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 772 ParamTypes.data(), ParamTypes.size(), 773 OldProto->isVariadic(), 774 OldProto->getTypeQuals()); 775 New->setType(NewQType); 776 New->setHasInheritedPrototype(); 777 778 // Synthesize a parameter for each argument type. 779 llvm::SmallVector<ParmVarDecl*, 16> Params; 780 for (FunctionProtoType::arg_type_iterator 781 ParamType = OldProto->arg_type_begin(), 782 ParamEnd = OldProto->arg_type_end(); 783 ParamType != ParamEnd; ++ParamType) { 784 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 785 SourceLocation(), 0, 786 *ParamType, VarDecl::None, 787 0); 788 Param->setImplicit(); 789 Params.push_back(Param); 790 } 791 792 New->setParams(Context, Params.data(), Params.size()); 793 } 794 795 return MergeCompatibleFunctionDecls(New, Old); 796 } 797 798 // GNU C permits a K&R definition to follow a prototype declaration 799 // if the declared types of the parameters in the K&R definition 800 // match the types in the prototype declaration, even when the 801 // promoted types of the parameters from the K&R definition differ 802 // from the types in the prototype. GCC then keeps the types from 803 // the prototype. 804 // 805 // If a variadic prototype is followed by a non-variadic K&R definition, 806 // the K&R definition becomes variadic. This is sort of an edge case, but 807 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 808 // C99 6.9.1p8. 809 if (!getLangOptions().CPlusPlus && 810 Old->hasPrototype() && !New->hasPrototype() && 811 New->getType()->getAsFunctionProtoType() && 812 Old->getNumParams() == New->getNumParams()) { 813 llvm::SmallVector<QualType, 16> ArgTypes; 814 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings; 815 const FunctionProtoType *OldProto 816 = Old->getType()->getAsFunctionProtoType(); 817 const FunctionProtoType *NewProto 818 = New->getType()->getAsFunctionProtoType(); 819 820 // Determine whether this is the GNU C extension. 821 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 822 NewProto->getResultType()); 823 bool LooseCompatible = !MergedReturn.isNull(); 824 for (unsigned Idx = 0, End = Old->getNumParams(); 825 LooseCompatible && Idx != End; ++Idx) { 826 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 827 ParmVarDecl *NewParm = New->getParamDecl(Idx); 828 if (Context.typesAreCompatible(OldParm->getType(), 829 NewProto->getArgType(Idx))) { 830 ArgTypes.push_back(NewParm->getType()); 831 } else if (Context.typesAreCompatible(OldParm->getType(), 832 NewParm->getType())) { 833 GNUCompatibleParamWarning Warn 834 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 835 Warnings.push_back(Warn); 836 ArgTypes.push_back(NewParm->getType()); 837 } else 838 LooseCompatible = false; 839 } 840 841 if (LooseCompatible) { 842 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 843 Diag(Warnings[Warn].NewParm->getLocation(), 844 diag::ext_param_promoted_not_compatible_with_prototype) 845 << Warnings[Warn].PromotedType 846 << Warnings[Warn].OldParm->getType(); 847 Diag(Warnings[Warn].OldParm->getLocation(), 848 diag::note_previous_declaration); 849 } 850 851 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 852 ArgTypes.size(), 853 OldProto->isVariadic(), 0)); 854 return MergeCompatibleFunctionDecls(New, Old); 855 } 856 857 // Fall through to diagnose conflicting types. 858 } 859 860 // A function that has already been declared has been redeclared or defined 861 // with a different type- show appropriate diagnostic 862 if (unsigned BuiltinID = Old->getBuiltinID(Context)) { 863 // The user has declared a builtin function with an incompatible 864 // signature. 865 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 866 // The function the user is redeclaring is a library-defined 867 // function like 'malloc' or 'printf'. Warn about the 868 // redeclaration, then pretend that we don't know about this 869 // library built-in. 870 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 871 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 872 << Old << Old->getType(); 873 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 874 Old->setInvalidDecl(); 875 return false; 876 } 877 878 PrevDiag = diag::note_previous_builtin_declaration; 879 } 880 881 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 882 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 883 return true; 884} 885 886/// \brief Completes the merge of two function declarations that are 887/// known to be compatible. 888/// 889/// This routine handles the merging of attributes and other 890/// properties of function declarations form the old declaration to 891/// the new declaration, once we know that New is in fact a 892/// redeclaration of Old. 893/// 894/// \returns false 895bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 896 // Merge the attributes 897 MergeAttributes(New, Old, Context); 898 899 // Merge the storage class. 900 if (Old->getStorageClass() != FunctionDecl::Extern) 901 New->setStorageClass(Old->getStorageClass()); 902 903 // Merge "inline" 904 if (Old->isInline()) 905 New->setInline(true); 906 907 // If this function declaration by itself qualifies as a C99 inline 908 // definition (C99 6.7.4p6), but the previous definition did not, 909 // then the function is not a C99 inline definition. 910 if (New->isC99InlineDefinition() && !Old->isC99InlineDefinition()) 911 New->setC99InlineDefinition(false); 912 else if (Old->isC99InlineDefinition() && !New->isC99InlineDefinition()) { 913 // Mark all preceding definitions as not being C99 inline definitions. 914 for (const FunctionDecl *Prev = Old; Prev; 915 Prev = Prev->getPreviousDeclaration()) 916 const_cast<FunctionDecl *>(Prev)->setC99InlineDefinition(false); 917 } 918 919 // Merge "pure" flag. 920 if (Old->isPure()) 921 New->setPure(); 922 923 // Merge the "deleted" flag. 924 if (Old->isDeleted()) 925 New->setDeleted(); 926 927 if (getLangOptions().CPlusPlus) 928 return MergeCXXFunctionDecl(New, Old); 929 930 return false; 931} 932 933/// MergeVarDecl - We just parsed a variable 'New' which has the same name 934/// and scope as a previous declaration 'Old'. Figure out how to resolve this 935/// situation, merging decls or emitting diagnostics as appropriate. 936/// 937/// Tentative definition rules (C99 6.9.2p2) are checked by 938/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 939/// definitions here, since the initializer hasn't been attached. 940/// 941void Sema::MergeVarDecl(VarDecl *New, Decl *OldD) { 942 // If either decl is invalid, make sure the new one is marked invalid and 943 // don't do any other checking. 944 if (New->isInvalidDecl() || OldD->isInvalidDecl()) 945 return New->setInvalidDecl(); 946 947 // Verify the old decl was also a variable. 948 VarDecl *Old = dyn_cast<VarDecl>(OldD); 949 if (!Old) { 950 Diag(New->getLocation(), diag::err_redefinition_different_kind) 951 << New->getDeclName(); 952 Diag(OldD->getLocation(), diag::note_previous_definition); 953 return New->setInvalidDecl(); 954 } 955 956 MergeAttributes(New, Old, Context); 957 958 // Merge the types 959 QualType MergedT; 960 if (getLangOptions().CPlusPlus) { 961 if (Context.hasSameType(New->getType(), Old->getType())) 962 MergedT = New->getType(); 963 } else { 964 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 965 } 966 if (MergedT.isNull()) { 967 Diag(New->getLocation(), diag::err_redefinition_different_type) 968 << New->getDeclName(); 969 Diag(Old->getLocation(), diag::note_previous_definition); 970 return New->setInvalidDecl(); 971 } 972 New->setType(MergedT); 973 974 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 975 if (New->getStorageClass() == VarDecl::Static && 976 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) { 977 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 978 Diag(Old->getLocation(), diag::note_previous_definition); 979 return New->setInvalidDecl(); 980 } 981 // C99 6.2.2p4: 982 // For an identifier declared with the storage-class specifier 983 // extern in a scope in which a prior declaration of that 984 // identifier is visible,23) if the prior declaration specifies 985 // internal or external linkage, the linkage of the identifier at 986 // the later declaration is the same as the linkage specified at 987 // the prior declaration. If no prior declaration is visible, or 988 // if the prior declaration specifies no linkage, then the 989 // identifier has external linkage. 990 if (New->hasExternalStorage() && Old->hasLinkage()) 991 /* Okay */; 992 else if (New->getStorageClass() != VarDecl::Static && 993 Old->getStorageClass() == VarDecl::Static) { 994 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 995 Diag(Old->getLocation(), diag::note_previous_definition); 996 return New->setInvalidDecl(); 997 } 998 999 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 1000 1001 // FIXME: The test for external storage here seems wrong? We still 1002 // need to check for mismatches. 1003 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 1004 // Don't complain about out-of-line definitions of static members. 1005 !(Old->getLexicalDeclContext()->isRecord() && 1006 !New->getLexicalDeclContext()->isRecord())) { 1007 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 1008 Diag(Old->getLocation(), diag::note_previous_definition); 1009 return New->setInvalidDecl(); 1010 } 1011 1012 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 1013 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 1014 Diag(Old->getLocation(), diag::note_previous_definition); 1015 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 1016 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 1017 Diag(Old->getLocation(), diag::note_previous_definition); 1018 } 1019 1020 // Keep a chain of previous declarations. 1021 New->setPreviousDeclaration(Old); 1022} 1023 1024/// CheckFallThrough - Check that we don't fall off the end of a 1025/// Statement that should return a value. 1026/// 1027/// \returns AlwaysFallThrough iff we always fall off the end of the statement, 1028/// MaybeFallThrough iff we might or might not fall off the end and 1029/// NeverFallThrough iff we never fall off the end of the statement. We assume 1030/// that functions not marked noreturn will return. 1031Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) { 1032 llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context)); 1033 1034 // FIXME: They should never return 0, fix that, delete this code. 1035 if (cfg == 0) 1036 return NeverFallThrough; 1037 // The CFG leaves in dead things, and we don't want to dead code paths to 1038 // confuse us, so we mark all live things first. 1039 std::queue<CFGBlock*> workq; 1040 llvm::BitVector live(cfg->getNumBlockIDs()); 1041 // Prep work queue 1042 workq.push(&cfg->getEntry()); 1043 // Solve 1044 while (!workq.empty()) { 1045 CFGBlock *item = workq.front(); 1046 workq.pop(); 1047 live.set(item->getBlockID()); 1048 for (CFGBlock::succ_iterator I=item->succ_begin(), 1049 E=item->succ_end(); 1050 I != E; 1051 ++I) { 1052 if ((*I) && !live[(*I)->getBlockID()]) { 1053 live.set((*I)->getBlockID()); 1054 workq.push(*I); 1055 } 1056 } 1057 } 1058 1059 // Now we know what is live, we check the live precessors of the exit block 1060 // and look for fall through paths, being careful to ignore normal returns, 1061 // and exceptional paths. 1062 bool HasLiveReturn = false; 1063 bool HasFakeEdge = false; 1064 bool HasPlainEdge = false; 1065 for (CFGBlock::succ_iterator I=cfg->getExit().pred_begin(), 1066 E = cfg->getExit().pred_end(); 1067 I != E; 1068 ++I) { 1069 CFGBlock& B = **I; 1070 if (!live[B.getBlockID()]) 1071 continue; 1072 if (B.size() == 0) { 1073 // A labeled empty statement, or the entry block... 1074 HasPlainEdge = true; 1075 continue; 1076 } 1077 Stmt *S = B[B.size()-1]; 1078 if (isa<ReturnStmt>(S)) { 1079 HasLiveReturn = true; 1080 continue; 1081 } 1082 if (isa<ObjCAtThrowStmt>(S)) { 1083 HasFakeEdge = true; 1084 continue; 1085 } 1086 if (isa<CXXThrowExpr>(S)) { 1087 HasFakeEdge = true; 1088 continue; 1089 } 1090 bool NoReturnEdge = false; 1091 if (CallExpr *C = dyn_cast<CallExpr>(S)) { 1092 Expr *CEE = C->getCallee()->IgnoreParenCasts(); 1093 if (CEE->getType().getNoReturnAttr()) { 1094 NoReturnEdge = true; 1095 HasFakeEdge = true; 1096 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) { 1097 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) { 1098 if (FD->hasAttr<NoReturnAttr>()) { 1099 NoReturnEdge = true; 1100 HasFakeEdge = true; 1101 } 1102 } 1103 } 1104 } 1105 // FIXME: Add noreturn message sends. 1106 if (NoReturnEdge == false) 1107 HasPlainEdge = true; 1108 } 1109 if (!HasPlainEdge) 1110 return NeverFallThrough; 1111 if (HasFakeEdge || HasLiveReturn) 1112 return MaybeFallThrough; 1113 // This says AlwaysFallThrough for calls to functions that are not marked 1114 // noreturn, that don't return. If people would like this warning to be more 1115 // accurate, such functions should be marked as noreturn. 1116 return AlwaysFallThrough; 1117} 1118 1119/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a 1120/// function that should return a value. Check that we don't fall off the end 1121/// of a noreturn function. We assume that functions and blocks not marked 1122/// noreturn will return. 1123void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) { 1124 // FIXME: Would be nice if we had a better way to control cascading errors, 1125 // but for now, avoid them. The problem is that when Parse sees: 1126 // int foo() { return a; } 1127 // The return is eaten and the Sema code sees just: 1128 // int foo() { } 1129 // which this code would then warn about. 1130 if (getDiagnostics().hasErrorOccurred()) 1131 return; 1132 bool ReturnsVoid = false; 1133 bool HasNoReturn = false; 1134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1135 if (FD->getResultType()->isVoidType()) 1136 ReturnsVoid = true; 1137 if (FD->hasAttr<NoReturnAttr>()) 1138 HasNoReturn = true; 1139 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 1140 if (MD->getResultType()->isVoidType()) 1141 ReturnsVoid = true; 1142 if (MD->hasAttr<NoReturnAttr>()) 1143 HasNoReturn = true; 1144 } 1145 1146 // Short circuit for compilation speed. 1147 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function) 1148 == Diagnostic::Ignored || ReturnsVoid) 1149 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr) 1150 == Diagnostic::Ignored || !HasNoReturn) 1151 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block) 1152 == Diagnostic::Ignored || !ReturnsVoid)) 1153 return; 1154 // FIXME: Funtion try block 1155 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 1156 switch (CheckFallThrough(Body)) { 1157 case MaybeFallThrough: 1158 if (HasNoReturn) 1159 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function); 1160 else if (!ReturnsVoid) 1161 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function); 1162 break; 1163 case AlwaysFallThrough: 1164 if (HasNoReturn) 1165 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function); 1166 else if (!ReturnsVoid) 1167 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function); 1168 break; 1169 case NeverFallThrough: 1170 if (ReturnsVoid) 1171 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function); 1172 break; 1173 } 1174 } 1175} 1176 1177/// CheckFallThroughForBlock - Check that we don't fall off the end of a block 1178/// that should return a value. Check that we don't fall off the end of a 1179/// noreturn block. We assume that functions and blocks not marked noreturn 1180/// will return. 1181void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) { 1182 // FIXME: Would be nice if we had a better way to control cascading errors, 1183 // but for now, avoid them. The problem is that when Parse sees: 1184 // int foo() { return a; } 1185 // The return is eaten and the Sema code sees just: 1186 // int foo() { } 1187 // which this code would then warn about. 1188 if (getDiagnostics().hasErrorOccurred()) 1189 return; 1190 bool ReturnsVoid = false; 1191 bool HasNoReturn = false; 1192 if (const FunctionType *FT = BlockTy->getPointeeType()->getAsFunctionType()) { 1193 if (FT->getResultType()->isVoidType()) 1194 ReturnsVoid = true; 1195 if (FT->getNoReturnAttr()) 1196 HasNoReturn = true; 1197 } 1198 1199 // Short circuit for compilation speed. 1200 if (ReturnsVoid 1201 && !HasNoReturn 1202 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block) 1203 == Diagnostic::Ignored || !ReturnsVoid)) 1204 return; 1205 // FIXME: Funtion try block 1206 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 1207 switch (CheckFallThrough(Body)) { 1208 case MaybeFallThrough: 1209 if (HasNoReturn) 1210 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr); 1211 else if (!ReturnsVoid) 1212 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block); 1213 break; 1214 case AlwaysFallThrough: 1215 if (HasNoReturn) 1216 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr); 1217 else if (!ReturnsVoid) 1218 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block); 1219 break; 1220 case NeverFallThrough: 1221 if (ReturnsVoid) 1222 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block); 1223 break; 1224 } 1225 } 1226} 1227 1228/// CheckParmsForFunctionDef - Check that the parameters of the given 1229/// function are appropriate for the definition of a function. This 1230/// takes care of any checks that cannot be performed on the 1231/// declaration itself, e.g., that the types of each of the function 1232/// parameters are complete. 1233bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 1234 bool HasInvalidParm = false; 1235 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1236 ParmVarDecl *Param = FD->getParamDecl(p); 1237 1238 // C99 6.7.5.3p4: the parameters in a parameter type list in a 1239 // function declarator that is part of a function definition of 1240 // that function shall not have incomplete type. 1241 // 1242 // This is also C++ [dcl.fct]p6. 1243 if (!Param->isInvalidDecl() && 1244 RequireCompleteType(Param->getLocation(), Param->getType(), 1245 diag::err_typecheck_decl_incomplete_type)) { 1246 Param->setInvalidDecl(); 1247 HasInvalidParm = true; 1248 } 1249 1250 // C99 6.9.1p5: If the declarator includes a parameter type list, the 1251 // declaration of each parameter shall include an identifier. 1252 if (Param->getIdentifier() == 0 && 1253 !Param->isImplicit() && 1254 !getLangOptions().CPlusPlus) 1255 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 1256 } 1257 1258 return HasInvalidParm; 1259} 1260 1261/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 1262/// no declarator (e.g. "struct foo;") is parsed. 1263Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 1264 // FIXME: Error on auto/register at file scope 1265 // FIXME: Error on inline/virtual/explicit 1266 // FIXME: Error on invalid restrict 1267 // FIXME: Warn on useless __thread 1268 // FIXME: Warn on useless const/volatile 1269 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable 1270 // FIXME: Warn on useless attributes 1271 TagDecl *Tag = 0; 1272 if (DS.getTypeSpecType() == DeclSpec::TST_class || 1273 DS.getTypeSpecType() == DeclSpec::TST_struct || 1274 DS.getTypeSpecType() == DeclSpec::TST_union || 1275 DS.getTypeSpecType() == DeclSpec::TST_enum) { 1276 if (!DS.getTypeRep()) // We probably had an error 1277 return DeclPtrTy(); 1278 1279 Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep())); 1280 } 1281 1282 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 1283 if (!Record->getDeclName() && Record->isDefinition() && 1284 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 1285 if (getLangOptions().CPlusPlus || 1286 Record->getDeclContext()->isRecord()) 1287 return BuildAnonymousStructOrUnion(S, DS, Record); 1288 1289 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 1290 << DS.getSourceRange(); 1291 } 1292 1293 // Microsoft allows unnamed struct/union fields. Don't complain 1294 // about them. 1295 // FIXME: Should we support Microsoft's extensions in this area? 1296 if (Record->getDeclName() && getLangOptions().Microsoft) 1297 return DeclPtrTy::make(Tag); 1298 } 1299 1300 if (!DS.isMissingDeclaratorOk() && 1301 DS.getTypeSpecType() != DeclSpec::TST_error) { 1302 // Warn about typedefs of enums without names, since this is an 1303 // extension in both Microsoft an GNU. 1304 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 1305 Tag && isa<EnumDecl>(Tag)) { 1306 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 1307 << DS.getSourceRange(); 1308 return DeclPtrTy::make(Tag); 1309 } 1310 1311 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 1312 << DS.getSourceRange(); 1313 return DeclPtrTy(); 1314 } 1315 1316 return DeclPtrTy::make(Tag); 1317} 1318 1319/// InjectAnonymousStructOrUnionMembers - Inject the members of the 1320/// anonymous struct or union AnonRecord into the owning context Owner 1321/// and scope S. This routine will be invoked just after we realize 1322/// that an unnamed union or struct is actually an anonymous union or 1323/// struct, e.g., 1324/// 1325/// @code 1326/// union { 1327/// int i; 1328/// float f; 1329/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 1330/// // f into the surrounding scope.x 1331/// @endcode 1332/// 1333/// This routine is recursive, injecting the names of nested anonymous 1334/// structs/unions into the owning context and scope as well. 1335bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner, 1336 RecordDecl *AnonRecord) { 1337 bool Invalid = false; 1338 for (RecordDecl::field_iterator F = AnonRecord->field_begin(), 1339 FEnd = AnonRecord->field_end(); 1340 F != FEnd; ++F) { 1341 if ((*F)->getDeclName()) { 1342 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(), 1343 LookupOrdinaryName, true); 1344 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 1345 // C++ [class.union]p2: 1346 // The names of the members of an anonymous union shall be 1347 // distinct from the names of any other entity in the 1348 // scope in which the anonymous union is declared. 1349 unsigned diagKind 1350 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl 1351 : diag::err_anonymous_struct_member_redecl; 1352 Diag((*F)->getLocation(), diagKind) 1353 << (*F)->getDeclName(); 1354 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 1355 Invalid = true; 1356 } else { 1357 // C++ [class.union]p2: 1358 // For the purpose of name lookup, after the anonymous union 1359 // definition, the members of the anonymous union are 1360 // considered to have been defined in the scope in which the 1361 // anonymous union is declared. 1362 Owner->makeDeclVisibleInContext(*F); 1363 S->AddDecl(DeclPtrTy::make(*F)); 1364 IdResolver.AddDecl(*F); 1365 } 1366 } else if (const RecordType *InnerRecordType 1367 = (*F)->getType()->getAs<RecordType>()) { 1368 RecordDecl *InnerRecord = InnerRecordType->getDecl(); 1369 if (InnerRecord->isAnonymousStructOrUnion()) 1370 Invalid = Invalid || 1371 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord); 1372 } 1373 } 1374 1375 return Invalid; 1376} 1377 1378/// ActOnAnonymousStructOrUnion - Handle the declaration of an 1379/// anonymous structure or union. Anonymous unions are a C++ feature 1380/// (C++ [class.union]) and a GNU C extension; anonymous structures 1381/// are a GNU C and GNU C++ extension. 1382Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1383 RecordDecl *Record) { 1384 DeclContext *Owner = Record->getDeclContext(); 1385 1386 // Diagnose whether this anonymous struct/union is an extension. 1387 if (Record->isUnion() && !getLangOptions().CPlusPlus) 1388 Diag(Record->getLocation(), diag::ext_anonymous_union); 1389 else if (!Record->isUnion()) 1390 Diag(Record->getLocation(), diag::ext_anonymous_struct); 1391 1392 // C and C++ require different kinds of checks for anonymous 1393 // structs/unions. 1394 bool Invalid = false; 1395 if (getLangOptions().CPlusPlus) { 1396 const char* PrevSpec = 0; 1397 // C++ [class.union]p3: 1398 // Anonymous unions declared in a named namespace or in the 1399 // global namespace shall be declared static. 1400 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 1401 (isa<TranslationUnitDecl>(Owner) || 1402 (isa<NamespaceDecl>(Owner) && 1403 cast<NamespaceDecl>(Owner)->getDeclName()))) { 1404 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 1405 Invalid = true; 1406 1407 // Recover by adding 'static'. 1408 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec); 1409 } 1410 // C++ [class.union]p3: 1411 // A storage class is not allowed in a declaration of an 1412 // anonymous union in a class scope. 1413 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1414 isa<RecordDecl>(Owner)) { 1415 Diag(DS.getStorageClassSpecLoc(), 1416 diag::err_anonymous_union_with_storage_spec); 1417 Invalid = true; 1418 1419 // Recover by removing the storage specifier. 1420 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 1421 PrevSpec); 1422 } 1423 1424 // C++ [class.union]p2: 1425 // The member-specification of an anonymous union shall only 1426 // define non-static data members. [Note: nested types and 1427 // functions cannot be declared within an anonymous union. ] 1428 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 1429 MemEnd = Record->decls_end(); 1430 Mem != MemEnd; ++Mem) { 1431 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 1432 // C++ [class.union]p3: 1433 // An anonymous union shall not have private or protected 1434 // members (clause 11). 1435 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) { 1436 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 1437 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 1438 Invalid = true; 1439 } 1440 } else if ((*Mem)->isImplicit()) { 1441 // Any implicit members are fine. 1442 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 1443 // This is a type that showed up in an 1444 // elaborated-type-specifier inside the anonymous struct or 1445 // union, but which actually declares a type outside of the 1446 // anonymous struct or union. It's okay. 1447 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 1448 if (!MemRecord->isAnonymousStructOrUnion() && 1449 MemRecord->getDeclName()) { 1450 // This is a nested type declaration. 1451 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 1452 << (int)Record->isUnion(); 1453 Invalid = true; 1454 } 1455 } else { 1456 // We have something that isn't a non-static data 1457 // member. Complain about it. 1458 unsigned DK = diag::err_anonymous_record_bad_member; 1459 if (isa<TypeDecl>(*Mem)) 1460 DK = diag::err_anonymous_record_with_type; 1461 else if (isa<FunctionDecl>(*Mem)) 1462 DK = diag::err_anonymous_record_with_function; 1463 else if (isa<VarDecl>(*Mem)) 1464 DK = diag::err_anonymous_record_with_static; 1465 Diag((*Mem)->getLocation(), DK) 1466 << (int)Record->isUnion(); 1467 Invalid = true; 1468 } 1469 } 1470 } 1471 1472 if (!Record->isUnion() && !Owner->isRecord()) { 1473 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 1474 << (int)getLangOptions().CPlusPlus; 1475 Invalid = true; 1476 } 1477 1478 // Create a declaration for this anonymous struct/union. 1479 NamedDecl *Anon = 0; 1480 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 1481 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(), 1482 /*IdentifierInfo=*/0, 1483 Context.getTypeDeclType(Record), 1484 /*BitWidth=*/0, /*Mutable=*/false, 1485 DS.getSourceRange().getBegin()); 1486 Anon->setAccess(AS_public); 1487 if (getLangOptions().CPlusPlus) 1488 FieldCollector->Add(cast<FieldDecl>(Anon)); 1489 } else { 1490 VarDecl::StorageClass SC; 1491 switch (DS.getStorageClassSpec()) { 1492 default: assert(0 && "Unknown storage class!"); 1493 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1494 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1495 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1496 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1497 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1498 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1499 case DeclSpec::SCS_mutable: 1500 // mutable can only appear on non-static class members, so it's always 1501 // an error here 1502 Diag(Record->getLocation(), diag::err_mutable_nonmember); 1503 Invalid = true; 1504 SC = VarDecl::None; 1505 break; 1506 } 1507 1508 Anon = VarDecl::Create(Context, Owner, Record->getLocation(), 1509 /*IdentifierInfo=*/0, 1510 Context.getTypeDeclType(Record), 1511 SC, DS.getSourceRange().getBegin()); 1512 } 1513 Anon->setImplicit(); 1514 1515 // Add the anonymous struct/union object to the current 1516 // context. We'll be referencing this object when we refer to one of 1517 // its members. 1518 Owner->addDecl(Anon); 1519 1520 // Inject the members of the anonymous struct/union into the owning 1521 // context and into the identifier resolver chain for name lookup 1522 // purposes. 1523 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record)) 1524 Invalid = true; 1525 1526 // Mark this as an anonymous struct/union type. Note that we do not 1527 // do this until after we have already checked and injected the 1528 // members of this anonymous struct/union type, because otherwise 1529 // the members could be injected twice: once by DeclContext when it 1530 // builds its lookup table, and once by 1531 // InjectAnonymousStructOrUnionMembers. 1532 Record->setAnonymousStructOrUnion(true); 1533 1534 if (Invalid) 1535 Anon->setInvalidDecl(); 1536 1537 return DeclPtrTy::make(Anon); 1538} 1539 1540 1541/// GetNameForDeclarator - Determine the full declaration name for the 1542/// given Declarator. 1543DeclarationName Sema::GetNameForDeclarator(Declarator &D) { 1544 switch (D.getKind()) { 1545 case Declarator::DK_Abstract: 1546 assert(D.getIdentifier() == 0 && "abstract declarators have no name"); 1547 return DeclarationName(); 1548 1549 case Declarator::DK_Normal: 1550 assert (D.getIdentifier() != 0 && "normal declarators have an identifier"); 1551 return DeclarationName(D.getIdentifier()); 1552 1553 case Declarator::DK_Constructor: { 1554 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1555 Ty = Context.getCanonicalType(Ty); 1556 return Context.DeclarationNames.getCXXConstructorName(Ty); 1557 } 1558 1559 case Declarator::DK_Destructor: { 1560 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1561 Ty = Context.getCanonicalType(Ty); 1562 return Context.DeclarationNames.getCXXDestructorName(Ty); 1563 } 1564 1565 case Declarator::DK_Conversion: { 1566 // FIXME: We'd like to keep the non-canonical type for diagnostics! 1567 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1568 Ty = Context.getCanonicalType(Ty); 1569 return Context.DeclarationNames.getCXXConversionFunctionName(Ty); 1570 } 1571 1572 case Declarator::DK_Operator: 1573 assert(D.getIdentifier() == 0 && "operator names have no identifier"); 1574 return Context.DeclarationNames.getCXXOperatorName( 1575 D.getOverloadedOperator()); 1576 } 1577 1578 assert(false && "Unknown name kind"); 1579 return DeclarationName(); 1580} 1581 1582/// isNearlyMatchingFunction - Determine whether the C++ functions 1583/// Declaration and Definition are "nearly" matching. This heuristic 1584/// is used to improve diagnostics in the case where an out-of-line 1585/// function definition doesn't match any declaration within 1586/// the class or namespace. 1587static bool isNearlyMatchingFunction(ASTContext &Context, 1588 FunctionDecl *Declaration, 1589 FunctionDecl *Definition) { 1590 if (Declaration->param_size() != Definition->param_size()) 1591 return false; 1592 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 1593 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 1594 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 1595 1596 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType()); 1597 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType()); 1598 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType()) 1599 return false; 1600 } 1601 1602 return true; 1603} 1604 1605Sema::DeclPtrTy 1606Sema::HandleDeclarator(Scope *S, Declarator &D, 1607 MultiTemplateParamsArg TemplateParamLists, 1608 bool IsFunctionDefinition) { 1609 DeclarationName Name = GetNameForDeclarator(D); 1610 1611 // All of these full declarators require an identifier. If it doesn't have 1612 // one, the ParsedFreeStandingDeclSpec action should be used. 1613 if (!Name) { 1614 if (!D.isInvalidType()) // Reject this if we think it is valid. 1615 Diag(D.getDeclSpec().getSourceRange().getBegin(), 1616 diag::err_declarator_need_ident) 1617 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 1618 return DeclPtrTy(); 1619 } 1620 1621 // The scope passed in may not be a decl scope. Zip up the scope tree until 1622 // we find one that is. 1623 while ((S->getFlags() & Scope::DeclScope) == 0 || 1624 (S->getFlags() & Scope::TemplateParamScope) != 0) 1625 S = S->getParent(); 1626 1627 DeclContext *DC; 1628 NamedDecl *PrevDecl; 1629 NamedDecl *New; 1630 1631 QualType R = GetTypeForDeclarator(D, S); 1632 1633 // See if this is a redefinition of a variable in the same scope. 1634 if (D.getCXXScopeSpec().isInvalid()) { 1635 DC = CurContext; 1636 PrevDecl = 0; 1637 D.setInvalidType(); 1638 } else if (!D.getCXXScopeSpec().isSet()) { 1639 LookupNameKind NameKind = LookupOrdinaryName; 1640 1641 // If the declaration we're planning to build will be a function 1642 // or object with linkage, then look for another declaration with 1643 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 1644 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1645 /* Do nothing*/; 1646 else if (R->isFunctionType()) { 1647 if (CurContext->isFunctionOrMethod() || 1648 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 1649 NameKind = LookupRedeclarationWithLinkage; 1650 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 1651 NameKind = LookupRedeclarationWithLinkage; 1652 else if (CurContext->getLookupContext()->isTranslationUnit() && 1653 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 1654 NameKind = LookupRedeclarationWithLinkage; 1655 1656 DC = CurContext; 1657 PrevDecl = LookupName(S, Name, NameKind, true, 1658 NameKind == LookupRedeclarationWithLinkage, 1659 D.getIdentifierLoc()); 1660 } else { // Something like "int foo::x;" 1661 DC = computeDeclContext(D.getCXXScopeSpec(), true); 1662 // FIXME: RequireCompleteDeclContext(D.getCXXScopeSpec()); ? 1663 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true); 1664 1665 // C++ 7.3.1.2p2: 1666 // Members (including explicit specializations of templates) of a named 1667 // namespace can also be defined outside that namespace by explicit 1668 // qualification of the name being defined, provided that the entity being 1669 // defined was already declared in the namespace and the definition appears 1670 // after the point of declaration in a namespace that encloses the 1671 // declarations namespace. 1672 // 1673 // Note that we only check the context at this point. We don't yet 1674 // have enough information to make sure that PrevDecl is actually 1675 // the declaration we want to match. For example, given: 1676 // 1677 // class X { 1678 // void f(); 1679 // void f(float); 1680 // }; 1681 // 1682 // void X::f(int) { } // ill-formed 1683 // 1684 // In this case, PrevDecl will point to the overload set 1685 // containing the two f's declared in X, but neither of them 1686 // matches. 1687 1688 // First check whether we named the global scope. 1689 if (isa<TranslationUnitDecl>(DC)) { 1690 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 1691 << Name << D.getCXXScopeSpec().getRange(); 1692 } else if (!CurContext->Encloses(DC)) { 1693 // The qualifying scope doesn't enclose the original declaration. 1694 // Emit diagnostic based on current scope. 1695 SourceLocation L = D.getIdentifierLoc(); 1696 SourceRange R = D.getCXXScopeSpec().getRange(); 1697 if (isa<FunctionDecl>(CurContext)) 1698 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 1699 else 1700 Diag(L, diag::err_invalid_declarator_scope) 1701 << Name << cast<NamedDecl>(DC) << R; 1702 D.setInvalidType(); 1703 } 1704 } 1705 1706 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1707 // Maybe we will complain about the shadowed template parameter. 1708 if (!D.isInvalidType()) 1709 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl)) 1710 D.setInvalidType(); 1711 1712 // Just pretend that we didn't see the previous declaration. 1713 PrevDecl = 0; 1714 } 1715 1716 // In C++, the previous declaration we find might be a tag type 1717 // (class or enum). In this case, the new declaration will hide the 1718 // tag type. Note that this does does not apply if we're declaring a 1719 // typedef (C++ [dcl.typedef]p4). 1720 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag && 1721 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 1722 PrevDecl = 0; 1723 1724 bool Redeclaration = false; 1725 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 1726 if (TemplateParamLists.size()) { 1727 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 1728 return DeclPtrTy(); 1729 } 1730 1731 New = ActOnTypedefDeclarator(S, D, DC, R, PrevDecl, Redeclaration); 1732 } else if (R->isFunctionType()) { 1733 New = ActOnFunctionDeclarator(S, D, DC, R, PrevDecl, 1734 move(TemplateParamLists), 1735 IsFunctionDefinition, Redeclaration); 1736 } else { 1737 New = ActOnVariableDeclarator(S, D, DC, R, PrevDecl, 1738 move(TemplateParamLists), 1739 Redeclaration); 1740 } 1741 1742 if (New == 0) 1743 return DeclPtrTy(); 1744 1745 // If this has an identifier and is not an invalid redeclaration, 1746 // add it to the scope stack. 1747 if (Name && !(Redeclaration && New->isInvalidDecl())) 1748 PushOnScopeChains(New, S); 1749 1750 return DeclPtrTy::make(New); 1751} 1752 1753/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 1754/// types into constant array types in certain situations which would otherwise 1755/// be errors (for GCC compatibility). 1756static QualType TryToFixInvalidVariablyModifiedType(QualType T, 1757 ASTContext &Context, 1758 bool &SizeIsNegative) { 1759 // This method tries to turn a variable array into a constant 1760 // array even when the size isn't an ICE. This is necessary 1761 // for compatibility with code that depends on gcc's buggy 1762 // constant expression folding, like struct {char x[(int)(char*)2];} 1763 SizeIsNegative = false; 1764 1765 if (const PointerType* PTy = dyn_cast<PointerType>(T)) { 1766 QualType Pointee = PTy->getPointeeType(); 1767 QualType FixedType = 1768 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative); 1769 if (FixedType.isNull()) return FixedType; 1770 FixedType = Context.getPointerType(FixedType); 1771 FixedType.setCVRQualifiers(T.getCVRQualifiers()); 1772 return FixedType; 1773 } 1774 1775 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 1776 if (!VLATy) 1777 return QualType(); 1778 // FIXME: We should probably handle this case 1779 if (VLATy->getElementType()->isVariablyModifiedType()) 1780 return QualType(); 1781 1782 Expr::EvalResult EvalResult; 1783 if (!VLATy->getSizeExpr() || 1784 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 1785 !EvalResult.Val.isInt()) 1786 return QualType(); 1787 1788 llvm::APSInt &Res = EvalResult.Val.getInt(); 1789 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) { 1790 Expr* ArySizeExpr = VLATy->getSizeExpr(); 1791 // FIXME: here we could "steal" (how?) ArySizeExpr from the VLA, 1792 // so as to transfer ownership to the ConstantArrayWithExpr. 1793 // Alternatively, we could "clone" it (how?). 1794 // Since we don't know how to do things above, we just use the 1795 // very same Expr*. 1796 return Context.getConstantArrayWithExprType(VLATy->getElementType(), 1797 Res, ArySizeExpr, 1798 ArrayType::Normal, 0, 1799 VLATy->getBracketsRange()); 1800 } 1801 1802 SizeIsNegative = true; 1803 return QualType(); 1804} 1805 1806/// \brief Register the given locally-scoped external C declaration so 1807/// that it can be found later for redeclarations 1808void 1809Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl, 1810 Scope *S) { 1811 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 1812 "Decl is not a locally-scoped decl!"); 1813 // Note that we have a locally-scoped external with this name. 1814 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 1815 1816 if (!PrevDecl) 1817 return; 1818 1819 // If there was a previous declaration of this variable, it may be 1820 // in our identifier chain. Update the identifier chain with the new 1821 // declaration. 1822 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 1823 // The previous declaration was found on the identifer resolver 1824 // chain, so remove it from its scope. 1825 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl))) 1826 S = S->getParent(); 1827 1828 if (S) 1829 S->RemoveDecl(DeclPtrTy::make(PrevDecl)); 1830 } 1831} 1832 1833/// \brief Diagnose function specifiers on a declaration of an identifier that 1834/// does not identify a function. 1835void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 1836 // FIXME: We should probably indicate the identifier in question to avoid 1837 // confusion for constructs like "inline int a(), b;" 1838 if (D.getDeclSpec().isInlineSpecified()) 1839 Diag(D.getDeclSpec().getInlineSpecLoc(), 1840 diag::err_inline_non_function); 1841 1842 if (D.getDeclSpec().isVirtualSpecified()) 1843 Diag(D.getDeclSpec().getVirtualSpecLoc(), 1844 diag::err_virtual_non_function); 1845 1846 if (D.getDeclSpec().isExplicitSpecified()) 1847 Diag(D.getDeclSpec().getExplicitSpecLoc(), 1848 diag::err_explicit_non_function); 1849} 1850 1851NamedDecl* 1852Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1853 QualType R, Decl* PrevDecl, bool &Redeclaration) { 1854 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 1855 if (D.getCXXScopeSpec().isSet()) { 1856 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 1857 << D.getCXXScopeSpec().getRange(); 1858 D.setInvalidType(); 1859 // Pretend we didn't see the scope specifier. 1860 DC = 0; 1861 } 1862 1863 if (getLangOptions().CPlusPlus) { 1864 // Check that there are no default arguments (C++ only). 1865 CheckExtraCXXDefaultArguments(D); 1866 } 1867 1868 DiagnoseFunctionSpecifiers(D); 1869 1870 if (D.getDeclSpec().isThreadSpecified()) 1871 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 1872 1873 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R); 1874 if (!NewTD) return 0; 1875 1876 if (D.isInvalidType()) 1877 NewTD->setInvalidDecl(); 1878 1879 // Handle attributes prior to checking for duplicates in MergeVarDecl 1880 ProcessDeclAttributes(S, NewTD, D); 1881 // Merge the decl with the existing one if appropriate. If the decl is 1882 // in an outer scope, it isn't the same thing. 1883 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 1884 Redeclaration = true; 1885 MergeTypeDefDecl(NewTD, PrevDecl); 1886 } 1887 1888 // C99 6.7.7p2: If a typedef name specifies a variably modified type 1889 // then it shall have block scope. 1890 QualType T = NewTD->getUnderlyingType(); 1891 if (T->isVariablyModifiedType()) { 1892 CurFunctionNeedsScopeChecking = true; 1893 1894 if (S->getFnParent() == 0) { 1895 bool SizeIsNegative; 1896 QualType FixedTy = 1897 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative); 1898 if (!FixedTy.isNull()) { 1899 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size); 1900 NewTD->setUnderlyingType(FixedTy); 1901 } else { 1902 if (SizeIsNegative) 1903 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size); 1904 else if (T->isVariableArrayType()) 1905 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope); 1906 else 1907 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope); 1908 NewTD->setInvalidDecl(); 1909 } 1910 } 1911 } 1912 1913 // If this is the C FILE type, notify the AST context. 1914 if (IdentifierInfo *II = NewTD->getIdentifier()) 1915 if (!NewTD->isInvalidDecl() && 1916 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) { 1917 if (II->isStr("FILE")) 1918 Context.setFILEDecl(NewTD); 1919 else if (II->isStr("jmp_buf")) 1920 Context.setjmp_bufDecl(NewTD); 1921 else if (II->isStr("sigjmp_buf")) 1922 Context.setsigjmp_bufDecl(NewTD); 1923 } 1924 1925 return NewTD; 1926} 1927 1928/// \brief Determines whether the given declaration is an out-of-scope 1929/// previous declaration. 1930/// 1931/// This routine should be invoked when name lookup has found a 1932/// previous declaration (PrevDecl) that is not in the scope where a 1933/// new declaration by the same name is being introduced. If the new 1934/// declaration occurs in a local scope, previous declarations with 1935/// linkage may still be considered previous declarations (C99 1936/// 6.2.2p4-5, C++ [basic.link]p6). 1937/// 1938/// \param PrevDecl the previous declaration found by name 1939/// lookup 1940/// 1941/// \param DC the context in which the new declaration is being 1942/// declared. 1943/// 1944/// \returns true if PrevDecl is an out-of-scope previous declaration 1945/// for a new delcaration with the same name. 1946static bool 1947isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 1948 ASTContext &Context) { 1949 if (!PrevDecl) 1950 return 0; 1951 1952 // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which 1953 // case we need to check each of the overloaded functions. 1954 if (!PrevDecl->hasLinkage()) 1955 return false; 1956 1957 if (Context.getLangOptions().CPlusPlus) { 1958 // C++ [basic.link]p6: 1959 // If there is a visible declaration of an entity with linkage 1960 // having the same name and type, ignoring entities declared 1961 // outside the innermost enclosing namespace scope, the block 1962 // scope declaration declares that same entity and receives the 1963 // linkage of the previous declaration. 1964 DeclContext *OuterContext = DC->getLookupContext(); 1965 if (!OuterContext->isFunctionOrMethod()) 1966 // This rule only applies to block-scope declarations. 1967 return false; 1968 else { 1969 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 1970 if (PrevOuterContext->isRecord()) 1971 // We found a member function: ignore it. 1972 return false; 1973 else { 1974 // Find the innermost enclosing namespace for the new and 1975 // previous declarations. 1976 while (!OuterContext->isFileContext()) 1977 OuterContext = OuterContext->getParent(); 1978 while (!PrevOuterContext->isFileContext()) 1979 PrevOuterContext = PrevOuterContext->getParent(); 1980 1981 // The previous declaration is in a different namespace, so it 1982 // isn't the same function. 1983 if (OuterContext->getPrimaryContext() != 1984 PrevOuterContext->getPrimaryContext()) 1985 return false; 1986 } 1987 } 1988 } 1989 1990 return true; 1991} 1992 1993NamedDecl* 1994Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1995 QualType R,NamedDecl* PrevDecl, 1996 MultiTemplateParamsArg TemplateParamLists, 1997 bool &Redeclaration) { 1998 DeclarationName Name = GetNameForDeclarator(D); 1999 2000 // Check that there are no default arguments (C++ only). 2001 if (getLangOptions().CPlusPlus) 2002 CheckExtraCXXDefaultArguments(D); 2003 2004 VarDecl *NewVD; 2005 VarDecl::StorageClass SC; 2006 switch (D.getDeclSpec().getStorageClassSpec()) { 2007 default: assert(0 && "Unknown storage class!"); 2008 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 2009 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 2010 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 2011 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 2012 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 2013 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 2014 case DeclSpec::SCS_mutable: 2015 // mutable can only appear on non-static class members, so it's always 2016 // an error here 2017 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 2018 D.setInvalidType(); 2019 SC = VarDecl::None; 2020 break; 2021 } 2022 2023 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2024 if (!II) { 2025 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 2026 << Name.getAsString(); 2027 return 0; 2028 } 2029 2030 DiagnoseFunctionSpecifiers(D); 2031 2032 if (!DC->isRecord() && S->getFnParent() == 0) { 2033 // C99 6.9p2: The storage-class specifiers auto and register shall not 2034 // appear in the declaration specifiers in an external declaration. 2035 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 2036 2037 // If this is a register variable with an asm label specified, then this 2038 // is a GNU extension. 2039 if (SC == VarDecl::Register && D.getAsmLabel()) 2040 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 2041 else 2042 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 2043 D.setInvalidType(); 2044 } 2045 } 2046 if (DC->isRecord() && !CurContext->isRecord()) { 2047 // This is an out-of-line definition of a static data member. 2048 if (SC == VarDecl::Static) { 2049 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2050 diag::err_static_out_of_line) 2051 << CodeModificationHint::CreateRemoval( 2052 SourceRange(D.getDeclSpec().getStorageClassSpecLoc())); 2053 } else if (SC == VarDecl::None) 2054 SC = VarDecl::Static; 2055 } 2056 if (SC == VarDecl::Static) { 2057 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 2058 if (RD->isLocalClass()) 2059 Diag(D.getIdentifierLoc(), 2060 diag::err_static_data_member_not_allowed_in_local_class) 2061 << Name << RD->getDeclName(); 2062 } 2063 } 2064 2065 // Check that we can declare a template here. 2066 if (TemplateParamLists.size() && 2067 CheckTemplateDeclScope(S, TemplateParamLists)) 2068 return 0; 2069 2070 // Match up the template parameter lists with the scope specifier, then 2071 // determine whether we have a template or a template specialization. 2072 if (TemplateParameterList *TemplateParams 2073 = MatchTemplateParametersToScopeSpecifier( 2074 D.getDeclSpec().getSourceRange().getBegin(), 2075 D.getCXXScopeSpec(), 2076 (TemplateParameterList**)TemplateParamLists.get(), 2077 TemplateParamLists.size())) { 2078 if (TemplateParams->size() > 0) { 2079 // There is no such thing as a variable template. 2080 Diag(D.getIdentifierLoc(), diag::err_template_variable) 2081 << II 2082 << SourceRange(TemplateParams->getTemplateLoc(), 2083 TemplateParams->getRAngleLoc()); 2084 return 0; 2085 } else { 2086 // There is an extraneous 'template<>' for this variable. Complain 2087 // about it, but allow the declaration of the variable. 2088 Diag(TemplateParams->getTemplateLoc(), 2089 diag::err_template_variable_noparams) 2090 << II 2091 << SourceRange(TemplateParams->getTemplateLoc(), 2092 TemplateParams->getRAngleLoc()); 2093 } 2094 } 2095 2096 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 2097 II, R, SC, 2098 // FIXME: Move to DeclGroup... 2099 D.getDeclSpec().getSourceRange().getBegin()); 2100 2101 if (D.isInvalidType()) 2102 NewVD->setInvalidDecl(); 2103 2104 if (D.getDeclSpec().isThreadSpecified()) { 2105 if (NewVD->hasLocalStorage()) 2106 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 2107 else if (!Context.Target.isTLSSupported()) 2108 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 2109 else 2110 NewVD->setThreadSpecified(true); 2111 } 2112 2113 // Set the lexical context. If the declarator has a C++ scope specifier, the 2114 // lexical context will be different from the semantic context. 2115 NewVD->setLexicalDeclContext(CurContext); 2116 2117 // Handle attributes prior to checking for duplicates in MergeVarDecl 2118 ProcessDeclAttributes(S, NewVD, D); 2119 2120 // Handle GNU asm-label extension (encoded as an attribute). 2121 if (Expr *E = (Expr*) D.getAsmLabel()) { 2122 // The parser guarantees this is a string. 2123 StringLiteral *SE = cast<StringLiteral>(E); 2124 NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(), 2125 SE->getByteLength()))); 2126 } 2127 2128 // If name lookup finds a previous declaration that is not in the 2129 // same scope as the new declaration, this may still be an 2130 // acceptable redeclaration. 2131 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) && 2132 !(NewVD->hasLinkage() && 2133 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context))) 2134 PrevDecl = 0; 2135 2136 // Merge the decl with the existing one if appropriate. 2137 if (PrevDecl) { 2138 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) { 2139 // The user tried to define a non-static data member 2140 // out-of-line (C++ [dcl.meaning]p1). 2141 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 2142 << D.getCXXScopeSpec().getRange(); 2143 PrevDecl = 0; 2144 NewVD->setInvalidDecl(); 2145 } 2146 } else if (D.getCXXScopeSpec().isSet()) { 2147 // No previous declaration in the qualifying scope. 2148 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member) 2149 << Name << D.getCXXScopeSpec().getRange(); 2150 NewVD->setInvalidDecl(); 2151 } 2152 2153 CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration); 2154 2155 // attributes declared post-definition are currently ignored 2156 if (PrevDecl) { 2157 const VarDecl *Def = 0, *PrevVD = dyn_cast<VarDecl>(PrevDecl); 2158 if (PrevVD->getDefinition(Def) && D.hasAttributes()) { 2159 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 2160 Diag(Def->getLocation(), diag::note_previous_definition); 2161 } 2162 } 2163 2164 // If this is a locally-scoped extern C variable, update the map of 2165 // such variables. 2166 if (CurContext->isFunctionOrMethod() && NewVD->isExternC(Context) && 2167 !NewVD->isInvalidDecl()) 2168 RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S); 2169 2170 return NewVD; 2171} 2172 2173/// \brief Perform semantic checking on a newly-created variable 2174/// declaration. 2175/// 2176/// This routine performs all of the type-checking required for a 2177/// variable declaration once it has been built. It is used both to 2178/// check variables after they have been parsed and their declarators 2179/// have been translated into a declaration, and to check variables 2180/// that have been instantiated from a template. 2181/// 2182/// Sets NewVD->isInvalidDecl() if an error was encountered. 2183void Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl, 2184 bool &Redeclaration) { 2185 // If the decl is already known invalid, don't check it. 2186 if (NewVD->isInvalidDecl()) 2187 return; 2188 2189 QualType T = NewVD->getType(); 2190 2191 if (T->isObjCInterfaceType()) { 2192 Diag(NewVD->getLocation(), diag::err_statically_allocated_object); 2193 return NewVD->setInvalidDecl(); 2194 } 2195 2196 // The variable can not have an abstract class type. 2197 if (RequireNonAbstractType(NewVD->getLocation(), T, 2198 diag::err_abstract_type_in_decl, 2199 AbstractVariableType)) 2200 return NewVD->setInvalidDecl(); 2201 2202 // Emit an error if an address space was applied to decl with local storage. 2203 // This includes arrays of objects with address space qualifiers, but not 2204 // automatic variables that point to other address spaces. 2205 // ISO/IEC TR 18037 S5.1.2 2206 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) { 2207 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 2208 return NewVD->setInvalidDecl(); 2209 } 2210 2211 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 2212 && !NewVD->hasAttr<BlocksAttr>()) 2213 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 2214 2215 bool isVM = T->isVariablyModifiedType(); 2216 if (isVM || NewVD->hasAttr<CleanupAttr>() || 2217 NewVD->hasAttr<BlocksAttr>()) 2218 CurFunctionNeedsScopeChecking = true; 2219 2220 if ((isVM && NewVD->hasLinkage()) || 2221 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 2222 bool SizeIsNegative; 2223 QualType FixedTy = 2224 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative); 2225 2226 if (FixedTy.isNull() && T->isVariableArrayType()) { 2227 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 2228 // FIXME: This won't give the correct result for 2229 // int a[10][n]; 2230 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 2231 2232 if (NewVD->isFileVarDecl()) 2233 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 2234 << SizeRange; 2235 else if (NewVD->getStorageClass() == VarDecl::Static) 2236 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 2237 << SizeRange; 2238 else 2239 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 2240 << SizeRange; 2241 return NewVD->setInvalidDecl(); 2242 } 2243 2244 if (FixedTy.isNull()) { 2245 if (NewVD->isFileVarDecl()) 2246 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 2247 else 2248 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 2249 return NewVD->setInvalidDecl(); 2250 } 2251 2252 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 2253 NewVD->setType(FixedTy); 2254 } 2255 2256 if (!PrevDecl && NewVD->isExternC(Context)) { 2257 // Since we did not find anything by this name and we're declaring 2258 // an extern "C" variable, look for a non-visible extern "C" 2259 // declaration with the same name. 2260 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 2261 = LocallyScopedExternalDecls.find(NewVD->getDeclName()); 2262 if (Pos != LocallyScopedExternalDecls.end()) 2263 PrevDecl = Pos->second; 2264 } 2265 2266 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 2267 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 2268 << T; 2269 return NewVD->setInvalidDecl(); 2270 } 2271 2272 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 2273 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 2274 return NewVD->setInvalidDecl(); 2275 } 2276 2277 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 2278 Diag(NewVD->getLocation(), diag::err_block_on_vm); 2279 return NewVD->setInvalidDecl(); 2280 } 2281 2282 if (PrevDecl) { 2283 Redeclaration = true; 2284 MergeVarDecl(NewVD, PrevDecl); 2285 } 2286} 2287 2288NamedDecl* 2289Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2290 QualType R, NamedDecl* PrevDecl, 2291 MultiTemplateParamsArg TemplateParamLists, 2292 bool IsFunctionDefinition, bool &Redeclaration) { 2293 assert(R.getTypePtr()->isFunctionType()); 2294 2295 DeclarationName Name = GetNameForDeclarator(D); 2296 FunctionDecl::StorageClass SC = FunctionDecl::None; 2297 switch (D.getDeclSpec().getStorageClassSpec()) { 2298 default: assert(0 && "Unknown storage class!"); 2299 case DeclSpec::SCS_auto: 2300 case DeclSpec::SCS_register: 2301 case DeclSpec::SCS_mutable: 2302 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2303 diag::err_typecheck_sclass_func); 2304 D.setInvalidType(); 2305 break; 2306 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 2307 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 2308 case DeclSpec::SCS_static: { 2309 if (CurContext->getLookupContext()->isFunctionOrMethod()) { 2310 // C99 6.7.1p5: 2311 // The declaration of an identifier for a function that has 2312 // block scope shall have no explicit storage-class specifier 2313 // other than extern 2314 // See also (C++ [dcl.stc]p4). 2315 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2316 diag::err_static_block_func); 2317 SC = FunctionDecl::None; 2318 } else 2319 SC = FunctionDecl::Static; 2320 break; 2321 } 2322 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 2323 } 2324 2325 if (D.getDeclSpec().isThreadSpecified()) 2326 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 2327 2328 bool isInline = D.getDeclSpec().isInlineSpecified(); 2329 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2330 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 2331 2332 // Check that the return type is not an abstract class type. 2333 // For record types, this is done by the AbstractClassUsageDiagnoser once 2334 // the class has been completely parsed. 2335 if (!DC->isRecord() && 2336 RequireNonAbstractType(D.getIdentifierLoc(), 2337 R->getAsFunctionType()->getResultType(), 2338 diag::err_abstract_type_in_decl, 2339 AbstractReturnType)) 2340 D.setInvalidType(); 2341 2342 // Do not allow returning a objc interface by-value. 2343 if (R->getAsFunctionType()->getResultType()->isObjCInterfaceType()) { 2344 Diag(D.getIdentifierLoc(), 2345 diag::err_object_cannot_be_passed_returned_by_value) << 0 2346 << R->getAsFunctionType()->getResultType(); 2347 D.setInvalidType(); 2348 } 2349 2350 // Check that we can declare a template here. 2351 if (TemplateParamLists.size() && 2352 CheckTemplateDeclScope(S, TemplateParamLists)) 2353 return 0; 2354 2355 bool isVirtualOkay = false; 2356 FunctionDecl *NewFD; 2357 if (D.getKind() == Declarator::DK_Constructor) { 2358 // This is a C++ constructor declaration. 2359 assert(DC->isRecord() && 2360 "Constructors can only be declared in a member context"); 2361 2362 R = CheckConstructorDeclarator(D, R, SC); 2363 2364 // Create the new declaration 2365 NewFD = CXXConstructorDecl::Create(Context, 2366 cast<CXXRecordDecl>(DC), 2367 D.getIdentifierLoc(), Name, R, 2368 isExplicit, isInline, 2369 /*isImplicitlyDeclared=*/false); 2370 } else if (D.getKind() == Declarator::DK_Destructor) { 2371 // This is a C++ destructor declaration. 2372 if (DC->isRecord()) { 2373 R = CheckDestructorDeclarator(D, SC); 2374 2375 NewFD = CXXDestructorDecl::Create(Context, 2376 cast<CXXRecordDecl>(DC), 2377 D.getIdentifierLoc(), Name, R, 2378 isInline, 2379 /*isImplicitlyDeclared=*/false); 2380 2381 isVirtualOkay = true; 2382 } else { 2383 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 2384 2385 // Create a FunctionDecl to satisfy the function definition parsing 2386 // code path. 2387 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 2388 Name, R, SC, isInline, 2389 /*hasPrototype=*/true, 2390 // FIXME: Move to DeclGroup... 2391 D.getDeclSpec().getSourceRange().getBegin()); 2392 D.setInvalidType(); 2393 } 2394 } else if (D.getKind() == Declarator::DK_Conversion) { 2395 if (!DC->isRecord()) { 2396 Diag(D.getIdentifierLoc(), 2397 diag::err_conv_function_not_member); 2398 return 0; 2399 } 2400 2401 CheckConversionDeclarator(D, R, SC); 2402 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 2403 D.getIdentifierLoc(), Name, R, 2404 isInline, isExplicit); 2405 2406 isVirtualOkay = true; 2407 } else if (DC->isRecord()) { 2408 // If the of the function is the same as the name of the record, then this 2409 // must be an invalid constructor that has a return type. 2410 // (The parser checks for a return type and makes the declarator a 2411 // constructor if it has no return type). 2412 // must have an invalid constructor that has a return type 2413 if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 2414 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 2415 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2416 << SourceRange(D.getIdentifierLoc()); 2417 return 0; 2418 } 2419 2420 // This is a C++ method declaration. 2421 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 2422 D.getIdentifierLoc(), Name, R, 2423 (SC == FunctionDecl::Static), isInline); 2424 2425 isVirtualOkay = (SC != FunctionDecl::Static); 2426 } else { 2427 // Determine whether the function was written with a 2428 // prototype. This true when: 2429 // - we're in C++ (where every function has a prototype), 2430 // - there is a prototype in the declarator, or 2431 // - the type R of the function is some kind of typedef or other reference 2432 // to a type name (which eventually refers to a function type). 2433 bool HasPrototype = 2434 getLangOptions().CPlusPlus || 2435 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) || 2436 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 2437 2438 NewFD = FunctionDecl::Create(Context, DC, 2439 D.getIdentifierLoc(), 2440 Name, R, SC, isInline, HasPrototype, 2441 // FIXME: Move to DeclGroup... 2442 D.getDeclSpec().getSourceRange().getBegin()); 2443 } 2444 2445 if (D.isInvalidType()) 2446 NewFD->setInvalidDecl(); 2447 2448 // Set the lexical context. If the declarator has a C++ 2449 // scope specifier, the lexical context will be different 2450 // from the semantic context. 2451 NewFD->setLexicalDeclContext(CurContext); 2452 2453 // Match up the template parameter lists with the scope specifier, then 2454 // determine whether we have a template or a template specialization. 2455 FunctionTemplateDecl *FunctionTemplate = 0; 2456 if (TemplateParameterList *TemplateParams 2457 = MatchTemplateParametersToScopeSpecifier( 2458 D.getDeclSpec().getSourceRange().getBegin(), 2459 D.getCXXScopeSpec(), 2460 (TemplateParameterList**)TemplateParamLists.get(), 2461 TemplateParamLists.size())) { 2462 if (TemplateParams->size() > 0) { 2463 // This is a function template 2464 FunctionTemplate = FunctionTemplateDecl::Create(Context, CurContext, 2465 NewFD->getLocation(), 2466 Name, TemplateParams, 2467 NewFD); 2468 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 2469 } else { 2470 // FIXME: Handle function template specializations 2471 } 2472 2473 // FIXME: Free this memory properly. 2474 TemplateParamLists.release(); 2475 } 2476 2477 // C++ [dcl.fct.spec]p5: 2478 // The virtual specifier shall only be used in declarations of 2479 // nonstatic class member functions that appear within a 2480 // member-specification of a class declaration; see 10.3. 2481 // 2482 if (isVirtual && !NewFD->isInvalidDecl()) { 2483 if (!isVirtualOkay) { 2484 Diag(D.getDeclSpec().getVirtualSpecLoc(), 2485 diag::err_virtual_non_function); 2486 } else if (!CurContext->isRecord()) { 2487 // 'virtual' was specified outside of the class. 2488 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class) 2489 << CodeModificationHint::CreateRemoval( 2490 SourceRange(D.getDeclSpec().getVirtualSpecLoc())); 2491 } else { 2492 // Okay: Add virtual to the method. 2493 cast<CXXMethodDecl>(NewFD)->setVirtualAsWritten(true); 2494 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC); 2495 CurClass->setAggregate(false); 2496 CurClass->setPOD(false); 2497 CurClass->setPolymorphic(true); 2498 CurClass->setHasTrivialConstructor(false); 2499 CurClass->setHasTrivialCopyConstructor(false); 2500 CurClass->setHasTrivialCopyAssignment(false); 2501 } 2502 } 2503 2504 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) { 2505 // Look for virtual methods in base classes that this method might override. 2506 2507 BasePaths Paths; 2508 if (LookupInBases(cast<CXXRecordDecl>(DC), 2509 MemberLookupCriteria(NewMD), Paths)) { 2510 for (BasePaths::decl_iterator I = Paths.found_decls_begin(), 2511 E = Paths.found_decls_end(); I != E; ++I) { 2512 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 2513 if (!CheckOverridingFunctionReturnType(NewMD, OldMD) && 2514 !CheckOverridingFunctionExceptionSpec(NewMD, OldMD)) 2515 NewMD->addOverriddenMethod(OldMD); 2516 } 2517 } 2518 } 2519 } 2520 2521 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) && 2522 !CurContext->isRecord()) { 2523 // C++ [class.static]p1: 2524 // A data or function member of a class may be declared static 2525 // in a class definition, in which case it is a static member of 2526 // the class. 2527 2528 // Complain about the 'static' specifier if it's on an out-of-line 2529 // member function definition. 2530 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2531 diag::err_static_out_of_line) 2532 << CodeModificationHint::CreateRemoval( 2533 SourceRange(D.getDeclSpec().getStorageClassSpecLoc())); 2534 } 2535 2536 // Handle GNU asm-label extension (encoded as an attribute). 2537 if (Expr *E = (Expr*) D.getAsmLabel()) { 2538 // The parser guarantees this is a string. 2539 StringLiteral *SE = cast<StringLiteral>(E); 2540 NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(), 2541 SE->getByteLength()))); 2542 } 2543 2544 // Copy the parameter declarations from the declarator D to the function 2545 // declaration NewFD, if they are available. First scavenge them into Params. 2546 llvm::SmallVector<ParmVarDecl*, 16> Params; 2547 if (D.getNumTypeObjects() > 0) { 2548 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2549 2550 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 2551 // function that takes no arguments, not a function that takes a 2552 // single void argument. 2553 // We let through "const void" here because Sema::GetTypeForDeclarator 2554 // already checks for that case. 2555 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2556 FTI.ArgInfo[0].Param && 2557 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) { 2558 // Empty arg list, don't push any params. 2559 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>(); 2560 2561 // In C++, the empty parameter-type-list must be spelled "void"; a 2562 // typedef of void is not permitted. 2563 if (getLangOptions().CPlusPlus && 2564 Param->getType().getUnqualifiedType() != Context.VoidTy) 2565 Diag(Param->getLocation(), diag::err_param_typedef_of_void); 2566 // FIXME: Leaks decl? 2567 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 2568 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2569 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>(); 2570 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 2571 Param->setDeclContext(NewFD); 2572 Params.push_back(Param); 2573 } 2574 } 2575 2576 } else if (const FunctionProtoType *FT = R->getAsFunctionProtoType()) { 2577 // When we're declaring a function with a typedef, typeof, etc as in the 2578 // following example, we'll need to synthesize (unnamed) 2579 // parameters for use in the declaration. 2580 // 2581 // @code 2582 // typedef void fn(int); 2583 // fn f; 2584 // @endcode 2585 2586 // Synthesize a parameter for each argument type. 2587 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 2588 AE = FT->arg_type_end(); AI != AE; ++AI) { 2589 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, 2590 SourceLocation(), 0, 2591 *AI, VarDecl::None, 0); 2592 Param->setImplicit(); 2593 Params.push_back(Param); 2594 } 2595 } else { 2596 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 2597 "Should not need args for typedef of non-prototype fn"); 2598 } 2599 // Finally, we know we have the right number of parameters, install them. 2600 NewFD->setParams(Context, Params.data(), Params.size()); 2601 2602 // If name lookup finds a previous declaration that is not in the 2603 // same scope as the new declaration, this may still be an 2604 // acceptable redeclaration. 2605 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) && 2606 !(NewFD->hasLinkage() && 2607 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context))) 2608 PrevDecl = 0; 2609 2610 // Perform semantic checking on the function declaration. 2611 bool OverloadableAttrRequired = false; // FIXME: HACK! 2612 CheckFunctionDeclaration(NewFD, PrevDecl, Redeclaration, 2613 /*FIXME:*/OverloadableAttrRequired); 2614 2615 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) { 2616 // An out-of-line member function declaration must also be a 2617 // definition (C++ [dcl.meaning]p1). 2618 if (!IsFunctionDefinition) { 2619 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration) 2620 << D.getCXXScopeSpec().getRange(); 2621 NewFD->setInvalidDecl(); 2622 } else if (!Redeclaration && (!PrevDecl || !isa<UsingDecl>(PrevDecl))) { 2623 // The user tried to provide an out-of-line definition for a 2624 // function that is a member of a class or namespace, but there 2625 // was no such member function declared (C++ [class.mfct]p2, 2626 // C++ [namespace.memdef]p2). For example: 2627 // 2628 // class X { 2629 // void f() const; 2630 // }; 2631 // 2632 // void X::f() { } // ill-formed 2633 // 2634 // Complain about this problem, and attempt to suggest close 2635 // matches (e.g., those that differ only in cv-qualifiers and 2636 // whether the parameter types are references). 2637 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 2638 << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange(); 2639 NewFD->setInvalidDecl(); 2640 2641 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName, 2642 true); 2643 assert(!Prev.isAmbiguous() && 2644 "Cannot have an ambiguity in previous-declaration lookup"); 2645 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 2646 Func != FuncEnd; ++Func) { 2647 if (isa<FunctionDecl>(*Func) && 2648 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD)) 2649 Diag((*Func)->getLocation(), diag::note_member_def_close_match); 2650 } 2651 2652 PrevDecl = 0; 2653 } 2654 } 2655 2656 // Handle attributes. We need to have merged decls when handling attributes 2657 // (for example to check for conflicts, etc). 2658 // FIXME: This needs to happen before we merge declarations. Then, 2659 // let attribute merging cope with attribute conflicts. 2660 ProcessDeclAttributes(S, NewFD, D); 2661 2662 // attributes declared post-definition are currently ignored 2663 if (PrevDecl) { 2664 const FunctionDecl *Def, *PrevFD = dyn_cast<FunctionDecl>(PrevDecl); 2665 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) { 2666 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 2667 Diag(Def->getLocation(), diag::note_previous_definition); 2668 } 2669 } 2670 2671 AddKnownFunctionAttributes(NewFD); 2672 2673 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) { 2674 // If a function name is overloadable in C, then every function 2675 // with that name must be marked "overloadable". 2676 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 2677 << Redeclaration << NewFD; 2678 if (PrevDecl) 2679 Diag(PrevDecl->getLocation(), 2680 diag::note_attribute_overloadable_prev_overload); 2681 NewFD->addAttr(::new (Context) OverloadableAttr()); 2682 } 2683 2684 // If this is a locally-scoped extern C function, update the 2685 // map of such names. 2686 if (CurContext->isFunctionOrMethod() && NewFD->isExternC(Context) 2687 && !NewFD->isInvalidDecl()) 2688 RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S); 2689 2690 // Set this FunctionDecl's range up to the right paren. 2691 NewFD->setLocEnd(D.getSourceRange().getEnd()); 2692 2693 if (FunctionTemplate && NewFD->isInvalidDecl()) 2694 FunctionTemplate->setInvalidDecl(); 2695 2696 if (FunctionTemplate) 2697 return FunctionTemplate; 2698 2699 return NewFD; 2700} 2701 2702/// \brief Perform semantic checking of a new function declaration. 2703/// 2704/// Performs semantic analysis of the new function declaration 2705/// NewFD. This routine performs all semantic checking that does not 2706/// require the actual declarator involved in the declaration, and is 2707/// used both for the declaration of functions as they are parsed 2708/// (called via ActOnDeclarator) and for the declaration of functions 2709/// that have been instantiated via C++ template instantiation (called 2710/// via InstantiateDecl). 2711/// 2712/// This sets NewFD->isInvalidDecl() to true if there was an error. 2713void Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl, 2714 bool &Redeclaration, 2715 bool &OverloadableAttrRequired) { 2716 // If NewFD is already known erroneous, don't do any of this checking. 2717 if (NewFD->isInvalidDecl()) 2718 return; 2719 2720 if (NewFD->getResultType()->isVariablyModifiedType()) { 2721 // Functions returning a variably modified type violate C99 6.7.5.2p2 2722 // because all functions have linkage. 2723 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 2724 return NewFD->setInvalidDecl(); 2725 } 2726 2727 if (NewFD->isMain()) CheckMain(NewFD); 2728 2729 // Semantic checking for this function declaration (in isolation). 2730 if (getLangOptions().CPlusPlus) { 2731 // C++-specific checks. 2732 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 2733 CheckConstructor(Constructor); 2734 } else if (isa<CXXDestructorDecl>(NewFD)) { 2735 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent()); 2736 QualType ClassType = Context.getTypeDeclType(Record); 2737 if (!ClassType->isDependentType()) { 2738 ClassType = Context.getCanonicalType(ClassType); 2739 DeclarationName Name 2740 = Context.DeclarationNames.getCXXDestructorName(ClassType); 2741 if (NewFD->getDeclName() != Name) { 2742 Diag(NewFD->getLocation(), diag::err_destructor_name); 2743 return NewFD->setInvalidDecl(); 2744 } 2745 } 2746 Record->setUserDeclaredDestructor(true); 2747 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no 2748 // user-defined destructor. 2749 Record->setPOD(false); 2750 2751 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly- 2752 // declared destructor. 2753 // FIXME: C++0x: don't do this for "= default" destructors 2754 Record->setHasTrivialDestructor(false); 2755 } else if (CXXConversionDecl *Conversion 2756 = dyn_cast<CXXConversionDecl>(NewFD)) 2757 ActOnConversionDeclarator(Conversion); 2758 2759 // Extra checking for C++ overloaded operators (C++ [over.oper]). 2760 if (NewFD->isOverloadedOperator() && 2761 CheckOverloadedOperatorDeclaration(NewFD)) 2762 return NewFD->setInvalidDecl(); 2763 } 2764 2765 // C99 6.7.4p6: 2766 // [... ] For a function with external linkage, the following 2767 // restrictions apply: [...] If all of the file scope declarations 2768 // for a function in a translation unit include the inline 2769 // function specifier without extern, then the definition in that 2770 // translation unit is an inline definition. An inline definition 2771 // does not provide an external definition for the function, and 2772 // does not forbid an external definition in another translation 2773 // unit. 2774 // 2775 // Here we determine whether this function, in isolation, would be a 2776 // C99 inline definition. MergeCompatibleFunctionDecls looks at 2777 // previous declarations. 2778 if (NewFD->isInline() && getLangOptions().C99 && 2779 NewFD->getStorageClass() == FunctionDecl::None && 2780 NewFD->getDeclContext()->getLookupContext()->isTranslationUnit()) 2781 NewFD->setC99InlineDefinition(true); 2782 2783 // Check for a previous declaration of this name. 2784 if (!PrevDecl && NewFD->isExternC(Context)) { 2785 // Since we did not find anything by this name and we're declaring 2786 // an extern "C" function, look for a non-visible extern "C" 2787 // declaration with the same name. 2788 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 2789 = LocallyScopedExternalDecls.find(NewFD->getDeclName()); 2790 if (Pos != LocallyScopedExternalDecls.end()) 2791 PrevDecl = Pos->second; 2792 } 2793 2794 // Merge or overload the declaration with an existing declaration of 2795 // the same name, if appropriate. 2796 if (PrevDecl) { 2797 // Determine whether NewFD is an overload of PrevDecl or 2798 // a declaration that requires merging. If it's an overload, 2799 // there's no more work to do here; we'll just add the new 2800 // function to the scope. 2801 OverloadedFunctionDecl::function_iterator MatchedDecl; 2802 2803 if (!getLangOptions().CPlusPlus && 2804 AllowOverloadingOfFunction(PrevDecl, Context)) { 2805 OverloadableAttrRequired = true; 2806 2807 // Functions marked "overloadable" must have a prototype (that 2808 // we can't get through declaration merging). 2809 if (!NewFD->getType()->getAsFunctionProtoType()) { 2810 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype) 2811 << NewFD; 2812 Redeclaration = true; 2813 2814 // Turn this into a variadic function with no parameters. 2815 QualType R = Context.getFunctionType( 2816 NewFD->getType()->getAsFunctionType()->getResultType(), 2817 0, 0, true, 0); 2818 NewFD->setType(R); 2819 return NewFD->setInvalidDecl(); 2820 } 2821 } 2822 2823 if (PrevDecl && 2824 (!AllowOverloadingOfFunction(PrevDecl, Context) || 2825 !IsOverload(NewFD, PrevDecl, MatchedDecl)) && 2826 !isa<UsingDecl>(PrevDecl)) { 2827 Redeclaration = true; 2828 Decl *OldDecl = PrevDecl; 2829 2830 // If PrevDecl was an overloaded function, extract the 2831 // FunctionDecl that matched. 2832 if (isa<OverloadedFunctionDecl>(PrevDecl)) 2833 OldDecl = *MatchedDecl; 2834 2835 // NewFD and OldDecl represent declarations that need to be 2836 // merged. 2837 if (MergeFunctionDecl(NewFD, OldDecl)) 2838 return NewFD->setInvalidDecl(); 2839 2840 if (FunctionTemplateDecl *OldTemplateDecl 2841 = dyn_cast<FunctionTemplateDecl>(OldDecl)) 2842 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 2843 else { 2844 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 2845 NewFD->setAccess(OldDecl->getAccess()); 2846 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 2847 } 2848 } 2849 } 2850 2851 // In C++, check default arguments now that we have merged decls. Unless 2852 // the lexical context is the class, because in this case this is done 2853 // during delayed parsing anyway. 2854 if (getLangOptions().CPlusPlus && !CurContext->isRecord()) 2855 CheckCXXDefaultArguments(NewFD); 2856} 2857 2858void Sema::CheckMain(FunctionDecl* FD) { 2859 // C++ [basic.start.main]p3: A program that declares main to be inline 2860 // or static is ill-formed. 2861 // C99 6.7.4p4: In a hosted environment, the inline function specifier 2862 // shall not appear in a declaration of main. 2863 // static main is not an error under C99, but we should warn about it. 2864 bool isInline = FD->isInline(); 2865 bool isStatic = FD->getStorageClass() == FunctionDecl::Static; 2866 if (isInline || isStatic) { 2867 unsigned diagID = diag::warn_unusual_main_decl; 2868 if (isInline || getLangOptions().CPlusPlus) 2869 diagID = diag::err_unusual_main_decl; 2870 2871 int which = isStatic + (isInline << 1) - 1; 2872 Diag(FD->getLocation(), diagID) << which; 2873 } 2874 2875 QualType T = FD->getType(); 2876 assert(T->isFunctionType() && "function decl is not of function type"); 2877 const FunctionType* FT = T->getAsFunctionType(); 2878 2879 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 2880 // TODO: add a replacement fixit to turn the return type into 'int'. 2881 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 2882 FD->setInvalidDecl(true); 2883 } 2884 2885 // Treat protoless main() as nullary. 2886 if (isa<FunctionNoProtoType>(FT)) return; 2887 2888 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 2889 unsigned nparams = FTP->getNumArgs(); 2890 assert(FD->getNumParams() == nparams); 2891 2892 if (nparams > 3) { 2893 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 2894 FD->setInvalidDecl(true); 2895 nparams = 3; 2896 } 2897 2898 // FIXME: a lot of the following diagnostics would be improved 2899 // if we had some location information about types. 2900 2901 QualType CharPP = 2902 Context.getPointerType(Context.getPointerType(Context.CharTy)); 2903 QualType Expected[] = { Context.IntTy, CharPP, CharPP }; 2904 2905 for (unsigned i = 0; i < nparams; ++i) { 2906 QualType AT = FTP->getArgType(i); 2907 2908 bool mismatch = true; 2909 2910 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 2911 mismatch = false; 2912 else if (Expected[i] == CharPP) { 2913 // As an extension, the following forms are okay: 2914 // char const ** 2915 // char const * const * 2916 // char * const * 2917 2918 QualifierSet qs; 2919 const PointerType* PT; 2920 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 2921 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 2922 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 2923 qs.removeConst(); 2924 mismatch = !qs.empty(); 2925 } 2926 } 2927 2928 if (mismatch) { 2929 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 2930 // TODO: suggest replacing given type with expected type 2931 FD->setInvalidDecl(true); 2932 } 2933 } 2934 2935 if (nparams == 1 && !FD->isInvalidDecl()) { 2936 Diag(FD->getLocation(), diag::warn_main_one_arg); 2937 } 2938} 2939 2940bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 2941 // FIXME: Need strict checking. In C89, we need to check for 2942 // any assignment, increment, decrement, function-calls, or 2943 // commas outside of a sizeof. In C99, it's the same list, 2944 // except that the aforementioned are allowed in unevaluated 2945 // expressions. Everything else falls under the 2946 // "may accept other forms of constant expressions" exception. 2947 // (We never end up here for C++, so the constant expression 2948 // rules there don't matter.) 2949 if (Init->isConstantInitializer(Context)) 2950 return false; 2951 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 2952 << Init->getSourceRange(); 2953 return true; 2954} 2955 2956void Sema::AddInitializerToDecl(DeclPtrTy dcl, FullExprArg init) { 2957 AddInitializerToDecl(dcl, init.release(), /*DirectInit=*/false); 2958} 2959 2960/// AddInitializerToDecl - Adds the initializer Init to the 2961/// declaration dcl. If DirectInit is true, this is C++ direct 2962/// initialization rather than copy initialization. 2963void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) { 2964 Decl *RealDecl = dcl.getAs<Decl>(); 2965 // If there is no declaration, there was an error parsing it. Just ignore 2966 // the initializer. 2967 if (RealDecl == 0) 2968 return; 2969 2970 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 2971 // With declarators parsed the way they are, the parser cannot 2972 // distinguish between a normal initializer and a pure-specifier. 2973 // Thus this grotesque test. 2974 IntegerLiteral *IL; 2975 Expr *Init = static_cast<Expr *>(init.get()); 2976 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 2977 Context.getCanonicalType(IL->getType()) == Context.IntTy) { 2978 if (Method->isVirtualAsWritten()) { 2979 Method->setPure(); 2980 2981 // A class is abstract if at least one function is pure virtual. 2982 cast<CXXRecordDecl>(CurContext)->setAbstract(true); 2983 } else if (!Method->isInvalidDecl()) { 2984 Diag(Method->getLocation(), diag::err_non_virtual_pure) 2985 << Method->getDeclName() << Init->getSourceRange(); 2986 Method->setInvalidDecl(); 2987 } 2988 } else { 2989 Diag(Method->getLocation(), diag::err_member_function_initialization) 2990 << Method->getDeclName() << Init->getSourceRange(); 2991 Method->setInvalidDecl(); 2992 } 2993 return; 2994 } 2995 2996 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 2997 if (!VDecl) { 2998 if (getLangOptions().CPlusPlus && 2999 RealDecl->getLexicalDeclContext()->isRecord() && 3000 isa<NamedDecl>(RealDecl)) 3001 Diag(RealDecl->getLocation(), diag::err_member_initialization) 3002 << cast<NamedDecl>(RealDecl)->getDeclName(); 3003 else 3004 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 3005 RealDecl->setInvalidDecl(); 3006 return; 3007 } 3008 3009 if (!VDecl->getType()->isArrayType() && 3010 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 3011 diag::err_typecheck_decl_incomplete_type)) { 3012 RealDecl->setInvalidDecl(); 3013 return; 3014 } 3015 3016 const VarDecl *Def = 0; 3017 if (VDecl->getDefinition(Def)) { 3018 Diag(VDecl->getLocation(), diag::err_redefinition) 3019 << VDecl->getDeclName(); 3020 Diag(Def->getLocation(), diag::note_previous_definition); 3021 VDecl->setInvalidDecl(); 3022 return; 3023 } 3024 3025 // Take ownership of the expression, now that we're sure we have somewhere 3026 // to put it. 3027 Expr *Init = init.takeAs<Expr>(); 3028 assert(Init && "missing initializer"); 3029 3030 // Get the decls type and save a reference for later, since 3031 // CheckInitializerTypes may change it. 3032 QualType DclT = VDecl->getType(), SavT = DclT; 3033 if (VDecl->isBlockVarDecl()) { 3034 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 3035 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 3036 VDecl->setInvalidDecl(); 3037 } else if (!VDecl->isInvalidDecl()) { 3038 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 3039 VDecl->getDeclName(), DirectInit)) 3040 VDecl->setInvalidDecl(); 3041 3042 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 3043 // Don't check invalid declarations to avoid emitting useless diagnostics. 3044 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 3045 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4. 3046 CheckForConstantInitializer(Init, DclT); 3047 } 3048 } 3049 } else if (VDecl->isStaticDataMember() && 3050 VDecl->getLexicalDeclContext()->isRecord()) { 3051 // This is an in-class initialization for a static data member, e.g., 3052 // 3053 // struct S { 3054 // static const int value = 17; 3055 // }; 3056 3057 // Attach the initializer 3058 VDecl->setInit(Context, Init); 3059 3060 // C++ [class.mem]p4: 3061 // A member-declarator can contain a constant-initializer only 3062 // if it declares a static member (9.4) of const integral or 3063 // const enumeration type, see 9.4.2. 3064 QualType T = VDecl->getType(); 3065 if (!T->isDependentType() && 3066 (!Context.getCanonicalType(T).isConstQualified() || 3067 !T->isIntegralType())) { 3068 Diag(VDecl->getLocation(), diag::err_member_initialization) 3069 << VDecl->getDeclName() << Init->getSourceRange(); 3070 VDecl->setInvalidDecl(); 3071 } else { 3072 // C++ [class.static.data]p4: 3073 // If a static data member is of const integral or const 3074 // enumeration type, its declaration in the class definition 3075 // can specify a constant-initializer which shall be an 3076 // integral constant expression (5.19). 3077 if (!Init->isTypeDependent() && 3078 !Init->getType()->isIntegralType()) { 3079 // We have a non-dependent, non-integral or enumeration type. 3080 Diag(Init->getSourceRange().getBegin(), 3081 diag::err_in_class_initializer_non_integral_type) 3082 << Init->getType() << Init->getSourceRange(); 3083 VDecl->setInvalidDecl(); 3084 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) { 3085 // Check whether the expression is a constant expression. 3086 llvm::APSInt Value; 3087 SourceLocation Loc; 3088 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) { 3089 Diag(Loc, diag::err_in_class_initializer_non_constant) 3090 << Init->getSourceRange(); 3091 VDecl->setInvalidDecl(); 3092 } else if (!VDecl->getType()->isDependentType()) 3093 ImpCastExprToType(Init, VDecl->getType()); 3094 } 3095 } 3096 } else if (VDecl->isFileVarDecl()) { 3097 if (VDecl->getStorageClass() == VarDecl::Extern) 3098 Diag(VDecl->getLocation(), diag::warn_extern_init); 3099 if (!VDecl->isInvalidDecl()) 3100 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 3101 VDecl->getDeclName(), DirectInit)) 3102 VDecl->setInvalidDecl(); 3103 3104 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 3105 // Don't check invalid declarations to avoid emitting useless diagnostics. 3106 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 3107 // C99 6.7.8p4. All file scoped initializers need to be constant. 3108 CheckForConstantInitializer(Init, DclT); 3109 } 3110 } 3111 // If the type changed, it means we had an incomplete type that was 3112 // completed by the initializer. For example: 3113 // int ary[] = { 1, 3, 5 }; 3114 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 3115 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 3116 VDecl->setType(DclT); 3117 Init->setType(DclT); 3118 } 3119 3120 // Attach the initializer to the decl. 3121 VDecl->setInit(Context, Init); 3122 3123 // If the previous declaration of VDecl was a tentative definition, 3124 // remove it from the set of tentative definitions. 3125 if (VDecl->getPreviousDeclaration() && 3126 VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) { 3127 llvm::DenseMap<DeclarationName, VarDecl *>::iterator Pos 3128 = TentativeDefinitions.find(VDecl->getDeclName()); 3129 assert(Pos != TentativeDefinitions.end() && 3130 "Unrecorded tentative definition?"); 3131 TentativeDefinitions.erase(Pos); 3132 } 3133 3134 return; 3135} 3136 3137void Sema::ActOnUninitializedDecl(DeclPtrTy dcl, 3138 bool TypeContainsUndeducedAuto) { 3139 Decl *RealDecl = dcl.getAs<Decl>(); 3140 3141 // If there is no declaration, there was an error parsing it. Just ignore it. 3142 if (RealDecl == 0) 3143 return; 3144 3145 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 3146 QualType Type = Var->getType(); 3147 3148 // Record tentative definitions. 3149 if (Var->isTentativeDefinition(Context)) 3150 TentativeDefinitions[Var->getDeclName()] = Var; 3151 3152 // C++ [dcl.init.ref]p3: 3153 // The initializer can be omitted for a reference only in a 3154 // parameter declaration (8.3.5), in the declaration of a 3155 // function return type, in the declaration of a class member 3156 // within its class declaration (9.2), and where the extern 3157 // specifier is explicitly used. 3158 if (Type->isReferenceType() && !Var->hasExternalStorage()) { 3159 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 3160 << Var->getDeclName() 3161 << SourceRange(Var->getLocation(), Var->getLocation()); 3162 Var->setInvalidDecl(); 3163 return; 3164 } 3165 3166 // C++0x [dcl.spec.auto]p3 3167 if (TypeContainsUndeducedAuto) { 3168 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 3169 << Var->getDeclName() << Type; 3170 Var->setInvalidDecl(); 3171 return; 3172 } 3173 3174 // C++ [dcl.init]p9: 3175 // 3176 // If no initializer is specified for an object, and the object 3177 // is of (possibly cv-qualified) non-POD class type (or array 3178 // thereof), the object shall be default-initialized; if the 3179 // object is of const-qualified type, the underlying class type 3180 // shall have a user-declared default constructor. 3181 if (getLangOptions().CPlusPlus) { 3182 QualType InitType = Type; 3183 if (const ArrayType *Array = Context.getAsArrayType(Type)) 3184 InitType = Array->getElementType(); 3185 if ((!Var->hasExternalStorage() && !Var->isExternC(Context)) && 3186 InitType->isRecordType() && !InitType->isDependentType()) { 3187 CXXRecordDecl *RD = 3188 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl()); 3189 CXXConstructorDecl *Constructor = 0; 3190 if (!RequireCompleteType(Var->getLocation(), InitType, 3191 diag::err_invalid_incomplete_type_use)) 3192 Constructor 3193 = PerformInitializationByConstructor(InitType, 0, 0, 3194 Var->getLocation(), 3195 SourceRange(Var->getLocation(), 3196 Var->getLocation()), 3197 Var->getDeclName(), 3198 IK_Default); 3199 if (!Constructor) 3200 Var->setInvalidDecl(); 3201 else { 3202 if (!RD->hasTrivialConstructor()) 3203 InitializeVarWithConstructor(Var, Constructor, InitType, 0, 0); 3204 // FIXME. Must do all that is needed to destroy the object 3205 // on scope exit. For now, just mark the destructor as used. 3206 MarkDestructorReferenced(Var->getLocation(), InitType); 3207 } 3208 } 3209 } 3210 3211#if 0 3212 // FIXME: Temporarily disabled because we are not properly parsing 3213 // linkage specifications on declarations, e.g., 3214 // 3215 // extern "C" const CGPoint CGPointerZero; 3216 // 3217 // C++ [dcl.init]p9: 3218 // 3219 // If no initializer is specified for an object, and the 3220 // object is of (possibly cv-qualified) non-POD class type (or 3221 // array thereof), the object shall be default-initialized; if 3222 // the object is of const-qualified type, the underlying class 3223 // type shall have a user-declared default 3224 // constructor. Otherwise, if no initializer is specified for 3225 // an object, the object and its subobjects, if any, have an 3226 // indeterminate initial value; if the object or any of its 3227 // subobjects are of const-qualified type, the program is 3228 // ill-formed. 3229 // 3230 // This isn't technically an error in C, so we don't diagnose it. 3231 // 3232 // FIXME: Actually perform the POD/user-defined default 3233 // constructor check. 3234 if (getLangOptions().CPlusPlus && 3235 Context.getCanonicalType(Type).isConstQualified() && 3236 !Var->hasExternalStorage()) 3237 Diag(Var->getLocation(), diag::err_const_var_requires_init) 3238 << Var->getName() 3239 << SourceRange(Var->getLocation(), Var->getLocation()); 3240#endif 3241 } 3242} 3243 3244Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 3245 DeclPtrTy *Group, 3246 unsigned NumDecls) { 3247 llvm::SmallVector<Decl*, 8> Decls; 3248 3249 if (DS.isTypeSpecOwned()) 3250 Decls.push_back((Decl*)DS.getTypeRep()); 3251 3252 for (unsigned i = 0; i != NumDecls; ++i) 3253 if (Decl *D = Group[i].getAs<Decl>()) 3254 Decls.push_back(D); 3255 3256 // Perform semantic analysis that depends on having fully processed both 3257 // the declarator and initializer. 3258 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 3259 VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]); 3260 if (!IDecl) 3261 continue; 3262 QualType T = IDecl->getType(); 3263 3264 // Block scope. C99 6.7p7: If an identifier for an object is declared with 3265 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 3266 if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) { 3267 if (!IDecl->isInvalidDecl() && 3268 RequireCompleteType(IDecl->getLocation(), T, 3269 diag::err_typecheck_decl_incomplete_type)) 3270 IDecl->setInvalidDecl(); 3271 } 3272 // File scope. C99 6.9.2p2: A declaration of an identifier for an 3273 // object that has file scope without an initializer, and without a 3274 // storage-class specifier or with the storage-class specifier "static", 3275 // constitutes a tentative definition. Note: A tentative definition with 3276 // external linkage is valid (C99 6.2.2p5). 3277 if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) { 3278 if (const IncompleteArrayType *ArrayT 3279 = Context.getAsIncompleteArrayType(T)) { 3280 if (RequireCompleteType(IDecl->getLocation(), 3281 ArrayT->getElementType(), 3282 diag::err_illegal_decl_array_incomplete_type)) 3283 IDecl->setInvalidDecl(); 3284 } 3285 else if (IDecl->getStorageClass() == VarDecl::Static) { 3286 // C99 6.9.2p3: If the declaration of an identifier for an object is 3287 // a tentative definition and has internal linkage (C99 6.2.2p3), the 3288 // declared type shall not be an incomplete type. 3289 // NOTE: code such as the following 3290 // static struct s; 3291 // struct s { int a; }; 3292 // is accepted by gcc. Hence here we issue a warning instead of 3293 // an error and we do not invalidate the static declaration. 3294 // NOTE: to avoid multiple warnings, only check the first declaration. 3295 if (IDecl->getPreviousDeclaration() == 0) 3296 RequireCompleteType(IDecl->getLocation(), T, 3297 diag::ext_typecheck_decl_incomplete_type); 3298 } 3299 } 3300 } 3301 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, 3302 Decls.data(), Decls.size())); 3303} 3304 3305 3306/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 3307/// to introduce parameters into function prototype scope. 3308Sema::DeclPtrTy 3309Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 3310 const DeclSpec &DS = D.getDeclSpec(); 3311 3312 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 3313 VarDecl::StorageClass StorageClass = VarDecl::None; 3314 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 3315 StorageClass = VarDecl::Register; 3316 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 3317 Diag(DS.getStorageClassSpecLoc(), 3318 diag::err_invalid_storage_class_in_func_decl); 3319 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3320 } 3321 3322 if (D.getDeclSpec().isThreadSpecified()) 3323 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3324 3325 DiagnoseFunctionSpecifiers(D); 3326 3327 // Check that there are no default arguments inside the type of this 3328 // parameter (C++ only). 3329 if (getLangOptions().CPlusPlus) 3330 CheckExtraCXXDefaultArguments(D); 3331 3332 TagDecl *OwnedDecl = 0; 3333 QualType parmDeclType = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedDecl); 3334 3335 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) { 3336 // C++ [dcl.fct]p6: 3337 // Types shall not be defined in return or parameter types. 3338 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type) 3339 << Context.getTypeDeclType(OwnedDecl); 3340 } 3341 3342 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 3343 // Can this happen for params? We already checked that they don't conflict 3344 // among each other. Here they can only shadow globals, which is ok. 3345 IdentifierInfo *II = D.getIdentifier(); 3346 if (II) { 3347 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 3348 if (PrevDecl->isTemplateParameter()) { 3349 // Maybe we will complain about the shadowed template parameter. 3350 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 3351 // Just pretend that we didn't see the previous declaration. 3352 PrevDecl = 0; 3353 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) { 3354 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 3355 3356 // Recover by removing the name 3357 II = 0; 3358 D.SetIdentifier(0, D.getIdentifierLoc()); 3359 } 3360 } 3361 } 3362 3363 // Parameters can not be abstract class types. 3364 // For record types, this is done by the AbstractClassUsageDiagnoser once 3365 // the class has been completely parsed. 3366 if (!CurContext->isRecord() && 3367 RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType, 3368 diag::err_abstract_type_in_decl, 3369 AbstractParamType)) 3370 D.setInvalidType(true); 3371 3372 QualType T = adjustParameterType(parmDeclType); 3373 3374 ParmVarDecl *New; 3375 if (T == parmDeclType) // parameter type did not need adjustment 3376 New = ParmVarDecl::Create(Context, CurContext, 3377 D.getIdentifierLoc(), II, 3378 parmDeclType, StorageClass, 3379 0); 3380 else // keep track of both the adjusted and unadjusted types 3381 New = OriginalParmVarDecl::Create(Context, CurContext, 3382 D.getIdentifierLoc(), II, T, 3383 parmDeclType, StorageClass, 0); 3384 3385 if (D.isInvalidType()) 3386 New->setInvalidDecl(); 3387 3388 // Parameter declarators cannot be interface types. All ObjC objects are 3389 // passed by reference. 3390 if (T->isObjCInterfaceType()) { 3391 Diag(D.getIdentifierLoc(), 3392 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T; 3393 New->setInvalidDecl(); 3394 } 3395 3396 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 3397 if (D.getCXXScopeSpec().isSet()) { 3398 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 3399 << D.getCXXScopeSpec().getRange(); 3400 New->setInvalidDecl(); 3401 } 3402 3403 // Add the parameter declaration into this scope. 3404 S->AddDecl(DeclPtrTy::make(New)); 3405 if (II) 3406 IdResolver.AddDecl(New); 3407 3408 ProcessDeclAttributes(S, New, D); 3409 3410 if (New->hasAttr<BlocksAttr>()) { 3411 Diag(New->getLocation(), diag::err_block_on_nonlocal); 3412 } 3413 return DeclPtrTy::make(New); 3414} 3415 3416void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 3417 SourceLocation LocAfterDecls) { 3418 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 3419 "Not a function declarator!"); 3420 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3421 3422 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 3423 // for a K&R function. 3424 if (!FTI.hasPrototype) { 3425 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 3426 --i; 3427 if (FTI.ArgInfo[i].Param == 0) { 3428 std::string Code = " int "; 3429 Code += FTI.ArgInfo[i].Ident->getName(); 3430 Code += ";\n"; 3431 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 3432 << FTI.ArgInfo[i].Ident 3433 << CodeModificationHint::CreateInsertion(LocAfterDecls, Code); 3434 3435 // Implicitly declare the argument as type 'int' for lack of a better 3436 // type. 3437 DeclSpec DS; 3438 const char* PrevSpec; // unused 3439 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 3440 PrevSpec); 3441 Declarator ParamD(DS, Declarator::KNRTypeListContext); 3442 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 3443 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 3444 } 3445 } 3446 } 3447} 3448 3449Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 3450 Declarator &D) { 3451 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 3452 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 3453 "Not a function declarator!"); 3454 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3455 3456 if (FTI.hasPrototype) { 3457 // FIXME: Diagnose arguments without names in C. 3458 } 3459 3460 Scope *ParentScope = FnBodyScope->getParent(); 3461 3462 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 3463 MultiTemplateParamsArg(*this), 3464 /*IsFunctionDefinition=*/true); 3465 return ActOnStartOfFunctionDef(FnBodyScope, DP); 3466} 3467 3468Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) { 3469 if (!D) 3470 return D; 3471 FunctionDecl *FD = cast<FunctionDecl>(D.getAs<Decl>()); 3472 3473 CurFunctionNeedsScopeChecking = false; 3474 3475 // See if this is a redefinition. 3476 const FunctionDecl *Definition; 3477 if (FD->getBody(Definition)) { 3478 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 3479 Diag(Definition->getLocation(), diag::note_previous_definition); 3480 } 3481 3482 // Builtin functions cannot be defined. 3483 if (unsigned BuiltinID = FD->getBuiltinID(Context)) { 3484 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3485 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 3486 FD->setInvalidDecl(); 3487 } 3488 } 3489 3490 // The return type of a function definition must be complete 3491 // (C99 6.9.1p3, C++ [dcl.fct]p6). 3492 QualType ResultType = FD->getResultType(); 3493 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 3494 !FD->isInvalidDecl() && 3495 RequireCompleteType(FD->getLocation(), ResultType, 3496 diag::err_func_def_incomplete_result)) 3497 FD->setInvalidDecl(); 3498 3499 // GNU warning -Wmissing-prototypes: 3500 // Warn if a global function is defined without a previous 3501 // prototype declaration. This warning is issued even if the 3502 // definition itself provides a prototype. The aim is to detect 3503 // global functions that fail to be declared in header files. 3504 if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) && 3505 !FD->isMain()) { 3506 bool MissingPrototype = true; 3507 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 3508 Prev; Prev = Prev->getPreviousDeclaration()) { 3509 // Ignore any declarations that occur in function or method 3510 // scope, because they aren't visible from the header. 3511 if (Prev->getDeclContext()->isFunctionOrMethod()) 3512 continue; 3513 3514 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 3515 break; 3516 } 3517 3518 if (MissingPrototype) 3519 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 3520 } 3521 3522 if (FnBodyScope) 3523 PushDeclContext(FnBodyScope, FD); 3524 3525 // Check the validity of our function parameters 3526 CheckParmsForFunctionDef(FD); 3527 3528 // Introduce our parameters into the function scope 3529 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 3530 ParmVarDecl *Param = FD->getParamDecl(p); 3531 Param->setOwningFunction(FD); 3532 3533 // If this has an identifier, add it to the scope stack. 3534 if (Param->getIdentifier() && FnBodyScope) 3535 PushOnScopeChains(Param, FnBodyScope); 3536 } 3537 3538 // Checking attributes of current function definition 3539 // dllimport attribute. 3540 if (FD->getAttr<DLLImportAttr>() && 3541 (!FD->getAttr<DLLExportAttr>())) { 3542 // dllimport attribute cannot be applied to definition. 3543 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) { 3544 Diag(FD->getLocation(), 3545 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 3546 << "dllimport"; 3547 FD->setInvalidDecl(); 3548 return DeclPtrTy::make(FD); 3549 } else { 3550 // If a symbol previously declared dllimport is later defined, the 3551 // attribute is ignored in subsequent references, and a warning is 3552 // emitted. 3553 Diag(FD->getLocation(), 3554 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 3555 << FD->getNameAsCString() << "dllimport"; 3556 } 3557 } 3558 return DeclPtrTy::make(FD); 3559} 3560 3561Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) { 3562 return ActOnFinishFunctionBody(D, move(BodyArg), false); 3563} 3564 3565Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg, 3566 bool IsInstantiation) { 3567 Decl *dcl = D.getAs<Decl>(); 3568 Stmt *Body = BodyArg.takeAs<Stmt>(); 3569 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 3570 FD->setBody(Body); 3571 if (FD->isMain()) 3572 // C and C++ allow for main to automagically return 0. 3573 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 3574 FD->setHasImplicitReturnZero(true); 3575 else 3576 CheckFallThroughForFunctionDef(FD, Body); 3577 3578 if (!FD->isInvalidDecl()) 3579 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 3580 3581 // C++ [basic.def.odr]p2: 3582 // [...] A virtual member function is used if it is not pure. [...] 3583 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 3584 if (Method->isVirtual() && !Method->isPure()) 3585 MarkDeclarationReferenced(Method->getLocation(), Method); 3586 3587 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 3588 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 3589 assert(MD == getCurMethodDecl() && "Method parsing confused"); 3590 MD->setBody(Body); 3591 CheckFallThroughForFunctionDef(MD, Body); 3592 MD->setEndLoc(Body->getLocEnd()); 3593 3594 if (!MD->isInvalidDecl()) 3595 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 3596 } else { 3597 Body->Destroy(Context); 3598 return DeclPtrTy(); 3599 } 3600 if (!IsInstantiation) 3601 PopDeclContext(); 3602 3603 // Verify and clean out per-function state. 3604 3605 assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?"); 3606 3607 // Check goto/label use. 3608 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 3609 I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) { 3610 LabelStmt *L = I->second; 3611 3612 // Verify that we have no forward references left. If so, there was a goto 3613 // or address of a label taken, but no definition of it. Label fwd 3614 // definitions are indicated with a null substmt. 3615 if (L->getSubStmt() != 0) 3616 continue; 3617 3618 // Emit error. 3619 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 3620 3621 // At this point, we have gotos that use the bogus label. Stitch it into 3622 // the function body so that they aren't leaked and that the AST is well 3623 // formed. 3624 if (Body == 0) { 3625 // The whole function wasn't parsed correctly, just delete this. 3626 L->Destroy(Context); 3627 continue; 3628 } 3629 3630 // Otherwise, the body is valid: we want to stitch the label decl into the 3631 // function somewhere so that it is properly owned and so that the goto 3632 // has a valid target. Do this by creating a new compound stmt with the 3633 // label in it. 3634 3635 // Give the label a sub-statement. 3636 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc())); 3637 3638 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ? 3639 cast<CXXTryStmt>(Body)->getTryBlock() : 3640 cast<CompoundStmt>(Body); 3641 std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end()); 3642 Elements.push_back(L); 3643 Compound->setStmts(Context, &Elements[0], Elements.size()); 3644 } 3645 FunctionLabelMap.clear(); 3646 3647 if (!Body) return D; 3648 3649 // Verify that that gotos and switch cases don't jump into scopes illegally. 3650 if (CurFunctionNeedsScopeChecking) 3651 DiagnoseInvalidJumps(Body); 3652 3653 // C++ constructors that have function-try-blocks can't have return 3654 // statements in the handlers of that block. (C++ [except.handle]p14) 3655 // Verify this. 3656 if (isa<CXXConstructorDecl>(dcl) && isa<CXXTryStmt>(Body)) 3657 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 3658 3659 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) 3660 Destructor->computeBaseOrMembersToDestroy(Context); 3661 return D; 3662} 3663 3664/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 3665/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 3666NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 3667 IdentifierInfo &II, Scope *S) { 3668 // Before we produce a declaration for an implicitly defined 3669 // function, see whether there was a locally-scoped declaration of 3670 // this name as a function or variable. If so, use that 3671 // (non-visible) declaration, and complain about it. 3672 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3673 = LocallyScopedExternalDecls.find(&II); 3674 if (Pos != LocallyScopedExternalDecls.end()) { 3675 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 3676 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 3677 return Pos->second; 3678 } 3679 3680 // Extension in C99. Legal in C90, but warn about it. 3681 if (getLangOptions().C99) 3682 Diag(Loc, diag::ext_implicit_function_decl) << &II; 3683 else 3684 Diag(Loc, diag::warn_implicit_function_decl) << &II; 3685 3686 // FIXME: handle stuff like: 3687 // void foo() { extern float X(); } 3688 // void bar() { X(); } <-- implicit decl for X in another scope. 3689 3690 // Set a Declarator for the implicit definition: int foo(); 3691 const char *Dummy; 3692 DeclSpec DS; 3693 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 3694 Error = Error; // Silence warning. 3695 assert(!Error && "Error setting up implicit decl!"); 3696 Declarator D(DS, Declarator::BlockContext); 3697 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 3698 0, 0, false, SourceLocation(), 3699 false, 0,0,0, Loc, D), 3700 SourceLocation()); 3701 D.SetIdentifier(&II, Loc); 3702 3703 // Insert this function into translation-unit scope. 3704 3705 DeclContext *PrevDC = CurContext; 3706 CurContext = Context.getTranslationUnitDecl(); 3707 3708 FunctionDecl *FD = 3709 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>()); 3710 FD->setImplicit(); 3711 3712 CurContext = PrevDC; 3713 3714 AddKnownFunctionAttributes(FD); 3715 3716 return FD; 3717} 3718 3719/// \brief Adds any function attributes that we know a priori based on 3720/// the declaration of this function. 3721/// 3722/// These attributes can apply both to implicitly-declared builtins 3723/// (like __builtin___printf_chk) or to library-declared functions 3724/// like NSLog or printf. 3725void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 3726 if (FD->isInvalidDecl()) 3727 return; 3728 3729 // If this is a built-in function, map its builtin attributes to 3730 // actual attributes. 3731 if (unsigned BuiltinID = FD->getBuiltinID(Context)) { 3732 // Handle printf-formatting attributes. 3733 unsigned FormatIdx; 3734 bool HasVAListArg; 3735 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 3736 if (!FD->getAttr<FormatAttr>()) 3737 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1, 3738 HasVAListArg ? 0 : FormatIdx + 2)); 3739 } 3740 3741 // Mark const if we don't care about errno and that is the only 3742 // thing preventing the function from being const. This allows 3743 // IRgen to use LLVM intrinsics for such functions. 3744 if (!getLangOptions().MathErrno && 3745 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 3746 if (!FD->getAttr<ConstAttr>()) 3747 FD->addAttr(::new (Context) ConstAttr()); 3748 } 3749 3750 if (Context.BuiltinInfo.isNoReturn(BuiltinID)) 3751 FD->addAttr(::new (Context) NoReturnAttr()); 3752 } 3753 3754 IdentifierInfo *Name = FD->getIdentifier(); 3755 if (!Name) 3756 return; 3757 if ((!getLangOptions().CPlusPlus && 3758 FD->getDeclContext()->isTranslationUnit()) || 3759 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 3760 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 3761 LinkageSpecDecl::lang_c)) { 3762 // Okay: this could be a libc/libm/Objective-C function we know 3763 // about. 3764 } else 3765 return; 3766 3767 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 3768 // FIXME: NSLog and NSLogv should be target specific 3769 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 3770 // FIXME: We known better than our headers. 3771 const_cast<FormatAttr *>(Format)->setType("printf"); 3772 } else 3773 FD->addAttr(::new (Context) FormatAttr("printf", 1, 3774 Name->isStr("NSLogv") ? 0 : 2)); 3775 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 3776 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 3777 // target-specific builtins, perhaps? 3778 if (!FD->getAttr<FormatAttr>()) 3779 FD->addAttr(::new (Context) FormatAttr("printf", 2, 3780 Name->isStr("vasprintf") ? 0 : 3)); 3781 } 3782} 3783 3784TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T) { 3785 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 3786 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 3787 3788 // Scope manipulation handled by caller. 3789 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 3790 D.getIdentifierLoc(), 3791 D.getIdentifier(), 3792 T); 3793 3794 if (TagType *TT = dyn_cast<TagType>(T)) { 3795 TagDecl *TD = TT->getDecl(); 3796 3797 // If the TagDecl that the TypedefDecl points to is an anonymous decl 3798 // keep track of the TypedefDecl. 3799 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 3800 TD->setTypedefForAnonDecl(NewTD); 3801 } 3802 3803 if (D.isInvalidType()) 3804 NewTD->setInvalidDecl(); 3805 return NewTD; 3806} 3807 3808 3809/// \brief Determine whether a tag with a given kind is acceptable 3810/// as a redeclaration of the given tag declaration. 3811/// 3812/// \returns true if the new tag kind is acceptable, false otherwise. 3813bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 3814 TagDecl::TagKind NewTag, 3815 SourceLocation NewTagLoc, 3816 const IdentifierInfo &Name) { 3817 // C++ [dcl.type.elab]p3: 3818 // The class-key or enum keyword present in the 3819 // elaborated-type-specifier shall agree in kind with the 3820 // declaration to which the name in theelaborated-type-specifier 3821 // refers. This rule also applies to the form of 3822 // elaborated-type-specifier that declares a class-name or 3823 // friend class since it can be construed as referring to the 3824 // definition of the class. Thus, in any 3825 // elaborated-type-specifier, the enum keyword shall be used to 3826 // refer to an enumeration (7.2), the union class-keyshall be 3827 // used to refer to a union (clause 9), and either the class or 3828 // struct class-key shall be used to refer to a class (clause 9) 3829 // declared using the class or struct class-key. 3830 TagDecl::TagKind OldTag = Previous->getTagKind(); 3831 if (OldTag == NewTag) 3832 return true; 3833 3834 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) && 3835 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) { 3836 // Warn about the struct/class tag mismatch. 3837 bool isTemplate = false; 3838 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 3839 isTemplate = Record->getDescribedClassTemplate(); 3840 3841 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 3842 << (NewTag == TagDecl::TK_class) 3843 << isTemplate << &Name 3844 << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc), 3845 OldTag == TagDecl::TK_class? "class" : "struct"); 3846 Diag(Previous->getLocation(), diag::note_previous_use); 3847 return true; 3848 } 3849 return false; 3850} 3851 3852/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 3853/// former case, Name will be non-null. In the later case, Name will be null. 3854/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 3855/// reference/declaration/definition of a tag. 3856Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 3857 SourceLocation KWLoc, const CXXScopeSpec &SS, 3858 IdentifierInfo *Name, SourceLocation NameLoc, 3859 AttributeList *Attr, AccessSpecifier AS, 3860 MultiTemplateParamsArg TemplateParameterLists, 3861 bool &OwnedDecl) { 3862 // If this is not a definition, it must have a name. 3863 assert((Name != 0 || TUK == TUK_Definition) && 3864 "Nameless record must be a definition!"); 3865 3866 OwnedDecl = false; 3867 TagDecl::TagKind Kind; 3868 switch (TagSpec) { 3869 default: assert(0 && "Unknown tag type!"); 3870 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 3871 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 3872 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 3873 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 3874 } 3875 3876 if (TUK != TUK_Reference) { 3877 if (TemplateParameterList *TemplateParams 3878 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS, 3879 (TemplateParameterList**)TemplateParameterLists.get(), 3880 TemplateParameterLists.size())) { 3881 if (TemplateParams->size() > 0) { 3882 // This is a declaration or definition of a class template (which may 3883 // be a member of another template). 3884 OwnedDecl = false; 3885 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 3886 SS, Name, NameLoc, Attr, 3887 move(TemplateParameterLists), 3888 AS); 3889 return Result.get(); 3890 } else { 3891 // FIXME: diagnose the extraneous 'template<>', once we recover 3892 // slightly better in ParseTemplate.cpp from bogus template 3893 // parameters. 3894 } 3895 } 3896 } 3897 3898 DeclContext *SearchDC = CurContext; 3899 DeclContext *DC = CurContext; 3900 NamedDecl *PrevDecl = 0; 3901 3902 bool Invalid = false; 3903 3904 if (Name && SS.isNotEmpty()) { 3905 // We have a nested-name tag ('struct foo::bar'). 3906 3907 // Check for invalid 'foo::'. 3908 if (SS.isInvalid()) { 3909 Name = 0; 3910 goto CreateNewDecl; 3911 } 3912 3913 if (RequireCompleteDeclContext(SS)) 3914 return DeclPtrTy::make((Decl *)0); 3915 3916 DC = computeDeclContext(SS, true); 3917 SearchDC = DC; 3918 // Look-up name inside 'foo::'. 3919 PrevDecl 3920 = dyn_cast_or_null<TagDecl>( 3921 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl()); 3922 3923 // A tag 'foo::bar' must already exist. 3924 if (PrevDecl == 0) { 3925 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange(); 3926 Name = 0; 3927 Invalid = true; 3928 goto CreateNewDecl; 3929 } 3930 } else if (Name) { 3931 // If this is a named struct, check to see if there was a previous forward 3932 // declaration or definition. 3933 // FIXME: We're looking into outer scopes here, even when we 3934 // shouldn't be. Doing so can result in ambiguities that we 3935 // shouldn't be diagnosing. 3936 LookupResult R = LookupName(S, Name, LookupTagName, 3937 /*RedeclarationOnly=*/(TUK != TUK_Reference)); 3938 if (R.isAmbiguous()) { 3939 DiagnoseAmbiguousLookup(R, Name, NameLoc); 3940 // FIXME: This is not best way to recover from case like: 3941 // 3942 // struct S s; 3943 // 3944 // causes needless "incomplete type" error later. 3945 Name = 0; 3946 PrevDecl = 0; 3947 Invalid = true; 3948 } 3949 else 3950 PrevDecl = R; 3951 3952 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 3953 // FIXME: This makes sure that we ignore the contexts associated 3954 // with C structs, unions, and enums when looking for a matching 3955 // tag declaration or definition. See the similar lookup tweak 3956 // in Sema::LookupName; is there a better way to deal with this? 3957 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 3958 SearchDC = SearchDC->getParent(); 3959 } 3960 } 3961 3962 if (PrevDecl && PrevDecl->isTemplateParameter()) { 3963 // Maybe we will complain about the shadowed template parameter. 3964 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 3965 // Just pretend that we didn't see the previous declaration. 3966 PrevDecl = 0; 3967 } 3968 3969 if (PrevDecl) { 3970 // Check whether the previous declaration is usable. 3971 (void)DiagnoseUseOfDecl(PrevDecl, NameLoc); 3972 3973 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 3974 // If this is a use of a previous tag, or if the tag is already declared 3975 // in the same scope (so that the definition/declaration completes or 3976 // rementions the tag), reuse the decl. 3977 if (TUK == TUK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) { 3978 // Make sure that this wasn't declared as an enum and now used as a 3979 // struct or something similar. 3980 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) { 3981 bool SafeToContinue 3982 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum && 3983 Kind != TagDecl::TK_enum); 3984 if (SafeToContinue) 3985 Diag(KWLoc, diag::err_use_with_wrong_tag) 3986 << Name 3987 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc), 3988 PrevTagDecl->getKindName()); 3989 else 3990 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 3991 Diag(PrevDecl->getLocation(), diag::note_previous_use); 3992 3993 if (SafeToContinue) 3994 Kind = PrevTagDecl->getTagKind(); 3995 else { 3996 // Recover by making this an anonymous redefinition. 3997 Name = 0; 3998 PrevDecl = 0; 3999 Invalid = true; 4000 } 4001 } 4002 4003 if (!Invalid) { 4004 // If this is a use, just return the declaration we found. 4005 4006 // FIXME: In the future, return a variant or some other clue 4007 // for the consumer of this Decl to know it doesn't own it. 4008 // For our current ASTs this shouldn't be a problem, but will 4009 // need to be changed with DeclGroups. 4010 if (TUK == TUK_Reference) 4011 return DeclPtrTy::make(PrevDecl); 4012 4013 // Diagnose attempts to redefine a tag. 4014 if (TUK == TUK_Definition) { 4015 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) { 4016 Diag(NameLoc, diag::err_redefinition) << Name; 4017 Diag(Def->getLocation(), diag::note_previous_definition); 4018 // If this is a redefinition, recover by making this 4019 // struct be anonymous, which will make any later 4020 // references get the previous definition. 4021 Name = 0; 4022 PrevDecl = 0; 4023 Invalid = true; 4024 } else { 4025 // If the type is currently being defined, complain 4026 // about a nested redefinition. 4027 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 4028 if (Tag->isBeingDefined()) { 4029 Diag(NameLoc, diag::err_nested_redefinition) << Name; 4030 Diag(PrevTagDecl->getLocation(), 4031 diag::note_previous_definition); 4032 Name = 0; 4033 PrevDecl = 0; 4034 Invalid = true; 4035 } 4036 } 4037 4038 // Okay, this is definition of a previously declared or referenced 4039 // tag PrevDecl. We're going to create a new Decl for it. 4040 } 4041 } 4042 // If we get here we have (another) forward declaration or we 4043 // have a definition. Just create a new decl. 4044 } else { 4045 // If we get here, this is a definition of a new tag type in a nested 4046 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 4047 // new decl/type. We set PrevDecl to NULL so that the entities 4048 // have distinct types. 4049 PrevDecl = 0; 4050 } 4051 // If we get here, we're going to create a new Decl. If PrevDecl 4052 // is non-NULL, it's a definition of the tag declared by 4053 // PrevDecl. If it's NULL, we have a new definition. 4054 } else { 4055 // PrevDecl is a namespace, template, or anything else 4056 // that lives in the IDNS_Tag identifier namespace. 4057 if (isDeclInScope(PrevDecl, SearchDC, S)) { 4058 // The tag name clashes with a namespace name, issue an error and 4059 // recover by making this tag be anonymous. 4060 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 4061 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4062 Name = 0; 4063 PrevDecl = 0; 4064 Invalid = true; 4065 } else { 4066 // The existing declaration isn't relevant to us; we're in a 4067 // new scope, so clear out the previous declaration. 4068 PrevDecl = 0; 4069 } 4070 } 4071 } else if (TUK == TUK_Reference && SS.isEmpty() && Name && 4072 (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) { 4073 // C++ [basic.scope.pdecl]p5: 4074 // -- for an elaborated-type-specifier of the form 4075 // 4076 // class-key identifier 4077 // 4078 // if the elaborated-type-specifier is used in the 4079 // decl-specifier-seq or parameter-declaration-clause of a 4080 // function defined in namespace scope, the identifier is 4081 // declared as a class-name in the namespace that contains 4082 // the declaration; otherwise, except as a friend 4083 // declaration, the identifier is declared in the smallest 4084 // non-class, non-function-prototype scope that contains the 4085 // declaration. 4086 // 4087 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 4088 // C structs and unions. 4089 // 4090 // GNU C also supports this behavior as part of its incomplete 4091 // enum types extension, while GNU C++ does not. 4092 // 4093 // Find the context where we'll be declaring the tag. 4094 // FIXME: We would like to maintain the current DeclContext as the 4095 // lexical context, 4096 while (SearchDC->isRecord()) 4097 SearchDC = SearchDC->getParent(); 4098 4099 // Find the scope where we'll be declaring the tag. 4100 while (S->isClassScope() || 4101 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) || 4102 ((S->getFlags() & Scope::DeclScope) == 0) || 4103 (S->getEntity() && 4104 ((DeclContext *)S->getEntity())->isTransparentContext())) 4105 S = S->getParent(); 4106 } 4107 4108CreateNewDecl: 4109 4110 // If there is an identifier, use the location of the identifier as the 4111 // location of the decl, otherwise use the location of the struct/union 4112 // keyword. 4113 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 4114 4115 // Otherwise, create a new declaration. If there is a previous 4116 // declaration of the same entity, the two will be linked via 4117 // PrevDecl. 4118 TagDecl *New; 4119 4120 if (Kind == TagDecl::TK_enum) { 4121 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 4122 // enum X { A, B, C } D; D should chain to X. 4123 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc, 4124 cast_or_null<EnumDecl>(PrevDecl)); 4125 // If this is an undefined enum, warn. 4126 if (TUK != TUK_Definition && !Invalid) { 4127 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum 4128 : diag::ext_forward_ref_enum; 4129 Diag(Loc, DK); 4130 } 4131 } else { 4132 // struct/union/class 4133 4134 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 4135 // struct X { int A; } D; D should chain to X. 4136 if (getLangOptions().CPlusPlus) 4137 // FIXME: Look for a way to use RecordDecl for simple structs. 4138 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 4139 cast_or_null<CXXRecordDecl>(PrevDecl)); 4140 else 4141 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 4142 cast_or_null<RecordDecl>(PrevDecl)); 4143 } 4144 4145 if (Kind != TagDecl::TK_enum) { 4146 // Handle #pragma pack: if the #pragma pack stack has non-default 4147 // alignment, make up a packed attribute for this decl. These 4148 // attributes are checked when the ASTContext lays out the 4149 // structure. 4150 // 4151 // It is important for implementing the correct semantics that this 4152 // happen here (in act on tag decl). The #pragma pack stack is 4153 // maintained as a result of parser callbacks which can occur at 4154 // many points during the parsing of a struct declaration (because 4155 // the #pragma tokens are effectively skipped over during the 4156 // parsing of the struct). 4157 if (unsigned Alignment = getPragmaPackAlignment()) 4158 New->addAttr(::new (Context) PackedAttr(Alignment * 8)); 4159 } 4160 4161 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) { 4162 // C++ [dcl.typedef]p3: 4163 // [...] Similarly, in a given scope, a class or enumeration 4164 // shall not be declared with the same name as a typedef-name 4165 // that is declared in that scope and refers to a type other 4166 // than the class or enumeration itself. 4167 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true); 4168 TypedefDecl *PrevTypedef = 0; 4169 if (Lookup.getKind() == LookupResult::Found) 4170 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl()); 4171 4172 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) && 4173 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) != 4174 Context.getCanonicalType(Context.getTypeDeclType(New))) { 4175 Diag(Loc, diag::err_tag_definition_of_typedef) 4176 << Context.getTypeDeclType(New) 4177 << PrevTypedef->getUnderlyingType(); 4178 Diag(PrevTypedef->getLocation(), diag::note_previous_definition); 4179 Invalid = true; 4180 } 4181 } 4182 4183 if (Invalid) 4184 New->setInvalidDecl(); 4185 4186 if (Attr) 4187 ProcessDeclAttributeList(S, New, Attr); 4188 4189 // If we're declaring or defining a tag in function prototype scope 4190 // in C, note that this type can only be used within the function. 4191 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 4192 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 4193 4194 // Set the lexical context. If the tag has a C++ scope specifier, the 4195 // lexical context will be different from the semantic context. 4196 New->setLexicalDeclContext(CurContext); 4197 4198 // Set the access specifier. 4199 if (!Invalid) 4200 SetMemberAccessSpecifier(New, PrevDecl, AS); 4201 4202 if (TUK == TUK_Definition) 4203 New->startDefinition(); 4204 4205 // If this has an identifier, add it to the scope stack. 4206 if (Name) { 4207 S = getNonFieldDeclScope(S); 4208 PushOnScopeChains(New, S); 4209 } else { 4210 CurContext->addDecl(New); 4211 } 4212 4213 // If this is the C FILE type, notify the AST context. 4214 if (IdentifierInfo *II = New->getIdentifier()) 4215 if (!New->isInvalidDecl() && 4216 New->getDeclContext()->getLookupContext()->isTranslationUnit() && 4217 II->isStr("FILE")) 4218 Context.setFILEDecl(New); 4219 4220 OwnedDecl = true; 4221 return DeclPtrTy::make(New); 4222} 4223 4224void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) { 4225 AdjustDeclIfTemplate(TagD); 4226 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 4227 4228 // Enter the tag context. 4229 PushDeclContext(S, Tag); 4230 4231 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) { 4232 FieldCollector->StartClass(); 4233 4234 if (Record->getIdentifier()) { 4235 // C++ [class]p2: 4236 // [...] The class-name is also inserted into the scope of the 4237 // class itself; this is known as the injected-class-name. For 4238 // purposes of access checking, the injected-class-name is treated 4239 // as if it were a public member name. 4240 CXXRecordDecl *InjectedClassName 4241 = CXXRecordDecl::Create(Context, Record->getTagKind(), 4242 CurContext, Record->getLocation(), 4243 Record->getIdentifier(), 4244 Record->getTagKeywordLoc(), 4245 Record); 4246 InjectedClassName->setImplicit(); 4247 InjectedClassName->setAccess(AS_public); 4248 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 4249 InjectedClassName->setDescribedClassTemplate(Template); 4250 PushOnScopeChains(InjectedClassName, S); 4251 assert(InjectedClassName->isInjectedClassName() && 4252 "Broken injected-class-name"); 4253 } 4254 } 4255} 4256 4257void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD, 4258 SourceLocation RBraceLoc) { 4259 AdjustDeclIfTemplate(TagD); 4260 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 4261 Tag->setRBraceLoc(RBraceLoc); 4262 4263 if (isa<CXXRecordDecl>(Tag)) 4264 FieldCollector->FinishClass(); 4265 4266 // Exit this scope of this tag's definition. 4267 PopDeclContext(); 4268 4269 // Notify the consumer that we've defined a tag. 4270 Consumer.HandleTagDeclDefinition(Tag); 4271} 4272 4273// Note that FieldName may be null for anonymous bitfields. 4274bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 4275 QualType FieldTy, const Expr *BitWidth) { 4276 4277 // C99 6.7.2.1p4 - verify the field type. 4278 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 4279 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) { 4280 // Handle incomplete types with specific error. 4281 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 4282 return true; 4283 if (FieldName) 4284 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 4285 << FieldName << FieldTy << BitWidth->getSourceRange(); 4286 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 4287 << FieldTy << BitWidth->getSourceRange(); 4288 } 4289 4290 // If the bit-width is type- or value-dependent, don't try to check 4291 // it now. 4292 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 4293 return false; 4294 4295 llvm::APSInt Value; 4296 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 4297 return true; 4298 4299 // Zero-width bitfield is ok for anonymous field. 4300 if (Value == 0 && FieldName) 4301 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 4302 4303 if (Value.isSigned() && Value.isNegative()) { 4304 if (FieldName) 4305 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 4306 << FieldName << Value.toString(10); 4307 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 4308 << Value.toString(10); 4309 } 4310 4311 if (!FieldTy->isDependentType()) { 4312 uint64_t TypeSize = Context.getTypeSize(FieldTy); 4313 if (Value.getZExtValue() > TypeSize) { 4314 if (FieldName) 4315 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 4316 << FieldName << (unsigned)TypeSize; 4317 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 4318 << (unsigned)TypeSize; 4319 } 4320 } 4321 4322 return false; 4323} 4324 4325/// ActOnField - Each field of a struct/union/class is passed into this in order 4326/// to create a FieldDecl object for it. 4327Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD, 4328 SourceLocation DeclStart, 4329 Declarator &D, ExprTy *BitfieldWidth) { 4330 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()), 4331 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 4332 AS_public); 4333 return DeclPtrTy::make(Res); 4334} 4335 4336/// HandleField - Analyze a field of a C struct or a C++ data member. 4337/// 4338FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 4339 SourceLocation DeclStart, 4340 Declarator &D, Expr *BitWidth, 4341 AccessSpecifier AS) { 4342 IdentifierInfo *II = D.getIdentifier(); 4343 SourceLocation Loc = DeclStart; 4344 if (II) Loc = D.getIdentifierLoc(); 4345 4346 QualType T = GetTypeForDeclarator(D, S); 4347 if (getLangOptions().CPlusPlus) 4348 CheckExtraCXXDefaultArguments(D); 4349 4350 DiagnoseFunctionSpecifiers(D); 4351 4352 if (D.getDeclSpec().isThreadSpecified()) 4353 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4354 4355 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true); 4356 4357 if (PrevDecl && PrevDecl->isTemplateParameter()) { 4358 // Maybe we will complain about the shadowed template parameter. 4359 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4360 // Just pretend that we didn't see the previous declaration. 4361 PrevDecl = 0; 4362 } 4363 4364 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 4365 PrevDecl = 0; 4366 4367 bool Mutable 4368 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 4369 SourceLocation TSSL = D.getSourceRange().getBegin(); 4370 FieldDecl *NewFD 4371 = CheckFieldDecl(II, T, Record, Loc, Mutable, BitWidth, TSSL, 4372 AS, PrevDecl, &D); 4373 if (NewFD->isInvalidDecl() && PrevDecl) { 4374 // Don't introduce NewFD into scope; there's already something 4375 // with the same name in the same scope. 4376 } else if (II) { 4377 PushOnScopeChains(NewFD, S); 4378 } else 4379 Record->addDecl(NewFD); 4380 4381 return NewFD; 4382} 4383 4384/// \brief Build a new FieldDecl and check its well-formedness. 4385/// 4386/// This routine builds a new FieldDecl given the fields name, type, 4387/// record, etc. \p PrevDecl should refer to any previous declaration 4388/// with the same name and in the same scope as the field to be 4389/// created. 4390/// 4391/// \returns a new FieldDecl. 4392/// 4393/// \todo The Declarator argument is a hack. It will be removed once 4394FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 4395 RecordDecl *Record, SourceLocation Loc, 4396 bool Mutable, Expr *BitWidth, 4397 SourceLocation TSSL, 4398 AccessSpecifier AS, NamedDecl *PrevDecl, 4399 Declarator *D) { 4400 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4401 bool InvalidDecl = false; 4402 if (D) InvalidDecl = D->isInvalidType(); 4403 4404 // If we receive a broken type, recover by assuming 'int' and 4405 // marking this declaration as invalid. 4406 if (T.isNull()) { 4407 InvalidDecl = true; 4408 T = Context.IntTy; 4409 } 4410 4411 // C99 6.7.2.1p8: A member of a structure or union may have any type other 4412 // than a variably modified type. 4413 if (T->isVariablyModifiedType()) { 4414 bool SizeIsNegative; 4415 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 4416 SizeIsNegative); 4417 if (!FixedTy.isNull()) { 4418 Diag(Loc, diag::warn_illegal_constant_array_size); 4419 T = FixedTy; 4420 } else { 4421 if (SizeIsNegative) 4422 Diag(Loc, diag::err_typecheck_negative_array_size); 4423 else 4424 Diag(Loc, diag::err_typecheck_field_variable_size); 4425 InvalidDecl = true; 4426 } 4427 } 4428 4429 // Fields can not have abstract class types 4430 if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl, 4431 AbstractFieldType)) 4432 InvalidDecl = true; 4433 4434 // If this is declared as a bit-field, check the bit-field. 4435 if (BitWidth && VerifyBitField(Loc, II, T, BitWidth)) { 4436 InvalidDecl = true; 4437 DeleteExpr(BitWidth); 4438 BitWidth = 0; 4439 } 4440 4441 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, BitWidth, 4442 Mutable, TSSL); 4443 if (InvalidDecl) 4444 NewFD->setInvalidDecl(); 4445 4446 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 4447 Diag(Loc, diag::err_duplicate_member) << II; 4448 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4449 NewFD->setInvalidDecl(); 4450 } 4451 4452 if (getLangOptions().CPlusPlus) { 4453 QualType EltTy = Context.getBaseElementType(T); 4454 4455 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 4456 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 4457 4458 if (!RDecl->hasTrivialConstructor()) 4459 cast<CXXRecordDecl>(Record)->setHasTrivialConstructor(false); 4460 if (!RDecl->hasTrivialCopyConstructor()) 4461 cast<CXXRecordDecl>(Record)->setHasTrivialCopyConstructor(false); 4462 if (!RDecl->hasTrivialCopyAssignment()) 4463 cast<CXXRecordDecl>(Record)->setHasTrivialCopyAssignment(false); 4464 if (!RDecl->hasTrivialDestructor()) 4465 cast<CXXRecordDecl>(Record)->setHasTrivialDestructor(false); 4466 4467 // C++ 9.5p1: An object of a class with a non-trivial 4468 // constructor, a non-trivial copy constructor, a non-trivial 4469 // destructor, or a non-trivial copy assignment operator 4470 // cannot be a member of a union, nor can an array of such 4471 // objects. 4472 // TODO: C++0x alters this restriction significantly. 4473 if (Record->isUnion()) { 4474 // We check for copy constructors before constructors 4475 // because otherwise we'll never get complaints about 4476 // copy constructors. 4477 4478 const CXXSpecialMember invalid = (CXXSpecialMember) -1; 4479 4480 CXXSpecialMember member; 4481 if (!RDecl->hasTrivialCopyConstructor()) 4482 member = CXXCopyConstructor; 4483 else if (!RDecl->hasTrivialConstructor()) 4484 member = CXXDefaultConstructor; 4485 else if (!RDecl->hasTrivialCopyAssignment()) 4486 member = CXXCopyAssignment; 4487 else if (!RDecl->hasTrivialDestructor()) 4488 member = CXXDestructor; 4489 else 4490 member = invalid; 4491 4492 if (member != invalid) { 4493 Diag(Loc, diag::err_illegal_union_member) << Name << member; 4494 DiagnoseNontrivial(RT, member); 4495 NewFD->setInvalidDecl(); 4496 } 4497 } 4498 } 4499 } 4500 4501 if (getLangOptions().CPlusPlus && !T->isPODType()) 4502 cast<CXXRecordDecl>(Record)->setPOD(false); 4503 4504 // FIXME: We need to pass in the attributes given an AST 4505 // representation, not a parser representation. 4506 if (D) 4507 // FIXME: What to pass instead of TUScope? 4508 ProcessDeclAttributes(TUScope, NewFD, *D); 4509 4510 if (T.isObjCGCWeak()) 4511 Diag(Loc, diag::warn_attribute_weak_on_field); 4512 4513 NewFD->setAccess(AS); 4514 4515 // C++ [dcl.init.aggr]p1: 4516 // An aggregate is an array or a class (clause 9) with [...] no 4517 // private or protected non-static data members (clause 11). 4518 // A POD must be an aggregate. 4519 if (getLangOptions().CPlusPlus && 4520 (AS == AS_private || AS == AS_protected)) { 4521 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 4522 CXXRecord->setAggregate(false); 4523 CXXRecord->setPOD(false); 4524 } 4525 4526 return NewFD; 4527} 4528 4529/// DiagnoseNontrivial - Given that a class has a non-trivial 4530/// special member, figure out why. 4531void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 4532 QualType QT(T, 0U); 4533 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 4534 4535 // Check whether the member was user-declared. 4536 switch (member) { 4537 case CXXDefaultConstructor: 4538 if (RD->hasUserDeclaredConstructor()) { 4539 typedef CXXRecordDecl::ctor_iterator ctor_iter; 4540 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce; ++ci) 4541 if (!ci->isImplicitlyDefined(Context)) { 4542 SourceLocation CtorLoc = ci->getLocation(); 4543 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 4544 return; 4545 } 4546 4547 assert(0 && "found no user-declared constructors"); 4548 return; 4549 } 4550 break; 4551 4552 case CXXCopyConstructor: 4553 if (RD->hasUserDeclaredCopyConstructor()) { 4554 SourceLocation CtorLoc = 4555 RD->getCopyConstructor(Context, 0)->getLocation(); 4556 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 4557 return; 4558 } 4559 break; 4560 4561 case CXXCopyAssignment: 4562 if (RD->hasUserDeclaredCopyAssignment()) { 4563 // FIXME: this should use the location of the copy 4564 // assignment, not the type. 4565 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 4566 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 4567 return; 4568 } 4569 break; 4570 4571 case CXXDestructor: 4572 if (RD->hasUserDeclaredDestructor()) { 4573 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation(); 4574 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 4575 return; 4576 } 4577 break; 4578 } 4579 4580 typedef CXXRecordDecl::base_class_iterator base_iter; 4581 4582 // Virtual bases and members inhibit trivial copying/construction, 4583 // but not trivial destruction. 4584 if (member != CXXDestructor) { 4585 // Check for virtual bases. vbases includes indirect virtual bases, 4586 // so we just iterate through the direct bases. 4587 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 4588 if (bi->isVirtual()) { 4589 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 4590 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 4591 return; 4592 } 4593 4594 // Check for virtual methods. 4595 typedef CXXRecordDecl::method_iterator meth_iter; 4596 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 4597 ++mi) { 4598 if (mi->isVirtual()) { 4599 SourceLocation MLoc = mi->getSourceRange().getBegin(); 4600 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 4601 return; 4602 } 4603 } 4604 } 4605 4606 bool (CXXRecordDecl::*hasTrivial)() const; 4607 switch (member) { 4608 case CXXDefaultConstructor: 4609 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break; 4610 case CXXCopyConstructor: 4611 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 4612 case CXXCopyAssignment: 4613 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 4614 case CXXDestructor: 4615 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 4616 default: 4617 assert(0 && "unexpected special member"); return; 4618 } 4619 4620 // Check for nontrivial bases (and recurse). 4621 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 4622 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 4623 assert(BaseRT); 4624 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 4625 if (!(BaseRecTy->*hasTrivial)()) { 4626 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 4627 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 4628 DiagnoseNontrivial(BaseRT, member); 4629 return; 4630 } 4631 } 4632 4633 // Check for nontrivial members (and recurse). 4634 typedef RecordDecl::field_iterator field_iter; 4635 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 4636 ++fi) { 4637 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 4638 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 4639 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 4640 4641 if (!(EltRD->*hasTrivial)()) { 4642 SourceLocation FLoc = (*fi)->getLocation(); 4643 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 4644 DiagnoseNontrivial(EltRT, member); 4645 return; 4646 } 4647 } 4648 } 4649 4650 assert(0 && "found no explanation for non-trivial member"); 4651} 4652 4653/// TranslateIvarVisibility - Translate visibility from a token ID to an 4654/// AST enum value. 4655static ObjCIvarDecl::AccessControl 4656TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 4657 switch (ivarVisibility) { 4658 default: assert(0 && "Unknown visitibility kind"); 4659 case tok::objc_private: return ObjCIvarDecl::Private; 4660 case tok::objc_public: return ObjCIvarDecl::Public; 4661 case tok::objc_protected: return ObjCIvarDecl::Protected; 4662 case tok::objc_package: return ObjCIvarDecl::Package; 4663 } 4664} 4665 4666/// ActOnIvar - Each ivar field of an objective-c class is passed into this 4667/// in order to create an IvarDecl object for it. 4668Sema::DeclPtrTy Sema::ActOnIvar(Scope *S, 4669 SourceLocation DeclStart, 4670 DeclPtrTy IntfDecl, 4671 Declarator &D, ExprTy *BitfieldWidth, 4672 tok::ObjCKeywordKind Visibility) { 4673 4674 IdentifierInfo *II = D.getIdentifier(); 4675 Expr *BitWidth = (Expr*)BitfieldWidth; 4676 SourceLocation Loc = DeclStart; 4677 if (II) Loc = D.getIdentifierLoc(); 4678 4679 // FIXME: Unnamed fields can be handled in various different ways, for 4680 // example, unnamed unions inject all members into the struct namespace! 4681 4682 QualType T = GetTypeForDeclarator(D, S); 4683 4684 if (BitWidth) { 4685 // 6.7.2.1p3, 6.7.2.1p4 4686 if (VerifyBitField(Loc, II, T, BitWidth)) { 4687 D.setInvalidType(); 4688 DeleteExpr(BitWidth); 4689 BitWidth = 0; 4690 } 4691 } else { 4692 // Not a bitfield. 4693 4694 // validate II. 4695 4696 } 4697 4698 // C99 6.7.2.1p8: A member of a structure or union may have any type other 4699 // than a variably modified type. 4700 if (T->isVariablyModifiedType()) { 4701 Diag(Loc, diag::err_typecheck_ivar_variable_size); 4702 D.setInvalidType(); 4703 } 4704 4705 // Get the visibility (access control) for this ivar. 4706 ObjCIvarDecl::AccessControl ac = 4707 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 4708 : ObjCIvarDecl::None; 4709 // Must set ivar's DeclContext to its enclosing interface. 4710 Decl *EnclosingDecl = IntfDecl.getAs<Decl>(); 4711 DeclContext *EnclosingContext; 4712 if (ObjCImplementationDecl *IMPDecl = 4713 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 4714 // Case of ivar declared in an implementation. Context is that of its class. 4715 ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface(); 4716 assert(IDecl && "No class- ActOnIvar"); 4717 EnclosingContext = cast_or_null<DeclContext>(IDecl); 4718 } 4719 else 4720 EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl); 4721 assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar"); 4722 4723 // Construct the decl. 4724 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, 4725 EnclosingContext, Loc, II, T,ac, 4726 (Expr *)BitfieldWidth); 4727 4728 if (II) { 4729 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true); 4730 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 4731 && !isa<TagDecl>(PrevDecl)) { 4732 Diag(Loc, diag::err_duplicate_member) << II; 4733 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4734 NewID->setInvalidDecl(); 4735 } 4736 } 4737 4738 // Process attributes attached to the ivar. 4739 ProcessDeclAttributes(S, NewID, D); 4740 4741 if (D.isInvalidType()) 4742 NewID->setInvalidDecl(); 4743 4744 if (II) { 4745 // FIXME: When interfaces are DeclContexts, we'll need to add 4746 // these to the interface. 4747 S->AddDecl(DeclPtrTy::make(NewID)); 4748 IdResolver.AddDecl(NewID); 4749 } 4750 4751 return DeclPtrTy::make(NewID); 4752} 4753 4754void Sema::ActOnFields(Scope* S, 4755 SourceLocation RecLoc, DeclPtrTy RecDecl, 4756 DeclPtrTy *Fields, unsigned NumFields, 4757 SourceLocation LBrac, SourceLocation RBrac, 4758 AttributeList *Attr) { 4759 Decl *EnclosingDecl = RecDecl.getAs<Decl>(); 4760 assert(EnclosingDecl && "missing record or interface decl"); 4761 4762 // If the decl this is being inserted into is invalid, then it may be a 4763 // redeclaration or some other bogus case. Don't try to add fields to it. 4764 if (EnclosingDecl->isInvalidDecl()) { 4765 // FIXME: Deallocate fields? 4766 return; 4767 } 4768 4769 4770 // Verify that all the fields are okay. 4771 unsigned NumNamedMembers = 0; 4772 llvm::SmallVector<FieldDecl*, 32> RecFields; 4773 4774 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 4775 for (unsigned i = 0; i != NumFields; ++i) { 4776 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>()); 4777 4778 // Get the type for the field. 4779 Type *FDTy = FD->getType().getTypePtr(); 4780 4781 if (!FD->isAnonymousStructOrUnion()) { 4782 // Remember all fields written by the user. 4783 RecFields.push_back(FD); 4784 } 4785 4786 // If the field is already invalid for some reason, don't emit more 4787 // diagnostics about it. 4788 if (FD->isInvalidDecl()) 4789 continue; 4790 4791 // C99 6.7.2.1p2: 4792 // A structure or union shall not contain a member with 4793 // incomplete or function type (hence, a structure shall not 4794 // contain an instance of itself, but may contain a pointer to 4795 // an instance of itself), except that the last member of a 4796 // structure with more than one named member may have incomplete 4797 // array type; such a structure (and any union containing, 4798 // possibly recursively, a member that is such a structure) 4799 // shall not be a member of a structure or an element of an 4800 // array. 4801 if (FDTy->isFunctionType()) { 4802 // Field declared as a function. 4803 Diag(FD->getLocation(), diag::err_field_declared_as_function) 4804 << FD->getDeclName(); 4805 FD->setInvalidDecl(); 4806 EnclosingDecl->setInvalidDecl(); 4807 continue; 4808 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 && 4809 Record && Record->isStruct()) { 4810 // Flexible array member. 4811 if (NumNamedMembers < 1) { 4812 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 4813 << FD->getDeclName(); 4814 FD->setInvalidDecl(); 4815 EnclosingDecl->setInvalidDecl(); 4816 continue; 4817 } 4818 // Okay, we have a legal flexible array member at the end of the struct. 4819 if (Record) 4820 Record->setHasFlexibleArrayMember(true); 4821 } else if (!FDTy->isDependentType() && 4822 RequireCompleteType(FD->getLocation(), FD->getType(), 4823 diag::err_field_incomplete)) { 4824 // Incomplete type 4825 FD->setInvalidDecl(); 4826 EnclosingDecl->setInvalidDecl(); 4827 continue; 4828 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 4829 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 4830 // If this is a member of a union, then entire union becomes "flexible". 4831 if (Record && Record->isUnion()) { 4832 Record->setHasFlexibleArrayMember(true); 4833 } else { 4834 // If this is a struct/class and this is not the last element, reject 4835 // it. Note that GCC supports variable sized arrays in the middle of 4836 // structures. 4837 if (i != NumFields-1) 4838 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 4839 << FD->getDeclName() << FD->getType(); 4840 else { 4841 // We support flexible arrays at the end of structs in 4842 // other structs as an extension. 4843 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 4844 << FD->getDeclName(); 4845 if (Record) 4846 Record->setHasFlexibleArrayMember(true); 4847 } 4848 } 4849 } 4850 if (Record && FDTTy->getDecl()->hasObjectMember()) 4851 Record->setHasObjectMember(true); 4852 } else if (FDTy->isObjCInterfaceType()) { 4853 /// A field cannot be an Objective-c object 4854 Diag(FD->getLocation(), diag::err_statically_allocated_object); 4855 FD->setInvalidDecl(); 4856 EnclosingDecl->setInvalidDecl(); 4857 continue; 4858 } 4859 else if (getLangOptions().ObjC1 && 4860 getLangOptions().getGCMode() != LangOptions::NonGC && 4861 Record && 4862 (FD->getType()->isObjCObjectPointerType() || 4863 FD->getType().isObjCGCStrong())) 4864 Record->setHasObjectMember(true); 4865 // Keep track of the number of named members. 4866 if (FD->getIdentifier()) 4867 ++NumNamedMembers; 4868 } 4869 4870 // Okay, we successfully defined 'Record'. 4871 if (Record) { 4872 Record->completeDefinition(Context); 4873 } else { 4874 ObjCIvarDecl **ClsFields = 4875 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 4876 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 4877 ID->setIVarList(ClsFields, RecFields.size(), Context); 4878 ID->setLocEnd(RBrac); 4879 // Add ivar's to class's DeclContext. 4880 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 4881 ClsFields[i]->setLexicalDeclContext(ID); 4882 ID->addDecl(ClsFields[i]); 4883 } 4884 // Must enforce the rule that ivars in the base classes may not be 4885 // duplicates. 4886 if (ID->getSuperClass()) { 4887 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 4888 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 4889 ObjCIvarDecl* Ivar = (*IVI); 4890 4891 if (IdentifierInfo *II = Ivar->getIdentifier()) { 4892 ObjCIvarDecl* prevIvar = 4893 ID->getSuperClass()->lookupInstanceVariable(II); 4894 if (prevIvar) { 4895 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 4896 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 4897 } 4898 } 4899 } 4900 } 4901 } else if (ObjCImplementationDecl *IMPDecl = 4902 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 4903 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 4904 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 4905 // Ivar declared in @implementation never belongs to the implementation. 4906 // Only it is in implementation's lexical context. 4907 ClsFields[I]->setLexicalDeclContext(IMPDecl); 4908 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 4909 } 4910 } 4911 4912 if (Attr) 4913 ProcessDeclAttributeList(S, Record, Attr); 4914} 4915 4916EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 4917 EnumConstantDecl *LastEnumConst, 4918 SourceLocation IdLoc, 4919 IdentifierInfo *Id, 4920 ExprArg val) { 4921 Expr *Val = (Expr *)val.get(); 4922 4923 llvm::APSInt EnumVal(32); 4924 QualType EltTy; 4925 if (Val && !Val->isTypeDependent()) { 4926 // Make sure to promote the operand type to int. 4927 UsualUnaryConversions(Val); 4928 if (Val != val.get()) { 4929 val.release(); 4930 val = Val; 4931 } 4932 4933 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 4934 SourceLocation ExpLoc; 4935 if (!Val->isValueDependent() && 4936 VerifyIntegerConstantExpression(Val, &EnumVal)) { 4937 Val = 0; 4938 } else { 4939 EltTy = Val->getType(); 4940 } 4941 } 4942 4943 if (!Val) { 4944 if (LastEnumConst) { 4945 // Assign the last value + 1. 4946 EnumVal = LastEnumConst->getInitVal(); 4947 ++EnumVal; 4948 4949 // Check for overflow on increment. 4950 if (EnumVal < LastEnumConst->getInitVal()) 4951 Diag(IdLoc, diag::warn_enum_value_overflow); 4952 4953 EltTy = LastEnumConst->getType(); 4954 } else { 4955 // First value, set to zero. 4956 EltTy = Context.IntTy; 4957 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 4958 } 4959 } 4960 4961 val.release(); 4962 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 4963 Val, EnumVal); 4964} 4965 4966 4967Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl, 4968 DeclPtrTy lastEnumConst, 4969 SourceLocation IdLoc, 4970 IdentifierInfo *Id, 4971 SourceLocation EqualLoc, ExprTy *val) { 4972 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>()); 4973 EnumConstantDecl *LastEnumConst = 4974 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>()); 4975 Expr *Val = static_cast<Expr*>(val); 4976 4977 // The scope passed in may not be a decl scope. Zip up the scope tree until 4978 // we find one that is. 4979 S = getNonFieldDeclScope(S); 4980 4981 // Verify that there isn't already something declared with this name in this 4982 // scope. 4983 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName); 4984 if (PrevDecl && PrevDecl->isTemplateParameter()) { 4985 // Maybe we will complain about the shadowed template parameter. 4986 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 4987 // Just pretend that we didn't see the previous declaration. 4988 PrevDecl = 0; 4989 } 4990 4991 if (PrevDecl) { 4992 // When in C++, we may get a TagDecl with the same name; in this case the 4993 // enum constant will 'hide' the tag. 4994 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 4995 "Received TagDecl when not in C++!"); 4996 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 4997 if (isa<EnumConstantDecl>(PrevDecl)) 4998 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 4999 else 5000 Diag(IdLoc, diag::err_redefinition) << Id; 5001 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5002 if (Val) Val->Destroy(Context); 5003 return DeclPtrTy(); 5004 } 5005 } 5006 5007 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst, 5008 IdLoc, Id, Owned(Val)); 5009 5010 // Register this decl in the current scope stack. 5011 if (New) 5012 PushOnScopeChains(New, S); 5013 5014 return DeclPtrTy::make(New); 5015} 5016 5017void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 5018 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX, 5019 DeclPtrTy *Elements, unsigned NumElements) { 5020 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>()); 5021 QualType EnumType = Context.getTypeDeclType(Enum); 5022 5023 // TODO: If the result value doesn't fit in an int, it must be a long or long 5024 // long value. ISO C does not support this, but GCC does as an extension, 5025 // emit a warning. 5026 unsigned IntWidth = Context.Target.getIntWidth(); 5027 5028 // Verify that all the values are okay, compute the size of the values, and 5029 // reverse the list. 5030 unsigned NumNegativeBits = 0; 5031 unsigned NumPositiveBits = 0; 5032 5033 // Keep track of whether all elements have type int. 5034 bool AllElementsInt = true; 5035 5036 for (unsigned i = 0; i != NumElements; ++i) { 5037 EnumConstantDecl *ECD = 5038 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 5039 if (!ECD) continue; // Already issued a diagnostic. 5040 5041 // If the enum value doesn't fit in an int, emit an extension warning. 5042 const llvm::APSInt &InitVal = ECD->getInitVal(); 5043 assert(InitVal.getBitWidth() >= IntWidth && 5044 "Should have promoted value to int"); 5045 if (InitVal.getBitWidth() > IntWidth) { 5046 llvm::APSInt V(InitVal); 5047 V.trunc(IntWidth); 5048 V.extend(InitVal.getBitWidth()); 5049 if (V != InitVal) 5050 Diag(ECD->getLocation(), diag::ext_enum_value_not_int) 5051 << InitVal.toString(10); 5052 } 5053 5054 // Keep track of the size of positive and negative values. 5055 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 5056 NumPositiveBits = std::max(NumPositiveBits, 5057 (unsigned)InitVal.getActiveBits()); 5058 else 5059 NumNegativeBits = std::max(NumNegativeBits, 5060 (unsigned)InitVal.getMinSignedBits()); 5061 5062 // Keep track of whether every enum element has type int (very commmon). 5063 if (AllElementsInt) 5064 AllElementsInt = ECD->getType() == Context.IntTy; 5065 } 5066 5067 // Figure out the type that should be used for this enum. 5068 // FIXME: Support attribute(packed) on enums and -fshort-enums. 5069 QualType BestType; 5070 unsigned BestWidth; 5071 5072 if (NumNegativeBits) { 5073 // If there is a negative value, figure out the smallest integer type (of 5074 // int/long/longlong) that fits. 5075 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 5076 BestType = Context.IntTy; 5077 BestWidth = IntWidth; 5078 } else { 5079 BestWidth = Context.Target.getLongWidth(); 5080 5081 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 5082 BestType = Context.LongTy; 5083 else { 5084 BestWidth = Context.Target.getLongLongWidth(); 5085 5086 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 5087 Diag(Enum->getLocation(), diag::warn_enum_too_large); 5088 BestType = Context.LongLongTy; 5089 } 5090 } 5091 } else { 5092 // If there is no negative value, figure out which of uint, ulong, ulonglong 5093 // fits. 5094 if (NumPositiveBits <= IntWidth) { 5095 BestType = Context.UnsignedIntTy; 5096 BestWidth = IntWidth; 5097 } else if (NumPositiveBits <= 5098 (BestWidth = Context.Target.getLongWidth())) { 5099 BestType = Context.UnsignedLongTy; 5100 } else { 5101 BestWidth = Context.Target.getLongLongWidth(); 5102 assert(NumPositiveBits <= BestWidth && 5103 "How could an initializer get larger than ULL?"); 5104 BestType = Context.UnsignedLongLongTy; 5105 } 5106 } 5107 5108 // Loop over all of the enumerator constants, changing their types to match 5109 // the type of the enum if needed. 5110 for (unsigned i = 0; i != NumElements; ++i) { 5111 EnumConstantDecl *ECD = 5112 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 5113 if (!ECD) continue; // Already issued a diagnostic. 5114 5115 // Standard C says the enumerators have int type, but we allow, as an 5116 // extension, the enumerators to be larger than int size. If each 5117 // enumerator value fits in an int, type it as an int, otherwise type it the 5118 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 5119 // that X has type 'int', not 'unsigned'. 5120 if (ECD->getType() == Context.IntTy) { 5121 // Make sure the init value is signed. 5122 llvm::APSInt IV = ECD->getInitVal(); 5123 IV.setIsSigned(true); 5124 ECD->setInitVal(IV); 5125 5126 if (getLangOptions().CPlusPlus) 5127 // C++ [dcl.enum]p4: Following the closing brace of an 5128 // enum-specifier, each enumerator has the type of its 5129 // enumeration. 5130 ECD->setType(EnumType); 5131 continue; // Already int type. 5132 } 5133 5134 // Determine whether the value fits into an int. 5135 llvm::APSInt InitVal = ECD->getInitVal(); 5136 bool FitsInInt; 5137 if (InitVal.isUnsigned() || !InitVal.isNegative()) 5138 FitsInInt = InitVal.getActiveBits() < IntWidth; 5139 else 5140 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 5141 5142 // If it fits into an integer type, force it. Otherwise force it to match 5143 // the enum decl type. 5144 QualType NewTy; 5145 unsigned NewWidth; 5146 bool NewSign; 5147 if (FitsInInt) { 5148 NewTy = Context.IntTy; 5149 NewWidth = IntWidth; 5150 NewSign = true; 5151 } else if (ECD->getType() == BestType) { 5152 // Already the right type! 5153 if (getLangOptions().CPlusPlus) 5154 // C++ [dcl.enum]p4: Following the closing brace of an 5155 // enum-specifier, each enumerator has the type of its 5156 // enumeration. 5157 ECD->setType(EnumType); 5158 continue; 5159 } else { 5160 NewTy = BestType; 5161 NewWidth = BestWidth; 5162 NewSign = BestType->isSignedIntegerType(); 5163 } 5164 5165 // Adjust the APSInt value. 5166 InitVal.extOrTrunc(NewWidth); 5167 InitVal.setIsSigned(NewSign); 5168 ECD->setInitVal(InitVal); 5169 5170 // Adjust the Expr initializer and type. 5171 if (ECD->getInitExpr()) 5172 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, 5173 CastExpr::CK_Unknown, 5174 ECD->getInitExpr(), 5175 /*isLvalue=*/false)); 5176 if (getLangOptions().CPlusPlus) 5177 // C++ [dcl.enum]p4: Following the closing brace of an 5178 // enum-specifier, each enumerator has the type of its 5179 // enumeration. 5180 ECD->setType(EnumType); 5181 else 5182 ECD->setType(NewTy); 5183 } 5184 5185 Enum->completeDefinition(Context, BestType); 5186} 5187 5188Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 5189 ExprArg expr) { 5190 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>()); 5191 5192 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 5193 Loc, AsmString); 5194 CurContext->addDecl(New); 5195 return DeclPtrTy::make(New); 5196} 5197 5198void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 5199 SourceLocation PragmaLoc, 5200 SourceLocation NameLoc) { 5201 Decl *PrevDecl = LookupName(TUScope, Name, LookupOrdinaryName); 5202 5203 if (PrevDecl) { 5204 PrevDecl->addAttr(::new (Context) WeakAttr()); 5205 } else { 5206 (void)WeakUndeclaredIdentifiers.insert( 5207 std::pair<IdentifierInfo*,WeakInfo> 5208 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 5209 } 5210} 5211 5212void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 5213 IdentifierInfo* AliasName, 5214 SourceLocation PragmaLoc, 5215 SourceLocation NameLoc, 5216 SourceLocation AliasNameLoc) { 5217 Decl *PrevDecl = LookupName(TUScope, AliasName, LookupOrdinaryName); 5218 WeakInfo W = WeakInfo(Name, NameLoc); 5219 5220 if (PrevDecl) { 5221 if (!PrevDecl->hasAttr<AliasAttr>()) 5222 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 5223 DeclApplyPragmaWeak(TUScope, ND, W); 5224 } else { 5225 (void)WeakUndeclaredIdentifiers.insert( 5226 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 5227 } 5228} 5229